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___float128:
136   case tok::kw_wchar_t:
137   case tok::kw_bool:
138   case tok::kw___underlying_type:
139   case tok::kw___auto_type:
140     return true;
141 
142   case tok::annot_typename:
143   case tok::kw_char16_t:
144   case tok::kw_char32_t:
145   case tok::kw_typeof:
146   case tok::annot_decltype:
147   case tok::kw_decltype:
148     return getLangOpts().CPlusPlus;
149 
150   default:
151     break;
152   }
153 
154   return false;
155 }
156 
157 namespace {
158 enum class UnqualifiedTypeNameLookupResult {
159   NotFound,
160   FoundNonType,
161   FoundType
162 };
163 } // end anonymous namespace
164 
165 /// \brief Tries to perform unqualified lookup of the type decls in bases for
166 /// dependent class.
167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
168 /// type decl, \a FoundType if only type decls are found.
169 static UnqualifiedTypeNameLookupResult
170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
171                                 SourceLocation NameLoc,
172                                 const CXXRecordDecl *RD) {
173   if (!RD->hasDefinition())
174     return UnqualifiedTypeNameLookupResult::NotFound;
175   // Look for type decls in base classes.
176   UnqualifiedTypeNameLookupResult FoundTypeDecl =
177       UnqualifiedTypeNameLookupResult::NotFound;
178   for (const auto &Base : RD->bases()) {
179     const CXXRecordDecl *BaseRD = nullptr;
180     if (auto *BaseTT = Base.getType()->getAs<TagType>())
181       BaseRD = BaseTT->getAsCXXRecordDecl();
182     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
183       // Look for type decls in dependent base classes that have known primary
184       // templates.
185       if (!TST || !TST->isDependentType())
186         continue;
187       auto *TD = TST->getTemplateName().getAsTemplateDecl();
188       if (!TD)
189         continue;
190       if (auto *BasePrimaryTemplate =
191           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
192         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
193           BaseRD = BasePrimaryTemplate;
194         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
195           if (const ClassTemplatePartialSpecializationDecl *PS =
196                   CTD->findPartialSpecialization(Base.getType()))
197             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
198               BaseRD = PS;
199         }
200       }
201     }
202     if (BaseRD) {
203       for (NamedDecl *ND : BaseRD->lookup(&II)) {
204         if (!isa<TypeDecl>(ND))
205           return UnqualifiedTypeNameLookupResult::FoundNonType;
206         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
207       }
208       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
209         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
210         case UnqualifiedTypeNameLookupResult::FoundNonType:
211           return UnqualifiedTypeNameLookupResult::FoundNonType;
212         case UnqualifiedTypeNameLookupResult::FoundType:
213           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214           break;
215         case UnqualifiedTypeNameLookupResult::NotFound:
216           break;
217         }
218       }
219     }
220   }
221 
222   return FoundTypeDecl;
223 }
224 
225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
226                                                       const IdentifierInfo &II,
227                                                       SourceLocation NameLoc) {
228   // Lookup in the parent class template context, if any.
229   const CXXRecordDecl *RD = nullptr;
230   UnqualifiedTypeNameLookupResult FoundTypeDecl =
231       UnqualifiedTypeNameLookupResult::NotFound;
232   for (DeclContext *DC = S.CurContext;
233        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
234        DC = DC->getParent()) {
235     // Look for type decls in dependent base classes that have known primary
236     // templates.
237     RD = dyn_cast<CXXRecordDecl>(DC);
238     if (RD && RD->getDescribedClassTemplate())
239       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
240   }
241   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
242     return nullptr;
243 
244   // We found some types in dependent base classes.  Recover as if the user
245   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
246   // lookup during template instantiation.
247   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
248 
249   ASTContext &Context = S.Context;
250   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
251                                           cast<Type>(Context.getRecordType(RD)));
252   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
253 
254   CXXScopeSpec SS;
255   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
256 
257   TypeLocBuilder Builder;
258   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
259   DepTL.setNameLoc(NameLoc);
260   DepTL.setElaboratedKeywordLoc(SourceLocation());
261   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
262   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
263 }
264 
265 /// \brief If the identifier refers to a type name within this scope,
266 /// return the declaration of that type.
267 ///
268 /// This routine performs ordinary name lookup of the identifier II
269 /// within the given scope, with optional C++ scope specifier SS, to
270 /// determine whether the name refers to a type. If so, returns an
271 /// opaque pointer (actually a QualType) corresponding to that
272 /// type. Otherwise, returns NULL.
273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
274                              Scope *S, CXXScopeSpec *SS,
275                              bool isClassName, bool HasTrailingDot,
276                              ParsedType ObjectTypePtr,
277                              bool IsCtorOrDtorName,
278                              bool WantNontrivialTypeSourceInfo,
279                              bool IsClassTemplateDeductionContext,
280                              IdentifierInfo **CorrectedII) {
281   // FIXME: Consider allowing this outside C++1z mode as an extension.
282   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
284                               !isClassName && !HasTrailingDot;
285 
286   // Determine where we will perform name lookup.
287   DeclContext *LookupCtx = nullptr;
288   if (ObjectTypePtr) {
289     QualType ObjectType = ObjectTypePtr.get();
290     if (ObjectType->isRecordType())
291       LookupCtx = computeDeclContext(ObjectType);
292   } else if (SS && SS->isNotEmpty()) {
293     LookupCtx = computeDeclContext(*SS, false);
294 
295     if (!LookupCtx) {
296       if (isDependentScopeSpecifier(*SS)) {
297         // C++ [temp.res]p3:
298         //   A qualified-id that refers to a type and in which the
299         //   nested-name-specifier depends on a template-parameter (14.6.2)
300         //   shall be prefixed by the keyword typename to indicate that the
301         //   qualified-id denotes a type, forming an
302         //   elaborated-type-specifier (7.1.5.3).
303         //
304         // We therefore do not perform any name lookup if the result would
305         // refer to a member of an unknown specialization.
306         if (!isClassName && !IsCtorOrDtorName)
307           return nullptr;
308 
309         // We know from the grammar that this name refers to a type,
310         // so build a dependent node to describe the type.
311         if (WantNontrivialTypeSourceInfo)
312           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
313 
314         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
315         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
316                                        II, NameLoc);
317         return ParsedType::make(T);
318       }
319 
320       return nullptr;
321     }
322 
323     if (!LookupCtx->isDependentContext() &&
324         RequireCompleteDeclContext(*SS, LookupCtx))
325       return nullptr;
326   }
327 
328   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
329   // lookup for class-names.
330   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
331                                       LookupOrdinaryName;
332   LookupResult Result(*this, &II, NameLoc, Kind);
333   if (LookupCtx) {
334     // Perform "qualified" name lookup into the declaration context we
335     // computed, which is either the type of the base of a member access
336     // expression or the declaration context associated with a prior
337     // nested-name-specifier.
338     LookupQualifiedName(Result, LookupCtx);
339 
340     if (ObjectTypePtr && Result.empty()) {
341       // C++ [basic.lookup.classref]p3:
342       //   If the unqualified-id is ~type-name, the type-name is looked up
343       //   in the context of the entire postfix-expression. If the type T of
344       //   the object expression is of a class type C, the type-name is also
345       //   looked up in the scope of class C. At least one of the lookups shall
346       //   find a name that refers to (possibly cv-qualified) T.
347       LookupName(Result, S);
348     }
349   } else {
350     // Perform unqualified name lookup.
351     LookupName(Result, S);
352 
353     // For unqualified lookup in a class template in MSVC mode, look into
354     // dependent base classes where the primary class template is known.
355     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
356       if (ParsedType TypeInBase =
357               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
358         return TypeInBase;
359     }
360   }
361 
362   NamedDecl *IIDecl = nullptr;
363   switch (Result.getResultKind()) {
364   case LookupResult::NotFound:
365   case LookupResult::NotFoundInCurrentInstantiation:
366     if (CorrectedII) {
367       TypoCorrection Correction =
368           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
369                       llvm::make_unique<TypeNameValidatorCCC>(
370                           true, isClassName, AllowDeducedTemplate),
371                       CTK_ErrorRecovery);
372       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
373       TemplateTy Template;
374       bool MemberOfUnknownSpecialization;
375       UnqualifiedId TemplateName;
376       TemplateName.setIdentifier(NewII, NameLoc);
377       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
378       CXXScopeSpec NewSS, *NewSSPtr = SS;
379       if (SS && NNS) {
380         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
381         NewSSPtr = &NewSS;
382       }
383       if (Correction && (NNS || NewII != &II) &&
384           // Ignore a correction to a template type as the to-be-corrected
385           // identifier is not a template (typo correction for template names
386           // is handled elsewhere).
387           !(getLangOpts().CPlusPlus && NewSSPtr &&
388             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
389                            Template, MemberOfUnknownSpecialization))) {
390         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
391                                     isClassName, HasTrailingDot, ObjectTypePtr,
392                                     IsCtorOrDtorName,
393                                     WantNontrivialTypeSourceInfo,
394                                     IsClassTemplateDeductionContext);
395         if (Ty) {
396           diagnoseTypo(Correction,
397                        PDiag(diag::err_unknown_type_or_class_name_suggest)
398                          << Result.getLookupName() << isClassName);
399           if (SS && NNS)
400             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
401           *CorrectedII = NewII;
402           return Ty;
403         }
404       }
405     }
406     // If typo correction failed or was not performed, fall through
407     LLVM_FALLTHROUGH;
408   case LookupResult::FoundOverloaded:
409   case LookupResult::FoundUnresolvedValue:
410     Result.suppressDiagnostics();
411     return nullptr;
412 
413   case LookupResult::Ambiguous:
414     // Recover from type-hiding ambiguities by hiding the type.  We'll
415     // do the lookup again when looking for an object, and we can
416     // diagnose the error then.  If we don't do this, then the error
417     // about hiding the type will be immediately followed by an error
418     // that only makes sense if the identifier was treated like a type.
419     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
420       Result.suppressDiagnostics();
421       return nullptr;
422     }
423 
424     // Look to see if we have a type anywhere in the list of results.
425     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
426          Res != ResEnd; ++Res) {
427       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
428           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
429         if (!IIDecl ||
430             (*Res)->getLocation().getRawEncoding() <
431               IIDecl->getLocation().getRawEncoding())
432           IIDecl = *Res;
433       }
434     }
435 
436     if (!IIDecl) {
437       // None of the entities we found is a type, so there is no way
438       // to even assume that the result is a type. In this case, don't
439       // complain about the ambiguity. The parser will either try to
440       // perform this lookup again (e.g., as an object name), which
441       // will produce the ambiguity, or will complain that it expected
442       // a type name.
443       Result.suppressDiagnostics();
444       return nullptr;
445     }
446 
447     // We found a type within the ambiguous lookup; diagnose the
448     // ambiguity and then return that type. This might be the right
449     // answer, or it might not be, but it suppresses any attempt to
450     // perform the name lookup again.
451     break;
452 
453   case LookupResult::Found:
454     IIDecl = Result.getFoundDecl();
455     break;
456   }
457 
458   assert(IIDecl && "Didn't find decl");
459 
460   QualType T;
461   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
462     // C++ [class.qual]p2: A lookup that would find the injected-class-name
463     // instead names the constructors of the class, except when naming a class.
464     // This is ill-formed when we're not actually forming a ctor or dtor name.
465     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
466     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
467     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
468         FoundRD->isInjectedClassName() &&
469         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
470       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
471           << &II << /*Type*/1;
472 
473     DiagnoseUseOfDecl(IIDecl, NameLoc);
474 
475     T = Context.getTypeDeclType(TD);
476     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
477   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
478     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
479     if (!HasTrailingDot)
480       T = Context.getObjCInterfaceType(IDecl);
481   } else if (AllowDeducedTemplate) {
482     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
483       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
484                                                        QualType(), false);
485   }
486 
487   if (T.isNull()) {
488     // If it's not plausibly a type, suppress diagnostics.
489     Result.suppressDiagnostics();
490     return nullptr;
491   }
492 
493   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
494   // constructor or destructor name (in such a case, the scope specifier
495   // will be attached to the enclosing Expr or Decl node).
496   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
497       !isa<ObjCInterfaceDecl>(IIDecl)) {
498     if (WantNontrivialTypeSourceInfo) {
499       // Construct a type with type-source information.
500       TypeLocBuilder Builder;
501       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
502 
503       T = getElaboratedType(ETK_None, *SS, T);
504       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
505       ElabTL.setElaboratedKeywordLoc(SourceLocation());
506       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
507       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
508     } else {
509       T = getElaboratedType(ETK_None, *SS, T);
510     }
511   }
512 
513   return ParsedType::make(T);
514 }
515 
516 // Builds a fake NNS for the given decl context.
517 static NestedNameSpecifier *
518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
519   for (;; DC = DC->getLookupParent()) {
520     DC = DC->getPrimaryContext();
521     auto *ND = dyn_cast<NamespaceDecl>(DC);
522     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
523       return NestedNameSpecifier::Create(Context, nullptr, ND);
524     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
525       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
526                                          RD->getTypeForDecl());
527     else if (isa<TranslationUnitDecl>(DC))
528       return NestedNameSpecifier::GlobalSpecifier(Context);
529   }
530   llvm_unreachable("something isn't in TU scope?");
531 }
532 
533 /// Find the parent class with dependent bases of the innermost enclosing method
534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
535 /// up allowing unqualified dependent type names at class-level, which MSVC
536 /// correctly rejects.
537 static const CXXRecordDecl *
538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
539   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
540     DC = DC->getPrimaryContext();
541     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
542       if (MD->getParent()->hasAnyDependentBases())
543         return MD->getParent();
544   }
545   return nullptr;
546 }
547 
548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
549                                           SourceLocation NameLoc,
550                                           bool IsTemplateTypeArg) {
551   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
552 
553   NestedNameSpecifier *NNS = nullptr;
554   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
555     // If we weren't able to parse a default template argument, delay lookup
556     // until instantiation time by making a non-dependent DependentTypeName. We
557     // pretend we saw a NestedNameSpecifier referring to the current scope, and
558     // lookup is retried.
559     // FIXME: This hurts our diagnostic quality, since we get errors like "no
560     // type named 'Foo' in 'current_namespace'" when the user didn't write any
561     // name specifiers.
562     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
563     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
564   } else if (const CXXRecordDecl *RD =
565                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
566     // Build a DependentNameType that will perform lookup into RD at
567     // instantiation time.
568     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569                                       RD->getTypeForDecl());
570 
571     // Diagnose that this identifier was undeclared, and retry the lookup during
572     // template instantiation.
573     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
574                                                                       << RD;
575   } else {
576     // This is not a situation that we should recover from.
577     return ParsedType();
578   }
579 
580   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
581 
582   // Build type location information.  We synthesized the qualifier, so we have
583   // to build a fake NestedNameSpecifierLoc.
584   NestedNameSpecifierLocBuilder NNSLocBuilder;
585   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
586   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
587 
588   TypeLocBuilder Builder;
589   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
590   DepTL.setNameLoc(NameLoc);
591   DepTL.setElaboratedKeywordLoc(SourceLocation());
592   DepTL.setQualifierLoc(QualifierLoc);
593   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
594 }
595 
596 /// isTagName() - This method is called *for error recovery purposes only*
597 /// to determine if the specified name is a valid tag name ("struct foo").  If
598 /// so, this returns the TST for the tag corresponding to it (TST_enum,
599 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
600 /// cases in C where the user forgot to specify the tag.
601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
602   // Do a tag name lookup in this scope.
603   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
604   LookupName(R, S, false);
605   R.suppressDiagnostics();
606   if (R.getResultKind() == LookupResult::Found)
607     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
608       switch (TD->getTagKind()) {
609       case TTK_Struct: return DeclSpec::TST_struct;
610       case TTK_Interface: return DeclSpec::TST_interface;
611       case TTK_Union:  return DeclSpec::TST_union;
612       case TTK_Class:  return DeclSpec::TST_class;
613       case TTK_Enum:   return DeclSpec::TST_enum;
614       }
615     }
616 
617   return DeclSpec::TST_unspecified;
618 }
619 
620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
622 /// then downgrade the missing typename error to a warning.
623 /// This is needed for MSVC compatibility; Example:
624 /// @code
625 /// template<class T> class A {
626 /// public:
627 ///   typedef int TYPE;
628 /// };
629 /// template<class T> class B : public A<T> {
630 /// public:
631 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
632 /// };
633 /// @endcode
634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
635   if (CurContext->isRecord()) {
636     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
637       return true;
638 
639     const Type *Ty = SS->getScopeRep()->getAsType();
640 
641     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
642     for (const auto &Base : RD->bases())
643       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
644         return true;
645     return S->isFunctionPrototypeScope();
646   }
647   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
648 }
649 
650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
651                                    SourceLocation IILoc,
652                                    Scope *S,
653                                    CXXScopeSpec *SS,
654                                    ParsedType &SuggestedType,
655                                    bool IsTemplateName) {
656   // Don't report typename errors for editor placeholders.
657   if (II->isEditorPlaceholder())
658     return;
659   // We don't have anything to suggest (yet).
660   SuggestedType = nullptr;
661 
662   // There may have been a typo in the name of the type. Look up typo
663   // results, in case we have something that we can suggest.
664   if (TypoCorrection Corrected =
665           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
666                       llvm::make_unique<TypeNameValidatorCCC>(
667                           false, false, IsTemplateName, !IsTemplateName),
668                       CTK_ErrorRecovery)) {
669     // FIXME: Support error recovery for the template-name case.
670     bool CanRecover = !IsTemplateName;
671     if (Corrected.isKeyword()) {
672       // We corrected to a keyword.
673       diagnoseTypo(Corrected,
674                    PDiag(IsTemplateName ? diag::err_no_template_suggest
675                                         : diag::err_unknown_typename_suggest)
676                        << II);
677       II = Corrected.getCorrectionAsIdentifierInfo();
678     } else {
679       // We found a similarly-named type or interface; suggest that.
680       if (!SS || !SS->isSet()) {
681         diagnoseTypo(Corrected,
682                      PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                           : diag::err_unknown_typename_suggest)
684                          << II, CanRecover);
685       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
686         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
687         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
688                                 II->getName().equals(CorrectedStr);
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName
691                                ? diag::err_no_member_template_suggest
692                                : diag::err_unknown_nested_typename_suggest)
693                          << II << DC << DroppedSpecifier << SS->getRange(),
694                      CanRecover);
695       } else {
696         llvm_unreachable("could not have corrected a typo here");
697       }
698 
699       if (!CanRecover)
700         return;
701 
702       CXXScopeSpec tmpSS;
703       if (Corrected.getCorrectionSpecifier())
704         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
705                           SourceRange(IILoc));
706       // FIXME: Support class template argument deduction here.
707       SuggestedType =
708           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
709                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
710                       /*IsCtorOrDtorName=*/false,
711                       /*NonTrivialTypeSourceInfo=*/true);
712     }
713     return;
714   }
715 
716   if (getLangOpts().CPlusPlus && !IsTemplateName) {
717     // See if II is a class template that the user forgot to pass arguments to.
718     UnqualifiedId Name;
719     Name.setIdentifier(II, IILoc);
720     CXXScopeSpec EmptySS;
721     TemplateTy TemplateResult;
722     bool MemberOfUnknownSpecialization;
723     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
724                        Name, nullptr, true, TemplateResult,
725                        MemberOfUnknownSpecialization) == TNK_Type_template) {
726       TemplateName TplName = TemplateResult.get();
727       Diag(IILoc, diag::err_template_missing_args)
728         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
729       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
730         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
731           << TplDecl->getTemplateParameters()->getSourceRange();
732       }
733       return;
734     }
735   }
736 
737   // FIXME: Should we move the logic that tries to recover from a missing tag
738   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
739 
740   if (!SS || (!SS->isSet() && !SS->isInvalid()))
741     Diag(IILoc, IsTemplateName ? diag::err_no_template
742                                : diag::err_unknown_typename)
743         << II;
744   else if (DeclContext *DC = computeDeclContext(*SS, false))
745     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
746                                : diag::err_typename_nested_not_found)
747         << II << DC << SS->getRange();
748   else if (isDependentScopeSpecifier(*SS)) {
749     unsigned DiagID = diag::err_typename_missing;
750     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
751       DiagID = diag::ext_typename_missing;
752 
753     Diag(SS->getRange().getBegin(), DiagID)
754       << SS->getScopeRep() << II->getName()
755       << SourceRange(SS->getRange().getBegin(), IILoc)
756       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
757     SuggestedType = ActOnTypenameType(S, SourceLocation(),
758                                       *SS, *II, IILoc).get();
759   } else {
760     assert(SS && SS->isInvalid() &&
761            "Invalid scope specifier has already been diagnosed");
762   }
763 }
764 
765 /// \brief Determine whether the given result set contains either a type name
766 /// or
767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
768   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
769                        NextToken.is(tok::less);
770 
771   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
772     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
773       return true;
774 
775     if (CheckTemplate && isa<TemplateDecl>(*I))
776       return true;
777   }
778 
779   return false;
780 }
781 
782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
783                                     Scope *S, CXXScopeSpec &SS,
784                                     IdentifierInfo *&Name,
785                                     SourceLocation NameLoc) {
786   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
787   SemaRef.LookupParsedName(R, S, &SS);
788   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
789     StringRef FixItTagName;
790     switch (Tag->getTagKind()) {
791       case TTK_Class:
792         FixItTagName = "class ";
793         break;
794 
795       case TTK_Enum:
796         FixItTagName = "enum ";
797         break;
798 
799       case TTK_Struct:
800         FixItTagName = "struct ";
801         break;
802 
803       case TTK_Interface:
804         FixItTagName = "__interface ";
805         break;
806 
807       case TTK_Union:
808         FixItTagName = "union ";
809         break;
810     }
811 
812     StringRef TagName = FixItTagName.drop_back();
813     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
814       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
815       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
816 
817     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
818          I != IEnd; ++I)
819       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
820         << Name << TagName;
821 
822     // Replace lookup results with just the tag decl.
823     Result.clear(Sema::LookupTagName);
824     SemaRef.LookupParsedName(Result, S, &SS);
825     return true;
826   }
827 
828   return false;
829 }
830 
831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
833                                   QualType T, SourceLocation NameLoc) {
834   ASTContext &Context = S.Context;
835 
836   TypeLocBuilder Builder;
837   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
838 
839   T = S.getElaboratedType(ETK_None, SS, T);
840   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
841   ElabTL.setElaboratedKeywordLoc(SourceLocation());
842   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
843   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
844 }
845 
846 Sema::NameClassification
847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
848                    SourceLocation NameLoc, const Token &NextToken,
849                    bool IsAddressOfOperand,
850                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865 
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868 
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876 
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886 
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889 
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919 
920     // In C, we first see whether there is a tag type by the same name, in
921     // which case it's likely that the user just forgot to write "enum",
922     // "struct", or "union".
923     if (!getLangOpts().CPlusPlus && !SecondTry &&
924         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
925       break;
926     }
927 
928     // Perform typo correction to determine if there is another name that is
929     // close to this name.
930     if (!SecondTry && CCC) {
931       SecondTry = true;
932       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
933                                                  Result.getLookupKind(), S,
934                                                  &SS, std::move(CCC),
935                                                  CTK_ErrorRecovery)) {
936         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
937         unsigned QualifiedDiag = diag::err_no_member_suggest;
938 
939         NamedDecl *FirstDecl = Corrected.getFoundDecl();
940         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
941         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
942             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
943           UnqualifiedDiag = diag::err_no_template_suggest;
944           QualifiedDiag = diag::err_no_member_template_suggest;
945         } else if (UnderlyingFirstDecl &&
946                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
947                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
949           UnqualifiedDiag = diag::err_unknown_typename_suggest;
950           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
951         }
952 
953         if (SS.isEmpty()) {
954           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
955         } else {// FIXME: is this even reachable? Test it.
956           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
957           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
958                                   Name->getName().equals(CorrectedStr);
959           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
960                                     << Name << computeDeclContext(SS, false)
961                                     << DroppedSpecifier << SS.getRange());
962         }
963 
964         // Update the name, so that the caller has the new name.
965         Name = Corrected.getCorrectionAsIdentifierInfo();
966 
967         // Typo correction corrected to a keyword.
968         if (Corrected.isKeyword())
969           return Name;
970 
971         // Also update the LookupResult...
972         // FIXME: This should probably go away at some point
973         Result.clear();
974         Result.setLookupName(Corrected.getCorrection());
975         if (FirstDecl)
976           Result.addDecl(FirstDecl);
977 
978         // If we found an Objective-C instance variable, let
979         // LookupInObjCMethod build the appropriate expression to
980         // reference the ivar.
981         // FIXME: This is a gross hack.
982         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
983           Result.clear();
984           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
985           return E;
986         }
987 
988         goto Corrected;
989       }
990     }
991 
992     // We failed to correct; just fall through and let the parser deal with it.
993     Result.suppressDiagnostics();
994     return NameClassification::Unknown();
995 
996   case LookupResult::NotFoundInCurrentInstantiation: {
997     // We performed name lookup into the current instantiation, and there were
998     // dependent bases, so we treat this result the same way as any other
999     // dependent nested-name-specifier.
1000 
1001     // C++ [temp.res]p2:
1002     //   A name used in a template declaration or definition and that is
1003     //   dependent on a template-parameter is assumed not to name a type
1004     //   unless the applicable name lookup finds a type name or the name is
1005     //   qualified by the keyword typename.
1006     //
1007     // FIXME: If the next token is '<', we might want to ask the parser to
1008     // perform some heroics to see if we actually have a
1009     // template-argument-list, which would indicate a missing 'template'
1010     // keyword here.
1011     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1012                                       NameInfo, IsAddressOfOperand,
1013                                       /*TemplateArgs=*/nullptr);
1014   }
1015 
1016   case LookupResult::Found:
1017   case LookupResult::FoundOverloaded:
1018   case LookupResult::FoundUnresolvedValue:
1019     break;
1020 
1021   case LookupResult::Ambiguous:
1022     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1023         hasAnyAcceptableTemplateNames(Result)) {
1024       // C++ [temp.local]p3:
1025       //   A lookup that finds an injected-class-name (10.2) can result in an
1026       //   ambiguity in certain cases (for example, if it is found in more than
1027       //   one base class). If all of the injected-class-names that are found
1028       //   refer to specializations of the same class template, and if the name
1029       //   is followed by a template-argument-list, the reference refers to the
1030       //   class template itself and not a specialization thereof, and is not
1031       //   ambiguous.
1032       //
1033       // This filtering can make an ambiguous result into an unambiguous one,
1034       // so try again after filtering out template names.
1035       FilterAcceptableTemplateNames(Result);
1036       if (!Result.isAmbiguous()) {
1037         IsFilteredTemplateName = true;
1038         break;
1039       }
1040     }
1041 
1042     // Diagnose the ambiguity and return an error.
1043     return NameClassification::Error();
1044   }
1045 
1046   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1048     // C++ [temp.names]p3:
1049     //   After name lookup (3.4) finds that a name is a template-name or that
1050     //   an operator-function-id or a literal- operator-id refers to a set of
1051     //   overloaded functions any member of which is a function template if
1052     //   this is followed by a <, the < is always taken as the delimiter of a
1053     //   template-argument-list and never as the less-than operator.
1054     if (!IsFilteredTemplateName)
1055       FilterAcceptableTemplateNames(Result);
1056 
1057     if (!Result.empty()) {
1058       bool IsFunctionTemplate;
1059       bool IsVarTemplate;
1060       TemplateName Template;
1061       if (Result.end() - Result.begin() > 1) {
1062         IsFunctionTemplate = true;
1063         Template = Context.getOverloadedTemplateName(Result.begin(),
1064                                                      Result.end());
1065       } else {
1066         TemplateDecl *TD
1067           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1068         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1069         IsVarTemplate = isa<VarTemplateDecl>(TD);
1070 
1071         if (SS.isSet() && !SS.isInvalid())
1072           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1073                                                     /*TemplateKeyword=*/false,
1074                                                       TD);
1075         else
1076           Template = TemplateName(TD);
1077       }
1078 
1079       if (IsFunctionTemplate) {
1080         // Function templates always go through overload resolution, at which
1081         // point we'll perform the various checks (e.g., accessibility) we need
1082         // to based on which function we selected.
1083         Result.suppressDiagnostics();
1084 
1085         return NameClassification::FunctionTemplate(Template);
1086       }
1087 
1088       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1089                            : NameClassification::TypeTemplate(Template);
1090     }
1091   }
1092 
1093   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1094   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1097     QualType T = Context.getTypeDeclType(Type);
1098     if (SS.isNotEmpty())
1099       return buildNestedType(*this, SS, T, NameLoc);
1100     return ParsedType::make(T);
1101   }
1102 
1103   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1104   if (!Class) {
1105     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1106     if (ObjCCompatibleAliasDecl *Alias =
1107             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1108       Class = Alias->getClassInterface();
1109   }
1110 
1111   if (Class) {
1112     DiagnoseUseOfDecl(Class, NameLoc);
1113 
1114     if (NextToken.is(tok::period)) {
1115       // Interface. <something> is parsed as a property reference expression.
1116       // Just return "unknown" as a fall-through for now.
1117       Result.suppressDiagnostics();
1118       return NameClassification::Unknown();
1119     }
1120 
1121     QualType T = Context.getObjCInterfaceType(Class);
1122     return ParsedType::make(T);
1123   }
1124 
1125   // We can have a type template here if we're classifying a template argument.
1126   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1127       !isa<VarTemplateDecl>(FirstDecl))
1128     return NameClassification::TypeTemplate(
1129         TemplateName(cast<TemplateDecl>(FirstDecl)));
1130 
1131   // Check for a tag type hidden by a non-type decl in a few cases where it
1132   // seems likely a type is wanted instead of the non-type that was found.
1133   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1134   if ((NextToken.is(tok::identifier) ||
1135        (NextIsOp &&
1136         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1137       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1138     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     QualType T = Context.getTypeDeclType(Type);
1141     if (SS.isNotEmpty())
1142       return buildNestedType(*this, SS, T, NameLoc);
1143     return ParsedType::make(T);
1144   }
1145 
1146   if (FirstDecl->isCXXClassMember())
1147     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1148                                            nullptr, S);
1149 
1150   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1151   return BuildDeclarationNameExpr(SS, Result, ADL);
1152 }
1153 
1154 Sema::TemplateNameKindForDiagnostics
1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1156   auto *TD = Name.getAsTemplateDecl();
1157   if (!TD)
1158     return TemplateNameKindForDiagnostics::DependentTemplate;
1159   if (isa<ClassTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::ClassTemplate;
1161   if (isa<FunctionTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::FunctionTemplate;
1163   if (isa<VarTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::VarTemplate;
1165   if (isa<TypeAliasTemplateDecl>(TD))
1166     return TemplateNameKindForDiagnostics::AliasTemplate;
1167   if (isa<TemplateTemplateParmDecl>(TD))
1168     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1169   return TemplateNameKindForDiagnostics::DependentTemplate;
1170 }
1171 
1172 // Determines the context to return to after temporarily entering a
1173 // context.  This depends in an unnecessarily complicated way on the
1174 // exact ordering of callbacks from the parser.
1175 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1176 
1177   // Functions defined inline within classes aren't parsed until we've
1178   // finished parsing the top-level class, so the top-level class is
1179   // the context we'll need to return to.
1180   // A Lambda call operator whose parent is a class must not be treated
1181   // as an inline member function.  A Lambda can be used legally
1182   // either as an in-class member initializer or a default argument.  These
1183   // are parsed once the class has been marked complete and so the containing
1184   // context would be the nested class (when the lambda is defined in one);
1185   // If the class is not complete, then the lambda is being used in an
1186   // ill-formed fashion (such as to specify the width of a bit-field, or
1187   // in an array-bound) - in which case we still want to return the
1188   // lexically containing DC (which could be a nested class).
1189   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1190     DC = DC->getLexicalParent();
1191 
1192     // A function not defined within a class will always return to its
1193     // lexical context.
1194     if (!isa<CXXRecordDecl>(DC))
1195       return DC;
1196 
1197     // A C++ inline method/friend is parsed *after* the topmost class
1198     // it was declared in is fully parsed ("complete");  the topmost
1199     // class is the context we need to return to.
1200     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1201       DC = RD;
1202 
1203     // Return the declaration context of the topmost class the inline method is
1204     // declared in.
1205     return DC;
1206   }
1207 
1208   return DC->getLexicalParent();
1209 }
1210 
1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1212   assert(getContainingDC(DC) == CurContext &&
1213       "The next DeclContext should be lexically contained in the current one.");
1214   CurContext = DC;
1215   S->setEntity(DC);
1216 }
1217 
1218 void Sema::PopDeclContext() {
1219   assert(CurContext && "DeclContext imbalance!");
1220 
1221   CurContext = getContainingDC(CurContext);
1222   assert(CurContext && "Popped translation unit!");
1223 }
1224 
1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1226                                                                     Decl *D) {
1227   // Unlike PushDeclContext, the context to which we return is not necessarily
1228   // the containing DC of TD, because the new context will be some pre-existing
1229   // TagDecl definition instead of a fresh one.
1230   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1231   CurContext = cast<TagDecl>(D)->getDefinition();
1232   assert(CurContext && "skipping definition of undefined tag");
1233   // Start lookups from the parent of the current context; we don't want to look
1234   // into the pre-existing complete definition.
1235   S->setEntity(CurContext->getLookupParent());
1236   return Result;
1237 }
1238 
1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1240   CurContext = static_cast<decltype(CurContext)>(Context);
1241 }
1242 
1243 /// EnterDeclaratorContext - Used when we must lookup names in the context
1244 /// of a declarator's nested name specifier.
1245 ///
1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1247   // C++0x [basic.lookup.unqual]p13:
1248   //   A name used in the definition of a static data member of class
1249   //   X (after the qualified-id of the static member) is looked up as
1250   //   if the name was used in a member function of X.
1251   // C++0x [basic.lookup.unqual]p14:
1252   //   If a variable member of a namespace is defined outside of the
1253   //   scope of its namespace then any name used in the definition of
1254   //   the variable member (after the declarator-id) is looked up as
1255   //   if the definition of the variable member occurred in its
1256   //   namespace.
1257   // Both of these imply that we should push a scope whose context
1258   // is the semantic context of the declaration.  We can't use
1259   // PushDeclContext here because that context is not necessarily
1260   // lexically contained in the current context.  Fortunately,
1261   // the containing scope should have the appropriate information.
1262 
1263   assert(!S->getEntity() && "scope already has entity");
1264 
1265 #ifndef NDEBUG
1266   Scope *Ancestor = S->getParent();
1267   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1268   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1269 #endif
1270 
1271   CurContext = DC;
1272   S->setEntity(DC);
1273 }
1274 
1275 void Sema::ExitDeclaratorContext(Scope *S) {
1276   assert(S->getEntity() == CurContext && "Context imbalance!");
1277 
1278   // Switch back to the lexical context.  The safety of this is
1279   // enforced by an assert in EnterDeclaratorContext.
1280   Scope *Ancestor = S->getParent();
1281   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1282   CurContext = Ancestor->getEntity();
1283 
1284   // We don't need to do anything with the scope, which is going to
1285   // disappear.
1286 }
1287 
1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1289   // We assume that the caller has already called
1290   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1291   FunctionDecl *FD = D->getAsFunction();
1292   if (!FD)
1293     return;
1294 
1295   // Same implementation as PushDeclContext, but enters the context
1296   // from the lexical parent, rather than the top-level class.
1297   assert(CurContext == FD->getLexicalParent() &&
1298     "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = FD;
1300   S->setEntity(CurContext);
1301 
1302   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1303     ParmVarDecl *Param = FD->getParamDecl(P);
1304     // If the parameter has an identifier, then add it to the scope
1305     if (Param->getIdentifier()) {
1306       S->AddDecl(Param);
1307       IdResolver.AddDecl(Param);
1308     }
1309   }
1310 }
1311 
1312 void Sema::ActOnExitFunctionContext() {
1313   // Same implementation as PopDeclContext, but returns to the lexical parent,
1314   // rather than the top-level class.
1315   assert(CurContext && "DeclContext imbalance!");
1316   CurContext = CurContext->getLexicalParent();
1317   assert(CurContext && "Popped translation unit!");
1318 }
1319 
1320 /// \brief Determine whether we allow overloading of the function
1321 /// PrevDecl with another declaration.
1322 ///
1323 /// This routine determines whether overloading is possible, not
1324 /// whether some new function is actually an overload. It will return
1325 /// true in C++ (where we can always provide overloads) or, as an
1326 /// extension, in C when the previous function is already an
1327 /// overloaded function declaration or has the "overloadable"
1328 /// attribute.
1329 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1330                                        ASTContext &Context) {
1331   if (Context.getLangOpts().CPlusPlus)
1332     return true;
1333 
1334   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1335     return true;
1336 
1337   return (Previous.getResultKind() == LookupResult::Found
1338           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1339 }
1340 
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348 
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354 
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362 
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367 
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375 
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380 
1381   S->AddDecl(D);
1382 
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395 
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401 
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406 
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411 
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419 
1420   return nullptr;
1421 }
1422 
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426 
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435 
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438 
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441 
1442     F.erase();
1443   }
1444 
1445   F.done();
1446 }
1447 
1448 static bool isUsingDecl(NamedDecl *D) {
1449   return isa<UsingShadowDecl>(D) ||
1450          isa<UnresolvedUsingTypenameDecl>(D) ||
1451          isa<UnresolvedUsingValueDecl>(D);
1452 }
1453 
1454 /// Removes using shadow declarations from the lookup results.
1455 static void RemoveUsingDecls(LookupResult &R) {
1456   LookupResult::Filter F = R.makeFilter();
1457   while (F.hasNext())
1458     if (isUsingDecl(F.next()))
1459       F.erase();
1460 
1461   F.done();
1462 }
1463 
1464 /// \brief Check for this common pattern:
1465 /// @code
1466 /// class S {
1467 ///   S(const S&); // DO NOT IMPLEMENT
1468 ///   void operator=(const S&); // DO NOT IMPLEMENT
1469 /// };
1470 /// @endcode
1471 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1472   // FIXME: Should check for private access too but access is set after we get
1473   // the decl here.
1474   if (D->doesThisDeclarationHaveABody())
1475     return false;
1476 
1477   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1478     return CD->isCopyConstructor();
1479   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1480     return Method->isCopyAssignmentOperator();
1481   return false;
1482 }
1483 
1484 // We need this to handle
1485 //
1486 // typedef struct {
1487 //   void *foo() { return 0; }
1488 // } A;
1489 //
1490 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1491 // for example. If 'A', foo will have external linkage. If we have '*A',
1492 // foo will have no linkage. Since we can't know until we get to the end
1493 // of the typedef, this function finds out if D might have non-external linkage.
1494 // Callers should verify at the end of the TU if it D has external linkage or
1495 // not.
1496 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1497   const DeclContext *DC = D->getDeclContext();
1498   while (!DC->isTranslationUnit()) {
1499     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1500       if (!RD->hasNameForLinkage())
1501         return true;
1502     }
1503     DC = DC->getParent();
1504   }
1505 
1506   return !D->isExternallyVisible();
1507 }
1508 
1509 // FIXME: This needs to be refactored; some other isInMainFile users want
1510 // these semantics.
1511 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1512   if (S.TUKind != TU_Complete)
1513     return false;
1514   return S.SourceMgr.isInMainFile(Loc);
1515 }
1516 
1517 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1518   assert(D);
1519 
1520   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1521     return false;
1522 
1523   // Ignore all entities declared within templates, and out-of-line definitions
1524   // of members of class templates.
1525   if (D->getDeclContext()->isDependentContext() ||
1526       D->getLexicalDeclContext()->isDependentContext())
1527     return false;
1528 
1529   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1530     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1531       return false;
1532     // A non-out-of-line declaration of a member specialization was implicitly
1533     // instantiated; it's the out-of-line declaration that we're interested in.
1534     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1535         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1536       return false;
1537 
1538     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1539       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1540         return false;
1541     } else {
1542       // 'static inline' functions are defined in headers; don't warn.
1543       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1544         return false;
1545     }
1546 
1547     if (FD->doesThisDeclarationHaveABody() &&
1548         Context.DeclMustBeEmitted(FD))
1549       return false;
1550   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1551     // Constants and utility variables are defined in headers with internal
1552     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1553     // like "inline".)
1554     if (!isMainFileLoc(*this, VD->getLocation()))
1555       return false;
1556 
1557     if (Context.DeclMustBeEmitted(VD))
1558       return false;
1559 
1560     if (VD->isStaticDataMember() &&
1561         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1562       return false;
1563     if (VD->isStaticDataMember() &&
1564         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1565         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1566       return false;
1567 
1568     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1569       return false;
1570   } else {
1571     return false;
1572   }
1573 
1574   // Only warn for unused decls internal to the translation unit.
1575   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1576   // for inline functions defined in the main source file, for instance.
1577   return mightHaveNonExternalLinkage(D);
1578 }
1579 
1580 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1581   if (!D)
1582     return;
1583 
1584   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1585     const FunctionDecl *First = FD->getFirstDecl();
1586     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1587       return; // First should already be in the vector.
1588   }
1589 
1590   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1591     const VarDecl *First = VD->getFirstDecl();
1592     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1593       return; // First should already be in the vector.
1594   }
1595 
1596   if (ShouldWarnIfUnusedFileScopedDecl(D))
1597     UnusedFileScopedDecls.push_back(D);
1598 }
1599 
1600 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1601   if (D->isInvalidDecl())
1602     return false;
1603 
1604   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1605       D->hasAttr<ObjCPreciseLifetimeAttr>())
1606     return false;
1607 
1608   if (isa<LabelDecl>(D))
1609     return true;
1610 
1611   // Except for labels, we only care about unused decls that are local to
1612   // functions.
1613   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1614   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1615     // For dependent types, the diagnostic is deferred.
1616     WithinFunction =
1617         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1618   if (!WithinFunction)
1619     return false;
1620 
1621   if (isa<TypedefNameDecl>(D))
1622     return true;
1623 
1624   // White-list anything that isn't a local variable.
1625   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1626     return false;
1627 
1628   // Types of valid local variables should be complete, so this should succeed.
1629   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1630 
1631     // White-list anything with an __attribute__((unused)) type.
1632     const auto *Ty = VD->getType().getTypePtr();
1633 
1634     // Only look at the outermost level of typedef.
1635     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1636       if (TT->getDecl()->hasAttr<UnusedAttr>())
1637         return false;
1638     }
1639 
1640     // If we failed to complete the type for some reason, or if the type is
1641     // dependent, don't diagnose the variable.
1642     if (Ty->isIncompleteType() || Ty->isDependentType())
1643       return false;
1644 
1645     // Look at the element type to ensure that the warning behaviour is
1646     // consistent for both scalars and arrays.
1647     Ty = Ty->getBaseElementTypeUnsafe();
1648 
1649     if (const TagType *TT = Ty->getAs<TagType>()) {
1650       const TagDecl *Tag = TT->getDecl();
1651       if (Tag->hasAttr<UnusedAttr>())
1652         return false;
1653 
1654       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1655         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1656           return false;
1657 
1658         if (const Expr *Init = VD->getInit()) {
1659           if (const ExprWithCleanups *Cleanups =
1660                   dyn_cast<ExprWithCleanups>(Init))
1661             Init = Cleanups->getSubExpr();
1662           const CXXConstructExpr *Construct =
1663             dyn_cast<CXXConstructExpr>(Init);
1664           if (Construct && !Construct->isElidable()) {
1665             CXXConstructorDecl *CD = Construct->getConstructor();
1666             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1667               return false;
1668           }
1669         }
1670       }
1671     }
1672 
1673     // TODO: __attribute__((unused)) templates?
1674   }
1675 
1676   return true;
1677 }
1678 
1679 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1680                                      FixItHint &Hint) {
1681   if (isa<LabelDecl>(D)) {
1682     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1683                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1684     if (AfterColon.isInvalid())
1685       return;
1686     Hint = FixItHint::CreateRemoval(CharSourceRange::
1687                                     getCharRange(D->getLocStart(), AfterColon));
1688   }
1689 }
1690 
1691 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1692   if (D->getTypeForDecl()->isDependentType())
1693     return;
1694 
1695   for (auto *TmpD : D->decls()) {
1696     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1697       DiagnoseUnusedDecl(T);
1698     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1699       DiagnoseUnusedNestedTypedefs(R);
1700   }
1701 }
1702 
1703 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1704 /// unless they are marked attr(unused).
1705 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1706   if (!ShouldDiagnoseUnusedDecl(D))
1707     return;
1708 
1709   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1710     // typedefs can be referenced later on, so the diagnostics are emitted
1711     // at end-of-translation-unit.
1712     UnusedLocalTypedefNameCandidates.insert(TD);
1713     return;
1714   }
1715 
1716   FixItHint Hint;
1717   GenerateFixForUnusedDecl(D, Context, Hint);
1718 
1719   unsigned DiagID;
1720   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1721     DiagID = diag::warn_unused_exception_param;
1722   else if (isa<LabelDecl>(D))
1723     DiagID = diag::warn_unused_label;
1724   else
1725     DiagID = diag::warn_unused_variable;
1726 
1727   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1728 }
1729 
1730 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1731   // Verify that we have no forward references left.  If so, there was a goto
1732   // or address of a label taken, but no definition of it.  Label fwd
1733   // definitions are indicated with a null substmt which is also not a resolved
1734   // MS inline assembly label name.
1735   bool Diagnose = false;
1736   if (L->isMSAsmLabel())
1737     Diagnose = !L->isResolvedMSAsmLabel();
1738   else
1739     Diagnose = L->getStmt() == nullptr;
1740   if (Diagnose)
1741     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1742 }
1743 
1744 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1745   S->mergeNRVOIntoParent();
1746 
1747   if (S->decl_empty()) return;
1748   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1749          "Scope shouldn't contain decls!");
1750 
1751   for (auto *TmpD : S->decls()) {
1752     assert(TmpD && "This decl didn't get pushed??");
1753 
1754     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1755     NamedDecl *D = cast<NamedDecl>(TmpD);
1756 
1757     if (!D->getDeclName()) continue;
1758 
1759     // Diagnose unused variables in this scope.
1760     if (!S->hasUnrecoverableErrorOccurred()) {
1761       DiagnoseUnusedDecl(D);
1762       if (const auto *RD = dyn_cast<RecordDecl>(D))
1763         DiagnoseUnusedNestedTypedefs(RD);
1764     }
1765 
1766     // If this was a forward reference to a label, verify it was defined.
1767     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1768       CheckPoppedLabel(LD, *this);
1769 
1770     // Remove this name from our lexical scope, and warn on it if we haven't
1771     // already.
1772     IdResolver.RemoveDecl(D);
1773     auto ShadowI = ShadowingDecls.find(D);
1774     if (ShadowI != ShadowingDecls.end()) {
1775       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1776         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1777             << D << FD << FD->getParent();
1778         Diag(FD->getLocation(), diag::note_previous_declaration);
1779       }
1780       ShadowingDecls.erase(ShadowI);
1781     }
1782   }
1783 }
1784 
1785 /// \brief Look for an Objective-C class in the translation unit.
1786 ///
1787 /// \param Id The name of the Objective-C class we're looking for. If
1788 /// typo-correction fixes this name, the Id will be updated
1789 /// to the fixed name.
1790 ///
1791 /// \param IdLoc The location of the name in the translation unit.
1792 ///
1793 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1794 /// if there is no class with the given name.
1795 ///
1796 /// \returns The declaration of the named Objective-C class, or NULL if the
1797 /// class could not be found.
1798 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1799                                               SourceLocation IdLoc,
1800                                               bool DoTypoCorrection) {
1801   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1802   // creation from this context.
1803   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1804 
1805   if (!IDecl && DoTypoCorrection) {
1806     // Perform typo correction at the given location, but only if we
1807     // find an Objective-C class name.
1808     if (TypoCorrection C = CorrectTypo(
1809             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1810             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1811             CTK_ErrorRecovery)) {
1812       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1813       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1814       Id = IDecl->getIdentifier();
1815     }
1816   }
1817   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1818   // This routine must always return a class definition, if any.
1819   if (Def && Def->getDefinition())
1820       Def = Def->getDefinition();
1821   return Def;
1822 }
1823 
1824 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1825 /// from S, where a non-field would be declared. This routine copes
1826 /// with the difference between C and C++ scoping rules in structs and
1827 /// unions. For example, the following code is well-formed in C but
1828 /// ill-formed in C++:
1829 /// @code
1830 /// struct S6 {
1831 ///   enum { BAR } e;
1832 /// };
1833 ///
1834 /// void test_S6() {
1835 ///   struct S6 a;
1836 ///   a.e = BAR;
1837 /// }
1838 /// @endcode
1839 /// For the declaration of BAR, this routine will return a different
1840 /// scope. The scope S will be the scope of the unnamed enumeration
1841 /// within S6. In C++, this routine will return the scope associated
1842 /// with S6, because the enumeration's scope is a transparent
1843 /// context but structures can contain non-field names. In C, this
1844 /// routine will return the translation unit scope, since the
1845 /// enumeration's scope is a transparent context and structures cannot
1846 /// contain non-field names.
1847 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1848   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1849          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1850          (S->isClassScope() && !getLangOpts().CPlusPlus))
1851     S = S->getParent();
1852   return S;
1853 }
1854 
1855 /// \brief Looks up the declaration of "struct objc_super" and
1856 /// saves it for later use in building builtin declaration of
1857 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1858 /// pre-existing declaration exists no action takes place.
1859 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1860                                         IdentifierInfo *II) {
1861   if (!II->isStr("objc_msgSendSuper"))
1862     return;
1863   ASTContext &Context = ThisSema.Context;
1864 
1865   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1866                       SourceLocation(), Sema::LookupTagName);
1867   ThisSema.LookupName(Result, S);
1868   if (Result.getResultKind() == LookupResult::Found)
1869     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1870       Context.setObjCSuperType(Context.getTagDeclType(TD));
1871 }
1872 
1873 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1874   switch (Error) {
1875   case ASTContext::GE_None:
1876     return "";
1877   case ASTContext::GE_Missing_stdio:
1878     return "stdio.h";
1879   case ASTContext::GE_Missing_setjmp:
1880     return "setjmp.h";
1881   case ASTContext::GE_Missing_ucontext:
1882     return "ucontext.h";
1883   }
1884   llvm_unreachable("unhandled error kind");
1885 }
1886 
1887 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1888 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1889 /// if we're creating this built-in in anticipation of redeclaring the
1890 /// built-in.
1891 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1892                                      Scope *S, bool ForRedeclaration,
1893                                      SourceLocation Loc) {
1894   LookupPredefedObjCSuperType(*this, S, II);
1895 
1896   ASTContext::GetBuiltinTypeError Error;
1897   QualType R = Context.GetBuiltinType(ID, Error);
1898   if (Error) {
1899     if (ForRedeclaration)
1900       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1901           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1902     return nullptr;
1903   }
1904 
1905   if (!ForRedeclaration &&
1906       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1907        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1908     Diag(Loc, diag::ext_implicit_lib_function_decl)
1909         << Context.BuiltinInfo.getName(ID) << R;
1910     if (Context.BuiltinInfo.getHeaderName(ID) &&
1911         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1912       Diag(Loc, diag::note_include_header_or_declare)
1913           << Context.BuiltinInfo.getHeaderName(ID)
1914           << Context.BuiltinInfo.getName(ID);
1915   }
1916 
1917   if (R.isNull())
1918     return nullptr;
1919 
1920   DeclContext *Parent = Context.getTranslationUnitDecl();
1921   if (getLangOpts().CPlusPlus) {
1922     LinkageSpecDecl *CLinkageDecl =
1923         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1924                                 LinkageSpecDecl::lang_c, false);
1925     CLinkageDecl->setImplicit();
1926     Parent->addDecl(CLinkageDecl);
1927     Parent = CLinkageDecl;
1928   }
1929 
1930   FunctionDecl *New = FunctionDecl::Create(Context,
1931                                            Parent,
1932                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1933                                            SC_Extern,
1934                                            false,
1935                                            R->isFunctionProtoType());
1936   New->setImplicit();
1937 
1938   // Create Decl objects for each parameter, adding them to the
1939   // FunctionDecl.
1940   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1941     SmallVector<ParmVarDecl*, 16> Params;
1942     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1943       ParmVarDecl *parm =
1944           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1945                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1946                               SC_None, nullptr);
1947       parm->setScopeInfo(0, i);
1948       Params.push_back(parm);
1949     }
1950     New->setParams(Params);
1951   }
1952 
1953   AddKnownFunctionAttributes(New);
1954   RegisterLocallyScopedExternCDecl(New, S);
1955 
1956   // TUScope is the translation-unit scope to insert this function into.
1957   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1958   // relate Scopes to DeclContexts, and probably eliminate CurContext
1959   // entirely, but we're not there yet.
1960   DeclContext *SavedContext = CurContext;
1961   CurContext = Parent;
1962   PushOnScopeChains(New, TUScope);
1963   CurContext = SavedContext;
1964   return New;
1965 }
1966 
1967 /// Typedef declarations don't have linkage, but they still denote the same
1968 /// entity if their types are the same.
1969 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1970 /// isSameEntity.
1971 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1972                                                      TypedefNameDecl *Decl,
1973                                                      LookupResult &Previous) {
1974   // This is only interesting when modules are enabled.
1975   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1976     return;
1977 
1978   // Empty sets are uninteresting.
1979   if (Previous.empty())
1980     return;
1981 
1982   LookupResult::Filter Filter = Previous.makeFilter();
1983   while (Filter.hasNext()) {
1984     NamedDecl *Old = Filter.next();
1985 
1986     // Non-hidden declarations are never ignored.
1987     if (S.isVisible(Old))
1988       continue;
1989 
1990     // Declarations of the same entity are not ignored, even if they have
1991     // different linkages.
1992     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1993       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1994                                 Decl->getUnderlyingType()))
1995         continue;
1996 
1997       // If both declarations give a tag declaration a typedef name for linkage
1998       // purposes, then they declare the same entity.
1999       if (S.getLangOpts().CPlusPlus &&
2000           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2001           Decl->getAnonDeclWithTypedefName())
2002         continue;
2003     }
2004 
2005     Filter.erase();
2006   }
2007 
2008   Filter.done();
2009 }
2010 
2011 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2012   QualType OldType;
2013   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2014     OldType = OldTypedef->getUnderlyingType();
2015   else
2016     OldType = Context.getTypeDeclType(Old);
2017   QualType NewType = New->getUnderlyingType();
2018 
2019   if (NewType->isVariablyModifiedType()) {
2020     // Must not redefine a typedef with a variably-modified type.
2021     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2022     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2023       << Kind << NewType;
2024     if (Old->getLocation().isValid())
2025       notePreviousDefinition(Old, New->getLocation());
2026     New->setInvalidDecl();
2027     return true;
2028   }
2029 
2030   if (OldType != NewType &&
2031       !OldType->isDependentType() &&
2032       !NewType->isDependentType() &&
2033       !Context.hasSameType(OldType, NewType)) {
2034     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2035     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2036       << Kind << NewType << OldType;
2037     if (Old->getLocation().isValid())
2038       notePreviousDefinition(Old, New->getLocation());
2039     New->setInvalidDecl();
2040     return true;
2041   }
2042   return false;
2043 }
2044 
2045 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2046 /// same name and scope as a previous declaration 'Old'.  Figure out
2047 /// how to resolve this situation, merging decls or emitting
2048 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2049 ///
2050 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2051                                 LookupResult &OldDecls) {
2052   // If the new decl is known invalid already, don't bother doing any
2053   // merging checks.
2054   if (New->isInvalidDecl()) return;
2055 
2056   // Allow multiple definitions for ObjC built-in typedefs.
2057   // FIXME: Verify the underlying types are equivalent!
2058   if (getLangOpts().ObjC1) {
2059     const IdentifierInfo *TypeID = New->getIdentifier();
2060     switch (TypeID->getLength()) {
2061     default: break;
2062     case 2:
2063       {
2064         if (!TypeID->isStr("id"))
2065           break;
2066         QualType T = New->getUnderlyingType();
2067         if (!T->isPointerType())
2068           break;
2069         if (!T->isVoidPointerType()) {
2070           QualType PT = T->getAs<PointerType>()->getPointeeType();
2071           if (!PT->isStructureType())
2072             break;
2073         }
2074         Context.setObjCIdRedefinitionType(T);
2075         // Install the built-in type for 'id', ignoring the current definition.
2076         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2077         return;
2078       }
2079     case 5:
2080       if (!TypeID->isStr("Class"))
2081         break;
2082       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2083       // Install the built-in type for 'Class', ignoring the current definition.
2084       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2085       return;
2086     case 3:
2087       if (!TypeID->isStr("SEL"))
2088         break;
2089       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2090       // Install the built-in type for 'SEL', ignoring the current definition.
2091       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2092       return;
2093     }
2094     // Fall through - the typedef name was not a builtin type.
2095   }
2096 
2097   // Verify the old decl was also a type.
2098   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2099   if (!Old) {
2100     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2101       << New->getDeclName();
2102 
2103     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2104     if (OldD->getLocation().isValid())
2105       notePreviousDefinition(OldD, New->getLocation());
2106 
2107     return New->setInvalidDecl();
2108   }
2109 
2110   // If the old declaration is invalid, just give up here.
2111   if (Old->isInvalidDecl())
2112     return New->setInvalidDecl();
2113 
2114   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2115     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2116     auto *NewTag = New->getAnonDeclWithTypedefName();
2117     NamedDecl *Hidden = nullptr;
2118     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2119         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2120         !hasVisibleDefinition(OldTag, &Hidden)) {
2121       // There is a definition of this tag, but it is not visible. Use it
2122       // instead of our tag.
2123       New->setTypeForDecl(OldTD->getTypeForDecl());
2124       if (OldTD->isModed())
2125         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2126                                     OldTD->getUnderlyingType());
2127       else
2128         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2129 
2130       // Make the old tag definition visible.
2131       makeMergedDefinitionVisible(Hidden);
2132 
2133       // If this was an unscoped enumeration, yank all of its enumerators
2134       // out of the scope.
2135       if (isa<EnumDecl>(NewTag)) {
2136         Scope *EnumScope = getNonFieldDeclScope(S);
2137         for (auto *D : NewTag->decls()) {
2138           auto *ED = cast<EnumConstantDecl>(D);
2139           assert(EnumScope->isDeclScope(ED));
2140           EnumScope->RemoveDecl(ED);
2141           IdResolver.RemoveDecl(ED);
2142           ED->getLexicalDeclContext()->removeDecl(ED);
2143         }
2144       }
2145     }
2146   }
2147 
2148   // If the typedef types are not identical, reject them in all languages and
2149   // with any extensions enabled.
2150   if (isIncompatibleTypedef(Old, New))
2151     return;
2152 
2153   // The types match.  Link up the redeclaration chain and merge attributes if
2154   // the old declaration was a typedef.
2155   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2156     New->setPreviousDecl(Typedef);
2157     mergeDeclAttributes(New, Old);
2158   }
2159 
2160   if (getLangOpts().MicrosoftExt)
2161     return;
2162 
2163   if (getLangOpts().CPlusPlus) {
2164     // C++ [dcl.typedef]p2:
2165     //   In a given non-class scope, a typedef specifier can be used to
2166     //   redefine the name of any type declared in that scope to refer
2167     //   to the type to which it already refers.
2168     if (!isa<CXXRecordDecl>(CurContext))
2169       return;
2170 
2171     // C++0x [dcl.typedef]p4:
2172     //   In a given class scope, a typedef specifier can be used to redefine
2173     //   any class-name declared in that scope that is not also a typedef-name
2174     //   to refer to the type to which it already refers.
2175     //
2176     // This wording came in via DR424, which was a correction to the
2177     // wording in DR56, which accidentally banned code like:
2178     //
2179     //   struct S {
2180     //     typedef struct A { } A;
2181     //   };
2182     //
2183     // in the C++03 standard. We implement the C++0x semantics, which
2184     // allow the above but disallow
2185     //
2186     //   struct S {
2187     //     typedef int I;
2188     //     typedef int I;
2189     //   };
2190     //
2191     // since that was the intent of DR56.
2192     if (!isa<TypedefNameDecl>(Old))
2193       return;
2194 
2195     Diag(New->getLocation(), diag::err_redefinition)
2196       << New->getDeclName();
2197     notePreviousDefinition(Old, New->getLocation());
2198     return New->setInvalidDecl();
2199   }
2200 
2201   // Modules always permit redefinition of typedefs, as does C11.
2202   if (getLangOpts().Modules || getLangOpts().C11)
2203     return;
2204 
2205   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2206   // is normally mapped to an error, but can be controlled with
2207   // -Wtypedef-redefinition.  If either the original or the redefinition is
2208   // in a system header, don't emit this for compatibility with GCC.
2209   if (getDiagnostics().getSuppressSystemWarnings() &&
2210       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2211       (Old->isImplicit() ||
2212        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2213        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2214     return;
2215 
2216   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2217     << New->getDeclName();
2218   notePreviousDefinition(Old, New->getLocation());
2219 }
2220 
2221 /// DeclhasAttr - returns true if decl Declaration already has the target
2222 /// attribute.
2223 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2224   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2225   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2226   for (const auto *i : D->attrs())
2227     if (i->getKind() == A->getKind()) {
2228       if (Ann) {
2229         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2230           return true;
2231         continue;
2232       }
2233       // FIXME: Don't hardcode this check
2234       if (OA && isa<OwnershipAttr>(i))
2235         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2236       return true;
2237     }
2238 
2239   return false;
2240 }
2241 
2242 static bool isAttributeTargetADefinition(Decl *D) {
2243   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2244     return VD->isThisDeclarationADefinition();
2245   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2246     return TD->isCompleteDefinition() || TD->isBeingDefined();
2247   return true;
2248 }
2249 
2250 /// Merge alignment attributes from \p Old to \p New, taking into account the
2251 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2252 ///
2253 /// \return \c true if any attributes were added to \p New.
2254 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2255   // Look for alignas attributes on Old, and pick out whichever attribute
2256   // specifies the strictest alignment requirement.
2257   AlignedAttr *OldAlignasAttr = nullptr;
2258   AlignedAttr *OldStrictestAlignAttr = nullptr;
2259   unsigned OldAlign = 0;
2260   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2261     // FIXME: We have no way of representing inherited dependent alignments
2262     // in a case like:
2263     //   template<int A, int B> struct alignas(A) X;
2264     //   template<int A, int B> struct alignas(B) X {};
2265     // For now, we just ignore any alignas attributes which are not on the
2266     // definition in such a case.
2267     if (I->isAlignmentDependent())
2268       return false;
2269 
2270     if (I->isAlignas())
2271       OldAlignasAttr = I;
2272 
2273     unsigned Align = I->getAlignment(S.Context);
2274     if (Align > OldAlign) {
2275       OldAlign = Align;
2276       OldStrictestAlignAttr = I;
2277     }
2278   }
2279 
2280   // Look for alignas attributes on New.
2281   AlignedAttr *NewAlignasAttr = nullptr;
2282   unsigned NewAlign = 0;
2283   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2284     if (I->isAlignmentDependent())
2285       return false;
2286 
2287     if (I->isAlignas())
2288       NewAlignasAttr = I;
2289 
2290     unsigned Align = I->getAlignment(S.Context);
2291     if (Align > NewAlign)
2292       NewAlign = Align;
2293   }
2294 
2295   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2296     // Both declarations have 'alignas' attributes. We require them to match.
2297     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2298     // fall short. (If two declarations both have alignas, they must both match
2299     // every definition, and so must match each other if there is a definition.)
2300 
2301     // If either declaration only contains 'alignas(0)' specifiers, then it
2302     // specifies the natural alignment for the type.
2303     if (OldAlign == 0 || NewAlign == 0) {
2304       QualType Ty;
2305       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2306         Ty = VD->getType();
2307       else
2308         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2309 
2310       if (OldAlign == 0)
2311         OldAlign = S.Context.getTypeAlign(Ty);
2312       if (NewAlign == 0)
2313         NewAlign = S.Context.getTypeAlign(Ty);
2314     }
2315 
2316     if (OldAlign != NewAlign) {
2317       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2318         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2319         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2320       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2321     }
2322   }
2323 
2324   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2325     // C++11 [dcl.align]p6:
2326     //   if any declaration of an entity has an alignment-specifier,
2327     //   every defining declaration of that entity shall specify an
2328     //   equivalent alignment.
2329     // C11 6.7.5/7:
2330     //   If the definition of an object does not have an alignment
2331     //   specifier, any other declaration of that object shall also
2332     //   have no alignment specifier.
2333     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2334       << OldAlignasAttr;
2335     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2336       << OldAlignasAttr;
2337   }
2338 
2339   bool AnyAdded = false;
2340 
2341   // Ensure we have an attribute representing the strictest alignment.
2342   if (OldAlign > NewAlign) {
2343     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2344     Clone->setInherited(true);
2345     New->addAttr(Clone);
2346     AnyAdded = true;
2347   }
2348 
2349   // Ensure we have an alignas attribute if the old declaration had one.
2350   if (OldAlignasAttr && !NewAlignasAttr &&
2351       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2352     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2353     Clone->setInherited(true);
2354     New->addAttr(Clone);
2355     AnyAdded = true;
2356   }
2357 
2358   return AnyAdded;
2359 }
2360 
2361 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2362                                const InheritableAttr *Attr,
2363                                Sema::AvailabilityMergeKind AMK) {
2364   // This function copies an attribute Attr from a previous declaration to the
2365   // new declaration D if the new declaration doesn't itself have that attribute
2366   // yet or if that attribute allows duplicates.
2367   // If you're adding a new attribute that requires logic different from
2368   // "use explicit attribute on decl if present, else use attribute from
2369   // previous decl", for example if the attribute needs to be consistent
2370   // between redeclarations, you need to call a custom merge function here.
2371   InheritableAttr *NewAttr = nullptr;
2372   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2373   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2374     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2375                                       AA->isImplicit(), AA->getIntroduced(),
2376                                       AA->getDeprecated(),
2377                                       AA->getObsoleted(), AA->getUnavailable(),
2378                                       AA->getMessage(), AA->getStrict(),
2379                                       AA->getReplacement(), AMK,
2380                                       AttrSpellingListIndex);
2381   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2382     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2383                                     AttrSpellingListIndex);
2384   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2385     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2386                                         AttrSpellingListIndex);
2387   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2388     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2389                                    AttrSpellingListIndex);
2390   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2391     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2392                                    AttrSpellingListIndex);
2393   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2394     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2395                                 FA->getFormatIdx(), FA->getFirstArg(),
2396                                 AttrSpellingListIndex);
2397   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2398     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2399                                  AttrSpellingListIndex);
2400   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2401     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2402                                        AttrSpellingListIndex,
2403                                        IA->getSemanticSpelling());
2404   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2405     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2406                                       &S.Context.Idents.get(AA->getSpelling()),
2407                                       AttrSpellingListIndex);
2408   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2409            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2410             isa<CUDAGlobalAttr>(Attr))) {
2411     // CUDA target attributes are part of function signature for
2412     // overloading purposes and must not be merged.
2413     return false;
2414   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2415     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2416   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2417     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2418   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2419     NewAttr = S.mergeInternalLinkageAttr(
2420         D, InternalLinkageA->getRange(),
2421         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2422         AttrSpellingListIndex);
2423   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2424     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2425                                 &S.Context.Idents.get(CommonA->getSpelling()),
2426                                 AttrSpellingListIndex);
2427   else if (isa<AlignedAttr>(Attr))
2428     // AlignedAttrs are handled separately, because we need to handle all
2429     // such attributes on a declaration at the same time.
2430     NewAttr = nullptr;
2431   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2432            (AMK == Sema::AMK_Override ||
2433             AMK == Sema::AMK_ProtocolImplementation))
2434     NewAttr = nullptr;
2435   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2436     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2437                               UA->getGuid());
2438   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2439     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2440 
2441   if (NewAttr) {
2442     NewAttr->setInherited(true);
2443     D->addAttr(NewAttr);
2444     if (isa<MSInheritanceAttr>(NewAttr))
2445       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2446     return true;
2447   }
2448 
2449   return false;
2450 }
2451 
2452 static const NamedDecl *getDefinition(const Decl *D) {
2453   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2454     return TD->getDefinition();
2455   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2456     const VarDecl *Def = VD->getDefinition();
2457     if (Def)
2458       return Def;
2459     return VD->getActingDefinition();
2460   }
2461   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2462     return FD->getDefinition();
2463   return nullptr;
2464 }
2465 
2466 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2467   for (const auto *Attribute : D->attrs())
2468     if (Attribute->getKind() == Kind)
2469       return true;
2470   return false;
2471 }
2472 
2473 /// checkNewAttributesAfterDef - If we already have a definition, check that
2474 /// there are no new attributes in this declaration.
2475 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2476   if (!New->hasAttrs())
2477     return;
2478 
2479   const NamedDecl *Def = getDefinition(Old);
2480   if (!Def || Def == New)
2481     return;
2482 
2483   AttrVec &NewAttributes = New->getAttrs();
2484   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2485     const Attr *NewAttribute = NewAttributes[I];
2486 
2487     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2488       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2489         Sema::SkipBodyInfo SkipBody;
2490         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2491 
2492         // If we're skipping this definition, drop the "alias" attribute.
2493         if (SkipBody.ShouldSkip) {
2494           NewAttributes.erase(NewAttributes.begin() + I);
2495           --E;
2496           continue;
2497         }
2498       } else {
2499         VarDecl *VD = cast<VarDecl>(New);
2500         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2501                                 VarDecl::TentativeDefinition
2502                             ? diag::err_alias_after_tentative
2503                             : diag::err_redefinition;
2504         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2505         if (Diag == diag::err_redefinition)
2506           S.notePreviousDefinition(Def, VD->getLocation());
2507         else
2508           S.Diag(Def->getLocation(), diag::note_previous_definition);
2509         VD->setInvalidDecl();
2510       }
2511       ++I;
2512       continue;
2513     }
2514 
2515     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2516       // Tentative definitions are only interesting for the alias check above.
2517       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2518         ++I;
2519         continue;
2520       }
2521     }
2522 
2523     if (hasAttribute(Def, NewAttribute->getKind())) {
2524       ++I;
2525       continue; // regular attr merging will take care of validating this.
2526     }
2527 
2528     if (isa<C11NoReturnAttr>(NewAttribute)) {
2529       // C's _Noreturn is allowed to be added to a function after it is defined.
2530       ++I;
2531       continue;
2532     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2533       if (AA->isAlignas()) {
2534         // C++11 [dcl.align]p6:
2535         //   if any declaration of an entity has an alignment-specifier,
2536         //   every defining declaration of that entity shall specify an
2537         //   equivalent alignment.
2538         // C11 6.7.5/7:
2539         //   If the definition of an object does not have an alignment
2540         //   specifier, any other declaration of that object shall also
2541         //   have no alignment specifier.
2542         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2543           << AA;
2544         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2545           << AA;
2546         NewAttributes.erase(NewAttributes.begin() + I);
2547         --E;
2548         continue;
2549       }
2550     }
2551 
2552     S.Diag(NewAttribute->getLocation(),
2553            diag::warn_attribute_precede_definition);
2554     S.Diag(Def->getLocation(), diag::note_previous_definition);
2555     NewAttributes.erase(NewAttributes.begin() + I);
2556     --E;
2557   }
2558 }
2559 
2560 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2561 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2562                                AvailabilityMergeKind AMK) {
2563   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2564     UsedAttr *NewAttr = OldAttr->clone(Context);
2565     NewAttr->setInherited(true);
2566     New->addAttr(NewAttr);
2567   }
2568 
2569   if (!Old->hasAttrs() && !New->hasAttrs())
2570     return;
2571 
2572   // Attributes declared post-definition are currently ignored.
2573   checkNewAttributesAfterDef(*this, New, Old);
2574 
2575   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2576     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2577       if (OldA->getLabel() != NewA->getLabel()) {
2578         // This redeclaration changes __asm__ label.
2579         Diag(New->getLocation(), diag::err_different_asm_label);
2580         Diag(OldA->getLocation(), diag::note_previous_declaration);
2581       }
2582     } else if (Old->isUsed()) {
2583       // This redeclaration adds an __asm__ label to a declaration that has
2584       // already been ODR-used.
2585       Diag(New->getLocation(), diag::err_late_asm_label_name)
2586         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2587     }
2588   }
2589 
2590   // Re-declaration cannot add abi_tag's.
2591   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2592     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2593       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2594         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2595                       NewTag) == OldAbiTagAttr->tags_end()) {
2596           Diag(NewAbiTagAttr->getLocation(),
2597                diag::err_new_abi_tag_on_redeclaration)
2598               << NewTag;
2599           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2600         }
2601       }
2602     } else {
2603       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2604       Diag(Old->getLocation(), diag::note_previous_declaration);
2605     }
2606   }
2607 
2608   if (!Old->hasAttrs())
2609     return;
2610 
2611   bool foundAny = New->hasAttrs();
2612 
2613   // Ensure that any moving of objects within the allocated map is done before
2614   // we process them.
2615   if (!foundAny) New->setAttrs(AttrVec());
2616 
2617   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2618     // Ignore deprecated/unavailable/availability attributes if requested.
2619     AvailabilityMergeKind LocalAMK = AMK_None;
2620     if (isa<DeprecatedAttr>(I) ||
2621         isa<UnavailableAttr>(I) ||
2622         isa<AvailabilityAttr>(I)) {
2623       switch (AMK) {
2624       case AMK_None:
2625         continue;
2626 
2627       case AMK_Redeclaration:
2628       case AMK_Override:
2629       case AMK_ProtocolImplementation:
2630         LocalAMK = AMK;
2631         break;
2632       }
2633     }
2634 
2635     // Already handled.
2636     if (isa<UsedAttr>(I))
2637       continue;
2638 
2639     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2640       foundAny = true;
2641   }
2642 
2643   if (mergeAlignedAttrs(*this, New, Old))
2644     foundAny = true;
2645 
2646   if (!foundAny) New->dropAttrs();
2647 }
2648 
2649 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2650 /// to the new one.
2651 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2652                                      const ParmVarDecl *oldDecl,
2653                                      Sema &S) {
2654   // C++11 [dcl.attr.depend]p2:
2655   //   The first declaration of a function shall specify the
2656   //   carries_dependency attribute for its declarator-id if any declaration
2657   //   of the function specifies the carries_dependency attribute.
2658   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2659   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2660     S.Diag(CDA->getLocation(),
2661            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2662     // Find the first declaration of the parameter.
2663     // FIXME: Should we build redeclaration chains for function parameters?
2664     const FunctionDecl *FirstFD =
2665       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2666     const ParmVarDecl *FirstVD =
2667       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2668     S.Diag(FirstVD->getLocation(),
2669            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2670   }
2671 
2672   if (!oldDecl->hasAttrs())
2673     return;
2674 
2675   bool foundAny = newDecl->hasAttrs();
2676 
2677   // Ensure that any moving of objects within the allocated map is
2678   // done before we process them.
2679   if (!foundAny) newDecl->setAttrs(AttrVec());
2680 
2681   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2682     if (!DeclHasAttr(newDecl, I)) {
2683       InheritableAttr *newAttr =
2684         cast<InheritableParamAttr>(I->clone(S.Context));
2685       newAttr->setInherited(true);
2686       newDecl->addAttr(newAttr);
2687       foundAny = true;
2688     }
2689   }
2690 
2691   if (!foundAny) newDecl->dropAttrs();
2692 }
2693 
2694 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2695                                 const ParmVarDecl *OldParam,
2696                                 Sema &S) {
2697   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2698     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2699       if (*Oldnullability != *Newnullability) {
2700         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2701           << DiagNullabilityKind(
2702                *Newnullability,
2703                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2704                 != 0))
2705           << DiagNullabilityKind(
2706                *Oldnullability,
2707                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2708                 != 0));
2709         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2710       }
2711     } else {
2712       QualType NewT = NewParam->getType();
2713       NewT = S.Context.getAttributedType(
2714                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2715                          NewT, NewT);
2716       NewParam->setType(NewT);
2717     }
2718   }
2719 }
2720 
2721 namespace {
2722 
2723 /// Used in MergeFunctionDecl to keep track of function parameters in
2724 /// C.
2725 struct GNUCompatibleParamWarning {
2726   ParmVarDecl *OldParm;
2727   ParmVarDecl *NewParm;
2728   QualType PromotedType;
2729 };
2730 
2731 } // end anonymous namespace
2732 
2733 /// getSpecialMember - get the special member enum for a method.
2734 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2735   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2736     if (Ctor->isDefaultConstructor())
2737       return Sema::CXXDefaultConstructor;
2738 
2739     if (Ctor->isCopyConstructor())
2740       return Sema::CXXCopyConstructor;
2741 
2742     if (Ctor->isMoveConstructor())
2743       return Sema::CXXMoveConstructor;
2744   } else if (isa<CXXDestructorDecl>(MD)) {
2745     return Sema::CXXDestructor;
2746   } else if (MD->isCopyAssignmentOperator()) {
2747     return Sema::CXXCopyAssignment;
2748   } else if (MD->isMoveAssignmentOperator()) {
2749     return Sema::CXXMoveAssignment;
2750   }
2751 
2752   return Sema::CXXInvalid;
2753 }
2754 
2755 // Determine whether the previous declaration was a definition, implicit
2756 // declaration, or a declaration.
2757 template <typename T>
2758 static std::pair<diag::kind, SourceLocation>
2759 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2760   diag::kind PrevDiag;
2761   SourceLocation OldLocation = Old->getLocation();
2762   if (Old->isThisDeclarationADefinition())
2763     PrevDiag = diag::note_previous_definition;
2764   else if (Old->isImplicit()) {
2765     PrevDiag = diag::note_previous_implicit_declaration;
2766     if (OldLocation.isInvalid())
2767       OldLocation = New->getLocation();
2768   } else
2769     PrevDiag = diag::note_previous_declaration;
2770   return std::make_pair(PrevDiag, OldLocation);
2771 }
2772 
2773 /// canRedefineFunction - checks if a function can be redefined. Currently,
2774 /// only extern inline functions can be redefined, and even then only in
2775 /// GNU89 mode.
2776 static bool canRedefineFunction(const FunctionDecl *FD,
2777                                 const LangOptions& LangOpts) {
2778   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2779           !LangOpts.CPlusPlus &&
2780           FD->isInlineSpecified() &&
2781           FD->getStorageClass() == SC_Extern);
2782 }
2783 
2784 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2785   const AttributedType *AT = T->getAs<AttributedType>();
2786   while (AT && !AT->isCallingConv())
2787     AT = AT->getModifiedType()->getAs<AttributedType>();
2788   return AT;
2789 }
2790 
2791 template <typename T>
2792 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2793   const DeclContext *DC = Old->getDeclContext();
2794   if (DC->isRecord())
2795     return false;
2796 
2797   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2798   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2799     return true;
2800   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2801     return true;
2802   return false;
2803 }
2804 
2805 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2806 static bool isExternC(VarTemplateDecl *) { return false; }
2807 
2808 /// \brief Check whether a redeclaration of an entity introduced by a
2809 /// using-declaration is valid, given that we know it's not an overload
2810 /// (nor a hidden tag declaration).
2811 template<typename ExpectedDecl>
2812 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2813                                    ExpectedDecl *New) {
2814   // C++11 [basic.scope.declarative]p4:
2815   //   Given a set of declarations in a single declarative region, each of
2816   //   which specifies the same unqualified name,
2817   //   -- they shall all refer to the same entity, or all refer to functions
2818   //      and function templates; or
2819   //   -- exactly one declaration shall declare a class name or enumeration
2820   //      name that is not a typedef name and the other declarations shall all
2821   //      refer to the same variable or enumerator, or all refer to functions
2822   //      and function templates; in this case the class name or enumeration
2823   //      name is hidden (3.3.10).
2824 
2825   // C++11 [namespace.udecl]p14:
2826   //   If a function declaration in namespace scope or block scope has the
2827   //   same name and the same parameter-type-list as a function introduced
2828   //   by a using-declaration, and the declarations do not declare the same
2829   //   function, the program is ill-formed.
2830 
2831   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2832   if (Old &&
2833       !Old->getDeclContext()->getRedeclContext()->Equals(
2834           New->getDeclContext()->getRedeclContext()) &&
2835       !(isExternC(Old) && isExternC(New)))
2836     Old = nullptr;
2837 
2838   if (!Old) {
2839     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2840     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2841     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2842     return true;
2843   }
2844   return false;
2845 }
2846 
2847 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2848                                             const FunctionDecl *B) {
2849   assert(A->getNumParams() == B->getNumParams());
2850 
2851   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2852     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2853     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2854     if (AttrA == AttrB)
2855       return true;
2856     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2857   };
2858 
2859   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2860 }
2861 
2862 /// MergeFunctionDecl - We just parsed a function 'New' from
2863 /// declarator D which has the same name and scope as a previous
2864 /// declaration 'Old'.  Figure out how to resolve this situation,
2865 /// merging decls or emitting diagnostics as appropriate.
2866 ///
2867 /// In C++, New and Old must be declarations that are not
2868 /// overloaded. Use IsOverload to determine whether New and Old are
2869 /// overloaded, and to select the Old declaration that New should be
2870 /// merged with.
2871 ///
2872 /// Returns true if there was an error, false otherwise.
2873 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2874                              Scope *S, bool MergeTypeWithOld) {
2875   // Verify the old decl was also a function.
2876   FunctionDecl *Old = OldD->getAsFunction();
2877   if (!Old) {
2878     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2879       if (New->getFriendObjectKind()) {
2880         Diag(New->getLocation(), diag::err_using_decl_friend);
2881         Diag(Shadow->getTargetDecl()->getLocation(),
2882              diag::note_using_decl_target);
2883         Diag(Shadow->getUsingDecl()->getLocation(),
2884              diag::note_using_decl) << 0;
2885         return true;
2886       }
2887 
2888       // Check whether the two declarations might declare the same function.
2889       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2890         return true;
2891       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2892     } else {
2893       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2894         << New->getDeclName();
2895       notePreviousDefinition(OldD, New->getLocation());
2896       return true;
2897     }
2898   }
2899 
2900   // If the old declaration is invalid, just give up here.
2901   if (Old->isInvalidDecl())
2902     return true;
2903 
2904   diag::kind PrevDiag;
2905   SourceLocation OldLocation;
2906   std::tie(PrevDiag, OldLocation) =
2907       getNoteDiagForInvalidRedeclaration(Old, New);
2908 
2909   // Don't complain about this if we're in GNU89 mode and the old function
2910   // is an extern inline function.
2911   // Don't complain about specializations. They are not supposed to have
2912   // storage classes.
2913   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2914       New->getStorageClass() == SC_Static &&
2915       Old->hasExternalFormalLinkage() &&
2916       !New->getTemplateSpecializationInfo() &&
2917       !canRedefineFunction(Old, getLangOpts())) {
2918     if (getLangOpts().MicrosoftExt) {
2919       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2920       Diag(OldLocation, PrevDiag);
2921     } else {
2922       Diag(New->getLocation(), diag::err_static_non_static) << New;
2923       Diag(OldLocation, PrevDiag);
2924       return true;
2925     }
2926   }
2927 
2928   if (New->hasAttr<InternalLinkageAttr>() &&
2929       !Old->hasAttr<InternalLinkageAttr>()) {
2930     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2931         << New->getDeclName();
2932     notePreviousDefinition(Old, New->getLocation());
2933     New->dropAttr<InternalLinkageAttr>();
2934   }
2935 
2936   // If a function is first declared with a calling convention, but is later
2937   // declared or defined without one, all following decls assume the calling
2938   // convention of the first.
2939   //
2940   // It's OK if a function is first declared without a calling convention,
2941   // but is later declared or defined with the default calling convention.
2942   //
2943   // To test if either decl has an explicit calling convention, we look for
2944   // AttributedType sugar nodes on the type as written.  If they are missing or
2945   // were canonicalized away, we assume the calling convention was implicit.
2946   //
2947   // Note also that we DO NOT return at this point, because we still have
2948   // other tests to run.
2949   QualType OldQType = Context.getCanonicalType(Old->getType());
2950   QualType NewQType = Context.getCanonicalType(New->getType());
2951   const FunctionType *OldType = cast<FunctionType>(OldQType);
2952   const FunctionType *NewType = cast<FunctionType>(NewQType);
2953   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2954   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2955   bool RequiresAdjustment = false;
2956 
2957   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2958     FunctionDecl *First = Old->getFirstDecl();
2959     const FunctionType *FT =
2960         First->getType().getCanonicalType()->castAs<FunctionType>();
2961     FunctionType::ExtInfo FI = FT->getExtInfo();
2962     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2963     if (!NewCCExplicit) {
2964       // Inherit the CC from the previous declaration if it was specified
2965       // there but not here.
2966       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2967       RequiresAdjustment = true;
2968     } else {
2969       // Calling conventions aren't compatible, so complain.
2970       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2971       Diag(New->getLocation(), diag::err_cconv_change)
2972         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2973         << !FirstCCExplicit
2974         << (!FirstCCExplicit ? "" :
2975             FunctionType::getNameForCallConv(FI.getCC()));
2976 
2977       // Put the note on the first decl, since it is the one that matters.
2978       Diag(First->getLocation(), diag::note_previous_declaration);
2979       return true;
2980     }
2981   }
2982 
2983   // FIXME: diagnose the other way around?
2984   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2985     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2986     RequiresAdjustment = true;
2987   }
2988 
2989   // Merge regparm attribute.
2990   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2991       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2992     if (NewTypeInfo.getHasRegParm()) {
2993       Diag(New->getLocation(), diag::err_regparm_mismatch)
2994         << NewType->getRegParmType()
2995         << OldType->getRegParmType();
2996       Diag(OldLocation, diag::note_previous_declaration);
2997       return true;
2998     }
2999 
3000     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3001     RequiresAdjustment = true;
3002   }
3003 
3004   // Merge ns_returns_retained attribute.
3005   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3006     if (NewTypeInfo.getProducesResult()) {
3007       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3008           << "'ns_returns_retained'";
3009       Diag(OldLocation, diag::note_previous_declaration);
3010       return true;
3011     }
3012 
3013     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3014     RequiresAdjustment = true;
3015   }
3016 
3017   if (OldTypeInfo.getNoCallerSavedRegs() !=
3018       NewTypeInfo.getNoCallerSavedRegs()) {
3019     if (NewTypeInfo.getNoCallerSavedRegs()) {
3020       AnyX86NoCallerSavedRegistersAttr *Attr =
3021         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3022       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3023       Diag(OldLocation, diag::note_previous_declaration);
3024       return true;
3025     }
3026 
3027     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3028     RequiresAdjustment = true;
3029   }
3030 
3031   if (RequiresAdjustment) {
3032     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3033     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3034     New->setType(QualType(AdjustedType, 0));
3035     NewQType = Context.getCanonicalType(New->getType());
3036     NewType = cast<FunctionType>(NewQType);
3037   }
3038 
3039   // If this redeclaration makes the function inline, we may need to add it to
3040   // UndefinedButUsed.
3041   if (!Old->isInlined() && New->isInlined() &&
3042       !New->hasAttr<GNUInlineAttr>() &&
3043       !getLangOpts().GNUInline &&
3044       Old->isUsed(false) &&
3045       !Old->isDefined() && !New->isThisDeclarationADefinition())
3046     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3047                                            SourceLocation()));
3048 
3049   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3050   // about it.
3051   if (New->hasAttr<GNUInlineAttr>() &&
3052       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3053     UndefinedButUsed.erase(Old->getCanonicalDecl());
3054   }
3055 
3056   // If pass_object_size params don't match up perfectly, this isn't a valid
3057   // redeclaration.
3058   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3059       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3060     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3061         << New->getDeclName();
3062     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3063     return true;
3064   }
3065 
3066   if (getLangOpts().CPlusPlus) {
3067     // C++1z [over.load]p2
3068     //   Certain function declarations cannot be overloaded:
3069     //     -- Function declarations that differ only in the return type,
3070     //        the exception specification, or both cannot be overloaded.
3071 
3072     // Check the exception specifications match. This may recompute the type of
3073     // both Old and New if it resolved exception specifications, so grab the
3074     // types again after this. Because this updates the type, we do this before
3075     // any of the other checks below, which may update the "de facto" NewQType
3076     // but do not necessarily update the type of New.
3077     if (CheckEquivalentExceptionSpec(Old, New))
3078       return true;
3079     OldQType = Context.getCanonicalType(Old->getType());
3080     NewQType = Context.getCanonicalType(New->getType());
3081 
3082     // Go back to the type source info to compare the declared return types,
3083     // per C++1y [dcl.type.auto]p13:
3084     //   Redeclarations or specializations of a function or function template
3085     //   with a declared return type that uses a placeholder type shall also
3086     //   use that placeholder, not a deduced type.
3087     QualType OldDeclaredReturnType =
3088         (Old->getTypeSourceInfo()
3089              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3090              : OldType)->getReturnType();
3091     QualType NewDeclaredReturnType =
3092         (New->getTypeSourceInfo()
3093              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3094              : NewType)->getReturnType();
3095     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3096         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3097           New->isLocalExternDecl())) {
3098       QualType ResQT;
3099       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3100           OldDeclaredReturnType->isObjCObjectPointerType())
3101         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3102       if (ResQT.isNull()) {
3103         if (New->isCXXClassMember() && New->isOutOfLine())
3104           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3105               << New << New->getReturnTypeSourceRange();
3106         else
3107           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3108               << New->getReturnTypeSourceRange();
3109         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3110                                     << Old->getReturnTypeSourceRange();
3111         return true;
3112       }
3113       else
3114         NewQType = ResQT;
3115     }
3116 
3117     QualType OldReturnType = OldType->getReturnType();
3118     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3119     if (OldReturnType != NewReturnType) {
3120       // If this function has a deduced return type and has already been
3121       // defined, copy the deduced value from the old declaration.
3122       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3123       if (OldAT && OldAT->isDeduced()) {
3124         New->setType(
3125             SubstAutoType(New->getType(),
3126                           OldAT->isDependentType() ? Context.DependentTy
3127                                                    : OldAT->getDeducedType()));
3128         NewQType = Context.getCanonicalType(
3129             SubstAutoType(NewQType,
3130                           OldAT->isDependentType() ? Context.DependentTy
3131                                                    : OldAT->getDeducedType()));
3132       }
3133     }
3134 
3135     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3136     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3137     if (OldMethod && NewMethod) {
3138       // Preserve triviality.
3139       NewMethod->setTrivial(OldMethod->isTrivial());
3140 
3141       // MSVC allows explicit template specialization at class scope:
3142       // 2 CXXMethodDecls referring to the same function will be injected.
3143       // We don't want a redeclaration error.
3144       bool IsClassScopeExplicitSpecialization =
3145                               OldMethod->isFunctionTemplateSpecialization() &&
3146                               NewMethod->isFunctionTemplateSpecialization();
3147       bool isFriend = NewMethod->getFriendObjectKind();
3148 
3149       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3150           !IsClassScopeExplicitSpecialization) {
3151         //    -- Member function declarations with the same name and the
3152         //       same parameter types cannot be overloaded if any of them
3153         //       is a static member function declaration.
3154         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3155           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3156           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3157           return true;
3158         }
3159 
3160         // C++ [class.mem]p1:
3161         //   [...] A member shall not be declared twice in the
3162         //   member-specification, except that a nested class or member
3163         //   class template can be declared and then later defined.
3164         if (!inTemplateInstantiation()) {
3165           unsigned NewDiag;
3166           if (isa<CXXConstructorDecl>(OldMethod))
3167             NewDiag = diag::err_constructor_redeclared;
3168           else if (isa<CXXDestructorDecl>(NewMethod))
3169             NewDiag = diag::err_destructor_redeclared;
3170           else if (isa<CXXConversionDecl>(NewMethod))
3171             NewDiag = diag::err_conv_function_redeclared;
3172           else
3173             NewDiag = diag::err_member_redeclared;
3174 
3175           Diag(New->getLocation(), NewDiag);
3176         } else {
3177           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3178             << New << New->getType();
3179         }
3180         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3181         return true;
3182 
3183       // Complain if this is an explicit declaration of a special
3184       // member that was initially declared implicitly.
3185       //
3186       // As an exception, it's okay to befriend such methods in order
3187       // to permit the implicit constructor/destructor/operator calls.
3188       } else if (OldMethod->isImplicit()) {
3189         if (isFriend) {
3190           NewMethod->setImplicit();
3191         } else {
3192           Diag(NewMethod->getLocation(),
3193                diag::err_definition_of_implicitly_declared_member)
3194             << New << getSpecialMember(OldMethod);
3195           return true;
3196         }
3197       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3198         Diag(NewMethod->getLocation(),
3199              diag::err_definition_of_explicitly_defaulted_member)
3200           << getSpecialMember(OldMethod);
3201         return true;
3202       }
3203     }
3204 
3205     // C++11 [dcl.attr.noreturn]p1:
3206     //   The first declaration of a function shall specify the noreturn
3207     //   attribute if any declaration of that function specifies the noreturn
3208     //   attribute.
3209     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3210     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3211       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3212       Diag(Old->getFirstDecl()->getLocation(),
3213            diag::note_noreturn_missing_first_decl);
3214     }
3215 
3216     // C++11 [dcl.attr.depend]p2:
3217     //   The first declaration of a function shall specify the
3218     //   carries_dependency attribute for its declarator-id if any declaration
3219     //   of the function specifies the carries_dependency attribute.
3220     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3221     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3222       Diag(CDA->getLocation(),
3223            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3224       Diag(Old->getFirstDecl()->getLocation(),
3225            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3226     }
3227 
3228     // (C++98 8.3.5p3):
3229     //   All declarations for a function shall agree exactly in both the
3230     //   return type and the parameter-type-list.
3231     // We also want to respect all the extended bits except noreturn.
3232 
3233     // noreturn should now match unless the old type info didn't have it.
3234     QualType OldQTypeForComparison = OldQType;
3235     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3236       auto *OldType = OldQType->castAs<FunctionProtoType>();
3237       const FunctionType *OldTypeForComparison
3238         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3239       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3240       assert(OldQTypeForComparison.isCanonical());
3241     }
3242 
3243     if (haveIncompatibleLanguageLinkages(Old, New)) {
3244       // As a special case, retain the language linkage from previous
3245       // declarations of a friend function as an extension.
3246       //
3247       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3248       // and is useful because there's otherwise no way to specify language
3249       // linkage within class scope.
3250       //
3251       // Check cautiously as the friend object kind isn't yet complete.
3252       if (New->getFriendObjectKind() != Decl::FOK_None) {
3253         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3254         Diag(OldLocation, PrevDiag);
3255       } else {
3256         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3257         Diag(OldLocation, PrevDiag);
3258         return true;
3259       }
3260     }
3261 
3262     if (OldQTypeForComparison == NewQType)
3263       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3264 
3265     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3266         New->isLocalExternDecl()) {
3267       // It's OK if we couldn't merge types for a local function declaraton
3268       // if either the old or new type is dependent. We'll merge the types
3269       // when we instantiate the function.
3270       return false;
3271     }
3272 
3273     // Fall through for conflicting redeclarations and redefinitions.
3274   }
3275 
3276   // C: Function types need to be compatible, not identical. This handles
3277   // duplicate function decls like "void f(int); void f(enum X);" properly.
3278   if (!getLangOpts().CPlusPlus &&
3279       Context.typesAreCompatible(OldQType, NewQType)) {
3280     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3281     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3282     const FunctionProtoType *OldProto = nullptr;
3283     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3284         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3285       // The old declaration provided a function prototype, but the
3286       // new declaration does not. Merge in the prototype.
3287       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3288       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3289       NewQType =
3290           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3291                                   OldProto->getExtProtoInfo());
3292       New->setType(NewQType);
3293       New->setHasInheritedPrototype();
3294 
3295       // Synthesize parameters with the same types.
3296       SmallVector<ParmVarDecl*, 16> Params;
3297       for (const auto &ParamType : OldProto->param_types()) {
3298         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3299                                                  SourceLocation(), nullptr,
3300                                                  ParamType, /*TInfo=*/nullptr,
3301                                                  SC_None, nullptr);
3302         Param->setScopeInfo(0, Params.size());
3303         Param->setImplicit();
3304         Params.push_back(Param);
3305       }
3306 
3307       New->setParams(Params);
3308     }
3309 
3310     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3311   }
3312 
3313   // GNU C permits a K&R definition to follow a prototype declaration
3314   // if the declared types of the parameters in the K&R definition
3315   // match the types in the prototype declaration, even when the
3316   // promoted types of the parameters from the K&R definition differ
3317   // from the types in the prototype. GCC then keeps the types from
3318   // the prototype.
3319   //
3320   // If a variadic prototype is followed by a non-variadic K&R definition,
3321   // the K&R definition becomes variadic.  This is sort of an edge case, but
3322   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3323   // C99 6.9.1p8.
3324   if (!getLangOpts().CPlusPlus &&
3325       Old->hasPrototype() && !New->hasPrototype() &&
3326       New->getType()->getAs<FunctionProtoType>() &&
3327       Old->getNumParams() == New->getNumParams()) {
3328     SmallVector<QualType, 16> ArgTypes;
3329     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3330     const FunctionProtoType *OldProto
3331       = Old->getType()->getAs<FunctionProtoType>();
3332     const FunctionProtoType *NewProto
3333       = New->getType()->getAs<FunctionProtoType>();
3334 
3335     // Determine whether this is the GNU C extension.
3336     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3337                                                NewProto->getReturnType());
3338     bool LooseCompatible = !MergedReturn.isNull();
3339     for (unsigned Idx = 0, End = Old->getNumParams();
3340          LooseCompatible && Idx != End; ++Idx) {
3341       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3342       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3343       if (Context.typesAreCompatible(OldParm->getType(),
3344                                      NewProto->getParamType(Idx))) {
3345         ArgTypes.push_back(NewParm->getType());
3346       } else if (Context.typesAreCompatible(OldParm->getType(),
3347                                             NewParm->getType(),
3348                                             /*CompareUnqualified=*/true)) {
3349         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3350                                            NewProto->getParamType(Idx) };
3351         Warnings.push_back(Warn);
3352         ArgTypes.push_back(NewParm->getType());
3353       } else
3354         LooseCompatible = false;
3355     }
3356 
3357     if (LooseCompatible) {
3358       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3359         Diag(Warnings[Warn].NewParm->getLocation(),
3360              diag::ext_param_promoted_not_compatible_with_prototype)
3361           << Warnings[Warn].PromotedType
3362           << Warnings[Warn].OldParm->getType();
3363         if (Warnings[Warn].OldParm->getLocation().isValid())
3364           Diag(Warnings[Warn].OldParm->getLocation(),
3365                diag::note_previous_declaration);
3366       }
3367 
3368       if (MergeTypeWithOld)
3369         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3370                                              OldProto->getExtProtoInfo()));
3371       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3372     }
3373 
3374     // Fall through to diagnose conflicting types.
3375   }
3376 
3377   // A function that has already been declared has been redeclared or
3378   // defined with a different type; show an appropriate diagnostic.
3379 
3380   // If the previous declaration was an implicitly-generated builtin
3381   // declaration, then at the very least we should use a specialized note.
3382   unsigned BuiltinID;
3383   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3384     // If it's actually a library-defined builtin function like 'malloc'
3385     // or 'printf', just warn about the incompatible redeclaration.
3386     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3387       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3388       Diag(OldLocation, diag::note_previous_builtin_declaration)
3389         << Old << Old->getType();
3390 
3391       // If this is a global redeclaration, just forget hereafter
3392       // about the "builtin-ness" of the function.
3393       //
3394       // Doing this for local extern declarations is problematic.  If
3395       // the builtin declaration remains visible, a second invalid
3396       // local declaration will produce a hard error; if it doesn't
3397       // remain visible, a single bogus local redeclaration (which is
3398       // actually only a warning) could break all the downstream code.
3399       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3400         New->getIdentifier()->revertBuiltin();
3401 
3402       return false;
3403     }
3404 
3405     PrevDiag = diag::note_previous_builtin_declaration;
3406   }
3407 
3408   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3409   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3410   return true;
3411 }
3412 
3413 /// \brief Completes the merge of two function declarations that are
3414 /// known to be compatible.
3415 ///
3416 /// This routine handles the merging of attributes and other
3417 /// properties of function declarations from the old declaration to
3418 /// the new declaration, once we know that New is in fact a
3419 /// redeclaration of Old.
3420 ///
3421 /// \returns false
3422 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3423                                         Scope *S, bool MergeTypeWithOld) {
3424   // Merge the attributes
3425   mergeDeclAttributes(New, Old);
3426 
3427   // Merge "pure" flag.
3428   if (Old->isPure())
3429     New->setPure();
3430 
3431   // Merge "used" flag.
3432   if (Old->getMostRecentDecl()->isUsed(false))
3433     New->setIsUsed();
3434 
3435   // Merge attributes from the parameters.  These can mismatch with K&R
3436   // declarations.
3437   if (New->getNumParams() == Old->getNumParams())
3438       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3439         ParmVarDecl *NewParam = New->getParamDecl(i);
3440         ParmVarDecl *OldParam = Old->getParamDecl(i);
3441         mergeParamDeclAttributes(NewParam, OldParam, *this);
3442         mergeParamDeclTypes(NewParam, OldParam, *this);
3443       }
3444 
3445   if (getLangOpts().CPlusPlus)
3446     return MergeCXXFunctionDecl(New, Old, S);
3447 
3448   // Merge the function types so the we get the composite types for the return
3449   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3450   // was visible.
3451   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3452   if (!Merged.isNull() && MergeTypeWithOld)
3453     New->setType(Merged);
3454 
3455   return false;
3456 }
3457 
3458 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3459                                 ObjCMethodDecl *oldMethod) {
3460   // Merge the attributes, including deprecated/unavailable
3461   AvailabilityMergeKind MergeKind =
3462     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3463       ? AMK_ProtocolImplementation
3464       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3465                                                        : AMK_Override;
3466 
3467   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3468 
3469   // Merge attributes from the parameters.
3470   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3471                                        oe = oldMethod->param_end();
3472   for (ObjCMethodDecl::param_iterator
3473          ni = newMethod->param_begin(), ne = newMethod->param_end();
3474        ni != ne && oi != oe; ++ni, ++oi)
3475     mergeParamDeclAttributes(*ni, *oi, *this);
3476 
3477   CheckObjCMethodOverride(newMethod, oldMethod);
3478 }
3479 
3480 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3481   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3482 
3483   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3484          ? diag::err_redefinition_different_type
3485          : diag::err_redeclaration_different_type)
3486     << New->getDeclName() << New->getType() << Old->getType();
3487 
3488   diag::kind PrevDiag;
3489   SourceLocation OldLocation;
3490   std::tie(PrevDiag, OldLocation)
3491     = getNoteDiagForInvalidRedeclaration(Old, New);
3492   S.Diag(OldLocation, PrevDiag);
3493   New->setInvalidDecl();
3494 }
3495 
3496 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3497 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3498 /// emitting diagnostics as appropriate.
3499 ///
3500 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3501 /// to here in AddInitializerToDecl. We can't check them before the initializer
3502 /// is attached.
3503 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3504                              bool MergeTypeWithOld) {
3505   if (New->isInvalidDecl() || Old->isInvalidDecl())
3506     return;
3507 
3508   QualType MergedT;
3509   if (getLangOpts().CPlusPlus) {
3510     if (New->getType()->isUndeducedType()) {
3511       // We don't know what the new type is until the initializer is attached.
3512       return;
3513     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3514       // These could still be something that needs exception specs checked.
3515       return MergeVarDeclExceptionSpecs(New, Old);
3516     }
3517     // C++ [basic.link]p10:
3518     //   [...] the types specified by all declarations referring to a given
3519     //   object or function shall be identical, except that declarations for an
3520     //   array object can specify array types that differ by the presence or
3521     //   absence of a major array bound (8.3.4).
3522     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3523       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3524       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3525 
3526       // We are merging a variable declaration New into Old. If it has an array
3527       // bound, and that bound differs from Old's bound, we should diagnose the
3528       // mismatch.
3529       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3530         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3531              PrevVD = PrevVD->getPreviousDecl()) {
3532           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3533           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3534             continue;
3535 
3536           if (!Context.hasSameType(NewArray, PrevVDTy))
3537             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3538         }
3539       }
3540 
3541       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3542         if (Context.hasSameType(OldArray->getElementType(),
3543                                 NewArray->getElementType()))
3544           MergedT = New->getType();
3545       }
3546       // FIXME: Check visibility. New is hidden but has a complete type. If New
3547       // has no array bound, it should not inherit one from Old, if Old is not
3548       // visible.
3549       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3550         if (Context.hasSameType(OldArray->getElementType(),
3551                                 NewArray->getElementType()))
3552           MergedT = Old->getType();
3553       }
3554     }
3555     else if (New->getType()->isObjCObjectPointerType() &&
3556                Old->getType()->isObjCObjectPointerType()) {
3557       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3558                                               Old->getType());
3559     }
3560   } else {
3561     // C 6.2.7p2:
3562     //   All declarations that refer to the same object or function shall have
3563     //   compatible type.
3564     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3565   }
3566   if (MergedT.isNull()) {
3567     // It's OK if we couldn't merge types if either type is dependent, for a
3568     // block-scope variable. In other cases (static data members of class
3569     // templates, variable templates, ...), we require the types to be
3570     // equivalent.
3571     // FIXME: The C++ standard doesn't say anything about this.
3572     if ((New->getType()->isDependentType() ||
3573          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3574       // If the old type was dependent, we can't merge with it, so the new type
3575       // becomes dependent for now. We'll reproduce the original type when we
3576       // instantiate the TypeSourceInfo for the variable.
3577       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3578         New->setType(Context.DependentTy);
3579       return;
3580     }
3581     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3582   }
3583 
3584   // Don't actually update the type on the new declaration if the old
3585   // declaration was an extern declaration in a different scope.
3586   if (MergeTypeWithOld)
3587     New->setType(MergedT);
3588 }
3589 
3590 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3591                                   LookupResult &Previous) {
3592   // C11 6.2.7p4:
3593   //   For an identifier with internal or external linkage declared
3594   //   in a scope in which a prior declaration of that identifier is
3595   //   visible, if the prior declaration specifies internal or
3596   //   external linkage, the type of the identifier at the later
3597   //   declaration becomes the composite type.
3598   //
3599   // If the variable isn't visible, we do not merge with its type.
3600   if (Previous.isShadowed())
3601     return false;
3602 
3603   if (S.getLangOpts().CPlusPlus) {
3604     // C++11 [dcl.array]p3:
3605     //   If there is a preceding declaration of the entity in the same
3606     //   scope in which the bound was specified, an omitted array bound
3607     //   is taken to be the same as in that earlier declaration.
3608     return NewVD->isPreviousDeclInSameBlockScope() ||
3609            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3610             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3611   } else {
3612     // If the old declaration was function-local, don't merge with its
3613     // type unless we're in the same function.
3614     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3615            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3616   }
3617 }
3618 
3619 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3620 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3621 /// situation, merging decls or emitting diagnostics as appropriate.
3622 ///
3623 /// Tentative definition rules (C99 6.9.2p2) are checked by
3624 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3625 /// definitions here, since the initializer hasn't been attached.
3626 ///
3627 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3628   // If the new decl is already invalid, don't do any other checking.
3629   if (New->isInvalidDecl())
3630     return;
3631 
3632   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3633     return;
3634 
3635   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3636 
3637   // Verify the old decl was also a variable or variable template.
3638   VarDecl *Old = nullptr;
3639   VarTemplateDecl *OldTemplate = nullptr;
3640   if (Previous.isSingleResult()) {
3641     if (NewTemplate) {
3642       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3643       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3644 
3645       if (auto *Shadow =
3646               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3647         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3648           return New->setInvalidDecl();
3649     } else {
3650       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3651 
3652       if (auto *Shadow =
3653               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3654         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3655           return New->setInvalidDecl();
3656     }
3657   }
3658   if (!Old) {
3659     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3660         << New->getDeclName();
3661     notePreviousDefinition(Previous.getRepresentativeDecl(),
3662                            New->getLocation());
3663     return New->setInvalidDecl();
3664   }
3665 
3666   // Ensure the template parameters are compatible.
3667   if (NewTemplate &&
3668       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3669                                       OldTemplate->getTemplateParameters(),
3670                                       /*Complain=*/true, TPL_TemplateMatch))
3671     return New->setInvalidDecl();
3672 
3673   // C++ [class.mem]p1:
3674   //   A member shall not be declared twice in the member-specification [...]
3675   //
3676   // Here, we need only consider static data members.
3677   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3678     Diag(New->getLocation(), diag::err_duplicate_member)
3679       << New->getIdentifier();
3680     Diag(Old->getLocation(), diag::note_previous_declaration);
3681     New->setInvalidDecl();
3682   }
3683 
3684   mergeDeclAttributes(New, Old);
3685   // Warn if an already-declared variable is made a weak_import in a subsequent
3686   // declaration
3687   if (New->hasAttr<WeakImportAttr>() &&
3688       Old->getStorageClass() == SC_None &&
3689       !Old->hasAttr<WeakImportAttr>()) {
3690     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3691     notePreviousDefinition(Old, New->getLocation());
3692     // Remove weak_import attribute on new declaration.
3693     New->dropAttr<WeakImportAttr>();
3694   }
3695 
3696   if (New->hasAttr<InternalLinkageAttr>() &&
3697       !Old->hasAttr<InternalLinkageAttr>()) {
3698     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3699         << New->getDeclName();
3700     notePreviousDefinition(Old, New->getLocation());
3701     New->dropAttr<InternalLinkageAttr>();
3702   }
3703 
3704   // Merge the types.
3705   VarDecl *MostRecent = Old->getMostRecentDecl();
3706   if (MostRecent != Old) {
3707     MergeVarDeclTypes(New, MostRecent,
3708                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3709     if (New->isInvalidDecl())
3710       return;
3711   }
3712 
3713   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3714   if (New->isInvalidDecl())
3715     return;
3716 
3717   diag::kind PrevDiag;
3718   SourceLocation OldLocation;
3719   std::tie(PrevDiag, OldLocation) =
3720       getNoteDiagForInvalidRedeclaration(Old, New);
3721 
3722   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3723   if (New->getStorageClass() == SC_Static &&
3724       !New->isStaticDataMember() &&
3725       Old->hasExternalFormalLinkage()) {
3726     if (getLangOpts().MicrosoftExt) {
3727       Diag(New->getLocation(), diag::ext_static_non_static)
3728           << New->getDeclName();
3729       Diag(OldLocation, PrevDiag);
3730     } else {
3731       Diag(New->getLocation(), diag::err_static_non_static)
3732           << New->getDeclName();
3733       Diag(OldLocation, PrevDiag);
3734       return New->setInvalidDecl();
3735     }
3736   }
3737   // C99 6.2.2p4:
3738   //   For an identifier declared with the storage-class specifier
3739   //   extern in a scope in which a prior declaration of that
3740   //   identifier is visible,23) if the prior declaration specifies
3741   //   internal or external linkage, the linkage of the identifier at
3742   //   the later declaration is the same as the linkage specified at
3743   //   the prior declaration. If no prior declaration is visible, or
3744   //   if the prior declaration specifies no linkage, then the
3745   //   identifier has external linkage.
3746   if (New->hasExternalStorage() && Old->hasLinkage())
3747     /* Okay */;
3748   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3749            !New->isStaticDataMember() &&
3750            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3751     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3752     Diag(OldLocation, PrevDiag);
3753     return New->setInvalidDecl();
3754   }
3755 
3756   // Check if extern is followed by non-extern and vice-versa.
3757   if (New->hasExternalStorage() &&
3758       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3759     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3760     Diag(OldLocation, PrevDiag);
3761     return New->setInvalidDecl();
3762   }
3763   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3764       !New->hasExternalStorage()) {
3765     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3766     Diag(OldLocation, PrevDiag);
3767     return New->setInvalidDecl();
3768   }
3769 
3770   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3771 
3772   // FIXME: The test for external storage here seems wrong? We still
3773   // need to check for mismatches.
3774   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3775       // Don't complain about out-of-line definitions of static members.
3776       !(Old->getLexicalDeclContext()->isRecord() &&
3777         !New->getLexicalDeclContext()->isRecord())) {
3778     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3779     Diag(OldLocation, PrevDiag);
3780     return New->setInvalidDecl();
3781   }
3782 
3783   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3784     if (VarDecl *Def = Old->getDefinition()) {
3785       // C++1z [dcl.fcn.spec]p4:
3786       //   If the definition of a variable appears in a translation unit before
3787       //   its first declaration as inline, the program is ill-formed.
3788       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3789       Diag(Def->getLocation(), diag::note_previous_definition);
3790     }
3791   }
3792 
3793   // If this redeclaration makes the function inline, we may need to add it to
3794   // UndefinedButUsed.
3795   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3796       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3797     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3798                                            SourceLocation()));
3799 
3800   if (New->getTLSKind() != Old->getTLSKind()) {
3801     if (!Old->getTLSKind()) {
3802       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3803       Diag(OldLocation, PrevDiag);
3804     } else if (!New->getTLSKind()) {
3805       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3806       Diag(OldLocation, PrevDiag);
3807     } else {
3808       // Do not allow redeclaration to change the variable between requiring
3809       // static and dynamic initialization.
3810       // FIXME: GCC allows this, but uses the TLS keyword on the first
3811       // declaration to determine the kind. Do we need to be compatible here?
3812       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3813         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3814       Diag(OldLocation, PrevDiag);
3815     }
3816   }
3817 
3818   // C++ doesn't have tentative definitions, so go right ahead and check here.
3819   if (getLangOpts().CPlusPlus &&
3820       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3821     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3822         Old->getCanonicalDecl()->isConstexpr()) {
3823       // This definition won't be a definition any more once it's been merged.
3824       Diag(New->getLocation(),
3825            diag::warn_deprecated_redundant_constexpr_static_def);
3826     } else if (VarDecl *Def = Old->getDefinition()) {
3827       if (checkVarDeclRedefinition(Def, New))
3828         return;
3829     }
3830   }
3831 
3832   if (haveIncompatibleLanguageLinkages(Old, New)) {
3833     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3834     Diag(OldLocation, PrevDiag);
3835     New->setInvalidDecl();
3836     return;
3837   }
3838 
3839   // Merge "used" flag.
3840   if (Old->getMostRecentDecl()->isUsed(false))
3841     New->setIsUsed();
3842 
3843   // Keep a chain of previous declarations.
3844   New->setPreviousDecl(Old);
3845   if (NewTemplate)
3846     NewTemplate->setPreviousDecl(OldTemplate);
3847 
3848   // Inherit access appropriately.
3849   New->setAccess(Old->getAccess());
3850   if (NewTemplate)
3851     NewTemplate->setAccess(New->getAccess());
3852 
3853   if (Old->isInline())
3854     New->setImplicitlyInline();
3855 }
3856 
3857 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3858   SourceManager &SrcMgr = getSourceManager();
3859   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3860   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3861   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3862   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3863   auto &HSI = PP.getHeaderSearchInfo();
3864   StringRef HdrFilename =
3865       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3866 
3867   auto noteFromModuleOrInclude = [&](Module *Mod,
3868                                      SourceLocation IncLoc) -> bool {
3869     // Redefinition errors with modules are common with non modular mapped
3870     // headers, example: a non-modular header H in module A that also gets
3871     // included directly in a TU. Pointing twice to the same header/definition
3872     // is confusing, try to get better diagnostics when modules is on.
3873     if (IncLoc.isValid()) {
3874       if (Mod) {
3875         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3876             << HdrFilename.str() << Mod->getFullModuleName();
3877         if (!Mod->DefinitionLoc.isInvalid())
3878           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3879               << Mod->getFullModuleName();
3880       } else {
3881         Diag(IncLoc, diag::note_redefinition_include_same_file)
3882             << HdrFilename.str();
3883       }
3884       return true;
3885     }
3886 
3887     return false;
3888   };
3889 
3890   // Is it the same file and same offset? Provide more information on why
3891   // this leads to a redefinition error.
3892   bool EmittedDiag = false;
3893   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3894     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3895     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3896     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3897     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3898 
3899     // If the header has no guards, emit a note suggesting one.
3900     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3901       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3902 
3903     if (EmittedDiag)
3904       return;
3905   }
3906 
3907   // Redefinition coming from different files or couldn't do better above.
3908   Diag(Old->getLocation(), diag::note_previous_definition);
3909 }
3910 
3911 /// We've just determined that \p Old and \p New both appear to be definitions
3912 /// of the same variable. Either diagnose or fix the problem.
3913 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3914   if (!hasVisibleDefinition(Old) &&
3915       (New->getFormalLinkage() == InternalLinkage ||
3916        New->isInline() ||
3917        New->getDescribedVarTemplate() ||
3918        New->getNumTemplateParameterLists() ||
3919        New->getDeclContext()->isDependentContext())) {
3920     // The previous definition is hidden, and multiple definitions are
3921     // permitted (in separate TUs). Demote this to a declaration.
3922     New->demoteThisDefinitionToDeclaration();
3923 
3924     // Make the canonical definition visible.
3925     if (auto *OldTD = Old->getDescribedVarTemplate())
3926       makeMergedDefinitionVisible(OldTD);
3927     makeMergedDefinitionVisible(Old);
3928     return false;
3929   } else {
3930     Diag(New->getLocation(), diag::err_redefinition) << New;
3931     notePreviousDefinition(Old, New->getLocation());
3932     New->setInvalidDecl();
3933     return true;
3934   }
3935 }
3936 
3937 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3938 /// no declarator (e.g. "struct foo;") is parsed.
3939 Decl *
3940 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3941                                  RecordDecl *&AnonRecord) {
3942   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3943                                     AnonRecord);
3944 }
3945 
3946 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3947 // disambiguate entities defined in different scopes.
3948 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3949 // compatibility.
3950 // We will pick our mangling number depending on which version of MSVC is being
3951 // targeted.
3952 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3953   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3954              ? S->getMSCurManglingNumber()
3955              : S->getMSLastManglingNumber();
3956 }
3957 
3958 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3959   if (!Context.getLangOpts().CPlusPlus)
3960     return;
3961 
3962   if (isa<CXXRecordDecl>(Tag->getParent())) {
3963     // If this tag is the direct child of a class, number it if
3964     // it is anonymous.
3965     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3966       return;
3967     MangleNumberingContext &MCtx =
3968         Context.getManglingNumberContext(Tag->getParent());
3969     Context.setManglingNumber(
3970         Tag, MCtx.getManglingNumber(
3971                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3972     return;
3973   }
3974 
3975   // If this tag isn't a direct child of a class, number it if it is local.
3976   Decl *ManglingContextDecl;
3977   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3978           Tag->getDeclContext(), ManglingContextDecl)) {
3979     Context.setManglingNumber(
3980         Tag, MCtx->getManglingNumber(
3981                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3982   }
3983 }
3984 
3985 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3986                                         TypedefNameDecl *NewTD) {
3987   if (TagFromDeclSpec->isInvalidDecl())
3988     return;
3989 
3990   // Do nothing if the tag already has a name for linkage purposes.
3991   if (TagFromDeclSpec->hasNameForLinkage())
3992     return;
3993 
3994   // A well-formed anonymous tag must always be a TUK_Definition.
3995   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3996 
3997   // The type must match the tag exactly;  no qualifiers allowed.
3998   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3999                            Context.getTagDeclType(TagFromDeclSpec))) {
4000     if (getLangOpts().CPlusPlus)
4001       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4002     return;
4003   }
4004 
4005   // If we've already computed linkage for the anonymous tag, then
4006   // adding a typedef name for the anonymous decl can change that
4007   // linkage, which might be a serious problem.  Diagnose this as
4008   // unsupported and ignore the typedef name.  TODO: we should
4009   // pursue this as a language defect and establish a formal rule
4010   // for how to handle it.
4011   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4012     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4013 
4014     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4015     tagLoc = getLocForEndOfToken(tagLoc);
4016 
4017     llvm::SmallString<40> textToInsert;
4018     textToInsert += ' ';
4019     textToInsert += NewTD->getIdentifier()->getName();
4020     Diag(tagLoc, diag::note_typedef_changes_linkage)
4021         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4022     return;
4023   }
4024 
4025   // Otherwise, set this is the anon-decl typedef for the tag.
4026   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4027 }
4028 
4029 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4030   switch (T) {
4031   case DeclSpec::TST_class:
4032     return 0;
4033   case DeclSpec::TST_struct:
4034     return 1;
4035   case DeclSpec::TST_interface:
4036     return 2;
4037   case DeclSpec::TST_union:
4038     return 3;
4039   case DeclSpec::TST_enum:
4040     return 4;
4041   default:
4042     llvm_unreachable("unexpected type specifier");
4043   }
4044 }
4045 
4046 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4047 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4048 /// parameters to cope with template friend declarations.
4049 Decl *
4050 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4051                                  MultiTemplateParamsArg TemplateParams,
4052                                  bool IsExplicitInstantiation,
4053                                  RecordDecl *&AnonRecord) {
4054   Decl *TagD = nullptr;
4055   TagDecl *Tag = nullptr;
4056   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4057       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4058       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4059       DS.getTypeSpecType() == DeclSpec::TST_union ||
4060       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4061     TagD = DS.getRepAsDecl();
4062 
4063     if (!TagD) // We probably had an error
4064       return nullptr;
4065 
4066     // Note that the above type specs guarantee that the
4067     // type rep is a Decl, whereas in many of the others
4068     // it's a Type.
4069     if (isa<TagDecl>(TagD))
4070       Tag = cast<TagDecl>(TagD);
4071     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4072       Tag = CTD->getTemplatedDecl();
4073   }
4074 
4075   if (Tag) {
4076     handleTagNumbering(Tag, S);
4077     Tag->setFreeStanding();
4078     if (Tag->isInvalidDecl())
4079       return Tag;
4080   }
4081 
4082   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4083     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4084     // or incomplete types shall not be restrict-qualified."
4085     if (TypeQuals & DeclSpec::TQ_restrict)
4086       Diag(DS.getRestrictSpecLoc(),
4087            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4088            << DS.getSourceRange();
4089   }
4090 
4091   if (DS.isInlineSpecified())
4092     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4093         << getLangOpts().CPlusPlus1z;
4094 
4095   if (DS.isConstexprSpecified()) {
4096     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4097     // and definitions of functions and variables.
4098     if (Tag)
4099       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4100           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4101     else
4102       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4103     // Don't emit warnings after this error.
4104     return TagD;
4105   }
4106 
4107   if (DS.isConceptSpecified()) {
4108     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4109     // either a function concept and its definition or a variable concept and
4110     // its initializer.
4111     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4112     return TagD;
4113   }
4114 
4115   DiagnoseFunctionSpecifiers(DS);
4116 
4117   if (DS.isFriendSpecified()) {
4118     // If we're dealing with a decl but not a TagDecl, assume that
4119     // whatever routines created it handled the friendship aspect.
4120     if (TagD && !Tag)
4121       return nullptr;
4122     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4123   }
4124 
4125   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4126   bool IsExplicitSpecialization =
4127     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4128   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4129       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4130       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4131     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4132     // nested-name-specifier unless it is an explicit instantiation
4133     // or an explicit specialization.
4134     //
4135     // FIXME: We allow class template partial specializations here too, per the
4136     // obvious intent of DR1819.
4137     //
4138     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4139     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4140         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4141     return nullptr;
4142   }
4143 
4144   // Track whether this decl-specifier declares anything.
4145   bool DeclaresAnything = true;
4146 
4147   // Handle anonymous struct definitions.
4148   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4149     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4150         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4151       if (getLangOpts().CPlusPlus ||
4152           Record->getDeclContext()->isRecord()) {
4153         // If CurContext is a DeclContext that can contain statements,
4154         // RecursiveASTVisitor won't visit the decls that
4155         // BuildAnonymousStructOrUnion() will put into CurContext.
4156         // Also store them here so that they can be part of the
4157         // DeclStmt that gets created in this case.
4158         // FIXME: Also return the IndirectFieldDecls created by
4159         // BuildAnonymousStructOr union, for the same reason?
4160         if (CurContext->isFunctionOrMethod())
4161           AnonRecord = Record;
4162         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4163                                            Context.getPrintingPolicy());
4164       }
4165 
4166       DeclaresAnything = false;
4167     }
4168   }
4169 
4170   // C11 6.7.2.1p2:
4171   //   A struct-declaration that does not declare an anonymous structure or
4172   //   anonymous union shall contain a struct-declarator-list.
4173   //
4174   // This rule also existed in C89 and C99; the grammar for struct-declaration
4175   // did not permit a struct-declaration without a struct-declarator-list.
4176   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4177       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4178     // Check for Microsoft C extension: anonymous struct/union member.
4179     // Handle 2 kinds of anonymous struct/union:
4180     //   struct STRUCT;
4181     //   union UNION;
4182     // and
4183     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4184     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4185     if ((Tag && Tag->getDeclName()) ||
4186         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4187       RecordDecl *Record = nullptr;
4188       if (Tag)
4189         Record = dyn_cast<RecordDecl>(Tag);
4190       else if (const RecordType *RT =
4191                    DS.getRepAsType().get()->getAsStructureType())
4192         Record = RT->getDecl();
4193       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4194         Record = UT->getDecl();
4195 
4196       if (Record && getLangOpts().MicrosoftExt) {
4197         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4198           << Record->isUnion() << DS.getSourceRange();
4199         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4200       }
4201 
4202       DeclaresAnything = false;
4203     }
4204   }
4205 
4206   // Skip all the checks below if we have a type error.
4207   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4208       (TagD && TagD->isInvalidDecl()))
4209     return TagD;
4210 
4211   if (getLangOpts().CPlusPlus &&
4212       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4213     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4214       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4215           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4216         DeclaresAnything = false;
4217 
4218   if (!DS.isMissingDeclaratorOk()) {
4219     // Customize diagnostic for a typedef missing a name.
4220     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4221       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4222         << DS.getSourceRange();
4223     else
4224       DeclaresAnything = false;
4225   }
4226 
4227   if (DS.isModulePrivateSpecified() &&
4228       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4229     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4230       << Tag->getTagKind()
4231       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4232 
4233   ActOnDocumentableDecl(TagD);
4234 
4235   // C 6.7/2:
4236   //   A declaration [...] shall declare at least a declarator [...], a tag,
4237   //   or the members of an enumeration.
4238   // C++ [dcl.dcl]p3:
4239   //   [If there are no declarators], and except for the declaration of an
4240   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4241   //   names into the program, or shall redeclare a name introduced by a
4242   //   previous declaration.
4243   if (!DeclaresAnything) {
4244     // In C, we allow this as a (popular) extension / bug. Don't bother
4245     // producing further diagnostics for redundant qualifiers after this.
4246     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4247     return TagD;
4248   }
4249 
4250   // C++ [dcl.stc]p1:
4251   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4252   //   init-declarator-list of the declaration shall not be empty.
4253   // C++ [dcl.fct.spec]p1:
4254   //   If a cv-qualifier appears in a decl-specifier-seq, the
4255   //   init-declarator-list of the declaration shall not be empty.
4256   //
4257   // Spurious qualifiers here appear to be valid in C.
4258   unsigned DiagID = diag::warn_standalone_specifier;
4259   if (getLangOpts().CPlusPlus)
4260     DiagID = diag::ext_standalone_specifier;
4261 
4262   // Note that a linkage-specification sets a storage class, but
4263   // 'extern "C" struct foo;' is actually valid and not theoretically
4264   // useless.
4265   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4266     if (SCS == DeclSpec::SCS_mutable)
4267       // Since mutable is not a viable storage class specifier in C, there is
4268       // no reason to treat it as an extension. Instead, diagnose as an error.
4269       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4270     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4271       Diag(DS.getStorageClassSpecLoc(), DiagID)
4272         << DeclSpec::getSpecifierName(SCS);
4273   }
4274 
4275   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4276     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4277       << DeclSpec::getSpecifierName(TSCS);
4278   if (DS.getTypeQualifiers()) {
4279     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4280       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4281     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4282       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4283     // Restrict is covered above.
4284     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4285       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4286     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4287       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4288   }
4289 
4290   // Warn about ignored type attributes, for example:
4291   // __attribute__((aligned)) struct A;
4292   // Attributes should be placed after tag to apply to type declaration.
4293   if (!DS.getAttributes().empty()) {
4294     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4295     if (TypeSpecType == DeclSpec::TST_class ||
4296         TypeSpecType == DeclSpec::TST_struct ||
4297         TypeSpecType == DeclSpec::TST_interface ||
4298         TypeSpecType == DeclSpec::TST_union ||
4299         TypeSpecType == DeclSpec::TST_enum) {
4300       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4301            attrs = attrs->getNext())
4302         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4303             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4304     }
4305   }
4306 
4307   return TagD;
4308 }
4309 
4310 /// We are trying to inject an anonymous member into the given scope;
4311 /// check if there's an existing declaration that can't be overloaded.
4312 ///
4313 /// \return true if this is a forbidden redeclaration
4314 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4315                                          Scope *S,
4316                                          DeclContext *Owner,
4317                                          DeclarationName Name,
4318                                          SourceLocation NameLoc,
4319                                          bool IsUnion) {
4320   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4321                  Sema::ForRedeclaration);
4322   if (!SemaRef.LookupName(R, S)) return false;
4323 
4324   // Pick a representative declaration.
4325   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4326   assert(PrevDecl && "Expected a non-null Decl");
4327 
4328   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4329     return false;
4330 
4331   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4332     << IsUnion << Name;
4333   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4334 
4335   return true;
4336 }
4337 
4338 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4339 /// anonymous struct or union AnonRecord into the owning context Owner
4340 /// and scope S. This routine will be invoked just after we realize
4341 /// that an unnamed union or struct is actually an anonymous union or
4342 /// struct, e.g.,
4343 ///
4344 /// @code
4345 /// union {
4346 ///   int i;
4347 ///   float f;
4348 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4349 ///    // f into the surrounding scope.x
4350 /// @endcode
4351 ///
4352 /// This routine is recursive, injecting the names of nested anonymous
4353 /// structs/unions into the owning context and scope as well.
4354 static bool
4355 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4356                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4357                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4358   bool Invalid = false;
4359 
4360   // Look every FieldDecl and IndirectFieldDecl with a name.
4361   for (auto *D : AnonRecord->decls()) {
4362     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4363         cast<NamedDecl>(D)->getDeclName()) {
4364       ValueDecl *VD = cast<ValueDecl>(D);
4365       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4366                                        VD->getLocation(),
4367                                        AnonRecord->isUnion())) {
4368         // C++ [class.union]p2:
4369         //   The names of the members of an anonymous union shall be
4370         //   distinct from the names of any other entity in the
4371         //   scope in which the anonymous union is declared.
4372         Invalid = true;
4373       } else {
4374         // C++ [class.union]p2:
4375         //   For the purpose of name lookup, after the anonymous union
4376         //   definition, the members of the anonymous union are
4377         //   considered to have been defined in the scope in which the
4378         //   anonymous union is declared.
4379         unsigned OldChainingSize = Chaining.size();
4380         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4381           Chaining.append(IF->chain_begin(), IF->chain_end());
4382         else
4383           Chaining.push_back(VD);
4384 
4385         assert(Chaining.size() >= 2);
4386         NamedDecl **NamedChain =
4387           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4388         for (unsigned i = 0; i < Chaining.size(); i++)
4389           NamedChain[i] = Chaining[i];
4390 
4391         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4392             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4393             VD->getType(), {NamedChain, Chaining.size()});
4394 
4395         for (const auto *Attr : VD->attrs())
4396           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4397 
4398         IndirectField->setAccess(AS);
4399         IndirectField->setImplicit();
4400         SemaRef.PushOnScopeChains(IndirectField, S);
4401 
4402         // That includes picking up the appropriate access specifier.
4403         if (AS != AS_none) IndirectField->setAccess(AS);
4404 
4405         Chaining.resize(OldChainingSize);
4406       }
4407     }
4408   }
4409 
4410   return Invalid;
4411 }
4412 
4413 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4414 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4415 /// illegal input values are mapped to SC_None.
4416 static StorageClass
4417 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4418   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4419   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4420          "Parser allowed 'typedef' as storage class VarDecl.");
4421   switch (StorageClassSpec) {
4422   case DeclSpec::SCS_unspecified:    return SC_None;
4423   case DeclSpec::SCS_extern:
4424     if (DS.isExternInLinkageSpec())
4425       return SC_None;
4426     return SC_Extern;
4427   case DeclSpec::SCS_static:         return SC_Static;
4428   case DeclSpec::SCS_auto:           return SC_Auto;
4429   case DeclSpec::SCS_register:       return SC_Register;
4430   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4431     // Illegal SCSs map to None: error reporting is up to the caller.
4432   case DeclSpec::SCS_mutable:        // Fall through.
4433   case DeclSpec::SCS_typedef:        return SC_None;
4434   }
4435   llvm_unreachable("unknown storage class specifier");
4436 }
4437 
4438 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4439   assert(Record->hasInClassInitializer());
4440 
4441   for (const auto *I : Record->decls()) {
4442     const auto *FD = dyn_cast<FieldDecl>(I);
4443     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4444       FD = IFD->getAnonField();
4445     if (FD && FD->hasInClassInitializer())
4446       return FD->getLocation();
4447   }
4448 
4449   llvm_unreachable("couldn't find in-class initializer");
4450 }
4451 
4452 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4453                                       SourceLocation DefaultInitLoc) {
4454   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4455     return;
4456 
4457   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4458   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4459 }
4460 
4461 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4462                                       CXXRecordDecl *AnonUnion) {
4463   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4464     return;
4465 
4466   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4467 }
4468 
4469 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4470 /// anonymous structure or union. Anonymous unions are a C++ feature
4471 /// (C++ [class.union]) and a C11 feature; anonymous structures
4472 /// are a C11 feature and GNU C++ extension.
4473 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4474                                         AccessSpecifier AS,
4475                                         RecordDecl *Record,
4476                                         const PrintingPolicy &Policy) {
4477   DeclContext *Owner = Record->getDeclContext();
4478 
4479   // Diagnose whether this anonymous struct/union is an extension.
4480   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4481     Diag(Record->getLocation(), diag::ext_anonymous_union);
4482   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4483     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4484   else if (!Record->isUnion() && !getLangOpts().C11)
4485     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4486 
4487   // C and C++ require different kinds of checks for anonymous
4488   // structs/unions.
4489   bool Invalid = false;
4490   if (getLangOpts().CPlusPlus) {
4491     const char *PrevSpec = nullptr;
4492     unsigned DiagID;
4493     if (Record->isUnion()) {
4494       // C++ [class.union]p6:
4495       //   Anonymous unions declared in a named namespace or in the
4496       //   global namespace shall be declared static.
4497       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4498           (isa<TranslationUnitDecl>(Owner) ||
4499            (isa<NamespaceDecl>(Owner) &&
4500             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4501         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4502           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4503 
4504         // Recover by adding 'static'.
4505         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4506                                PrevSpec, DiagID, Policy);
4507       }
4508       // C++ [class.union]p6:
4509       //   A storage class is not allowed in a declaration of an
4510       //   anonymous union in a class scope.
4511       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4512                isa<RecordDecl>(Owner)) {
4513         Diag(DS.getStorageClassSpecLoc(),
4514              diag::err_anonymous_union_with_storage_spec)
4515           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4516 
4517         // Recover by removing the storage specifier.
4518         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4519                                SourceLocation(),
4520                                PrevSpec, DiagID, Context.getPrintingPolicy());
4521       }
4522     }
4523 
4524     // Ignore const/volatile/restrict qualifiers.
4525     if (DS.getTypeQualifiers()) {
4526       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4527         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4528           << Record->isUnion() << "const"
4529           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4530       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4531         Diag(DS.getVolatileSpecLoc(),
4532              diag::ext_anonymous_struct_union_qualified)
4533           << Record->isUnion() << "volatile"
4534           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4535       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4536         Diag(DS.getRestrictSpecLoc(),
4537              diag::ext_anonymous_struct_union_qualified)
4538           << Record->isUnion() << "restrict"
4539           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4540       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4541         Diag(DS.getAtomicSpecLoc(),
4542              diag::ext_anonymous_struct_union_qualified)
4543           << Record->isUnion() << "_Atomic"
4544           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4545       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4546         Diag(DS.getUnalignedSpecLoc(),
4547              diag::ext_anonymous_struct_union_qualified)
4548           << Record->isUnion() << "__unaligned"
4549           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4550 
4551       DS.ClearTypeQualifiers();
4552     }
4553 
4554     // C++ [class.union]p2:
4555     //   The member-specification of an anonymous union shall only
4556     //   define non-static data members. [Note: nested types and
4557     //   functions cannot be declared within an anonymous union. ]
4558     for (auto *Mem : Record->decls()) {
4559       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4560         // C++ [class.union]p3:
4561         //   An anonymous union shall not have private or protected
4562         //   members (clause 11).
4563         assert(FD->getAccess() != AS_none);
4564         if (FD->getAccess() != AS_public) {
4565           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4566             << Record->isUnion() << (FD->getAccess() == AS_protected);
4567           Invalid = true;
4568         }
4569 
4570         // C++ [class.union]p1
4571         //   An object of a class with a non-trivial constructor, a non-trivial
4572         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4573         //   assignment operator cannot be a member of a union, nor can an
4574         //   array of such objects.
4575         if (CheckNontrivialField(FD))
4576           Invalid = true;
4577       } else if (Mem->isImplicit()) {
4578         // Any implicit members are fine.
4579       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4580         // This is a type that showed up in an
4581         // elaborated-type-specifier inside the anonymous struct or
4582         // union, but which actually declares a type outside of the
4583         // anonymous struct or union. It's okay.
4584       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4585         if (!MemRecord->isAnonymousStructOrUnion() &&
4586             MemRecord->getDeclName()) {
4587           // Visual C++ allows type definition in anonymous struct or union.
4588           if (getLangOpts().MicrosoftExt)
4589             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4590               << Record->isUnion();
4591           else {
4592             // This is a nested type declaration.
4593             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4594               << Record->isUnion();
4595             Invalid = true;
4596           }
4597         } else {
4598           // This is an anonymous type definition within another anonymous type.
4599           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4600           // not part of standard C++.
4601           Diag(MemRecord->getLocation(),
4602                diag::ext_anonymous_record_with_anonymous_type)
4603             << Record->isUnion();
4604         }
4605       } else if (isa<AccessSpecDecl>(Mem)) {
4606         // Any access specifier is fine.
4607       } else if (isa<StaticAssertDecl>(Mem)) {
4608         // In C++1z, static_assert declarations are also fine.
4609       } else {
4610         // We have something that isn't a non-static data
4611         // member. Complain about it.
4612         unsigned DK = diag::err_anonymous_record_bad_member;
4613         if (isa<TypeDecl>(Mem))
4614           DK = diag::err_anonymous_record_with_type;
4615         else if (isa<FunctionDecl>(Mem))
4616           DK = diag::err_anonymous_record_with_function;
4617         else if (isa<VarDecl>(Mem))
4618           DK = diag::err_anonymous_record_with_static;
4619 
4620         // Visual C++ allows type definition in anonymous struct or union.
4621         if (getLangOpts().MicrosoftExt &&
4622             DK == diag::err_anonymous_record_with_type)
4623           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4624             << Record->isUnion();
4625         else {
4626           Diag(Mem->getLocation(), DK) << Record->isUnion();
4627           Invalid = true;
4628         }
4629       }
4630     }
4631 
4632     // C++11 [class.union]p8 (DR1460):
4633     //   At most one variant member of a union may have a
4634     //   brace-or-equal-initializer.
4635     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4636         Owner->isRecord())
4637       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4638                                 cast<CXXRecordDecl>(Record));
4639   }
4640 
4641   if (!Record->isUnion() && !Owner->isRecord()) {
4642     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4643       << getLangOpts().CPlusPlus;
4644     Invalid = true;
4645   }
4646 
4647   // Mock up a declarator.
4648   Declarator Dc(DS, Declarator::MemberContext);
4649   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4650   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4651 
4652   // Create a declaration for this anonymous struct/union.
4653   NamedDecl *Anon = nullptr;
4654   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4655     Anon = FieldDecl::Create(Context, OwningClass,
4656                              DS.getLocStart(),
4657                              Record->getLocation(),
4658                              /*IdentifierInfo=*/nullptr,
4659                              Context.getTypeDeclType(Record),
4660                              TInfo,
4661                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4662                              /*InitStyle=*/ICIS_NoInit);
4663     Anon->setAccess(AS);
4664     if (getLangOpts().CPlusPlus)
4665       FieldCollector->Add(cast<FieldDecl>(Anon));
4666   } else {
4667     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4668     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4669     if (SCSpec == DeclSpec::SCS_mutable) {
4670       // mutable can only appear on non-static class members, so it's always
4671       // an error here
4672       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4673       Invalid = true;
4674       SC = SC_None;
4675     }
4676 
4677     Anon = VarDecl::Create(Context, Owner,
4678                            DS.getLocStart(),
4679                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4680                            Context.getTypeDeclType(Record),
4681                            TInfo, SC);
4682 
4683     // Default-initialize the implicit variable. This initialization will be
4684     // trivial in almost all cases, except if a union member has an in-class
4685     // initializer:
4686     //   union { int n = 0; };
4687     ActOnUninitializedDecl(Anon);
4688   }
4689   Anon->setImplicit();
4690 
4691   // Mark this as an anonymous struct/union type.
4692   Record->setAnonymousStructOrUnion(true);
4693 
4694   // Add the anonymous struct/union object to the current
4695   // context. We'll be referencing this object when we refer to one of
4696   // its members.
4697   Owner->addDecl(Anon);
4698 
4699   // Inject the members of the anonymous struct/union into the owning
4700   // context and into the identifier resolver chain for name lookup
4701   // purposes.
4702   SmallVector<NamedDecl*, 2> Chain;
4703   Chain.push_back(Anon);
4704 
4705   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4706     Invalid = true;
4707 
4708   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4709     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4710       Decl *ManglingContextDecl;
4711       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4712               NewVD->getDeclContext(), ManglingContextDecl)) {
4713         Context.setManglingNumber(
4714             NewVD, MCtx->getManglingNumber(
4715                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4716         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4717       }
4718     }
4719   }
4720 
4721   if (Invalid)
4722     Anon->setInvalidDecl();
4723 
4724   return Anon;
4725 }
4726 
4727 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4728 /// Microsoft C anonymous structure.
4729 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4730 /// Example:
4731 ///
4732 /// struct A { int a; };
4733 /// struct B { struct A; int b; };
4734 ///
4735 /// void foo() {
4736 ///   B var;
4737 ///   var.a = 3;
4738 /// }
4739 ///
4740 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4741                                            RecordDecl *Record) {
4742   assert(Record && "expected a record!");
4743 
4744   // Mock up a declarator.
4745   Declarator Dc(DS, Declarator::TypeNameContext);
4746   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4747   assert(TInfo && "couldn't build declarator info for anonymous struct");
4748 
4749   auto *ParentDecl = cast<RecordDecl>(CurContext);
4750   QualType RecTy = Context.getTypeDeclType(Record);
4751 
4752   // Create a declaration for this anonymous struct.
4753   NamedDecl *Anon = FieldDecl::Create(Context,
4754                              ParentDecl,
4755                              DS.getLocStart(),
4756                              DS.getLocStart(),
4757                              /*IdentifierInfo=*/nullptr,
4758                              RecTy,
4759                              TInfo,
4760                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4761                              /*InitStyle=*/ICIS_NoInit);
4762   Anon->setImplicit();
4763 
4764   // Add the anonymous struct object to the current context.
4765   CurContext->addDecl(Anon);
4766 
4767   // Inject the members of the anonymous struct into the current
4768   // context and into the identifier resolver chain for name lookup
4769   // purposes.
4770   SmallVector<NamedDecl*, 2> Chain;
4771   Chain.push_back(Anon);
4772 
4773   RecordDecl *RecordDef = Record->getDefinition();
4774   if (RequireCompleteType(Anon->getLocation(), RecTy,
4775                           diag::err_field_incomplete) ||
4776       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4777                                           AS_none, Chain)) {
4778     Anon->setInvalidDecl();
4779     ParentDecl->setInvalidDecl();
4780   }
4781 
4782   return Anon;
4783 }
4784 
4785 /// GetNameForDeclarator - Determine the full declaration name for the
4786 /// given Declarator.
4787 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4788   return GetNameFromUnqualifiedId(D.getName());
4789 }
4790 
4791 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4792 DeclarationNameInfo
4793 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4794   DeclarationNameInfo NameInfo;
4795   NameInfo.setLoc(Name.StartLocation);
4796 
4797   switch (Name.getKind()) {
4798 
4799   case UnqualifiedId::IK_ImplicitSelfParam:
4800   case UnqualifiedId::IK_Identifier:
4801     NameInfo.setName(Name.Identifier);
4802     NameInfo.setLoc(Name.StartLocation);
4803     return NameInfo;
4804 
4805   case UnqualifiedId::IK_DeductionGuideName: {
4806     // C++ [temp.deduct.guide]p3:
4807     //   The simple-template-id shall name a class template specialization.
4808     //   The template-name shall be the same identifier as the template-name
4809     //   of the simple-template-id.
4810     // These together intend to imply that the template-name shall name a
4811     // class template.
4812     // FIXME: template<typename T> struct X {};
4813     //        template<typename T> using Y = X<T>;
4814     //        Y(int) -> Y<int>;
4815     //   satisfies these rules but does not name a class template.
4816     TemplateName TN = Name.TemplateName.get().get();
4817     auto *Template = TN.getAsTemplateDecl();
4818     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4819       Diag(Name.StartLocation,
4820            diag::err_deduction_guide_name_not_class_template)
4821         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4822       if (Template)
4823         Diag(Template->getLocation(), diag::note_template_decl_here);
4824       return DeclarationNameInfo();
4825     }
4826 
4827     NameInfo.setName(
4828         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4829     NameInfo.setLoc(Name.StartLocation);
4830     return NameInfo;
4831   }
4832 
4833   case UnqualifiedId::IK_OperatorFunctionId:
4834     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4835                                            Name.OperatorFunctionId.Operator));
4836     NameInfo.setLoc(Name.StartLocation);
4837     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4838       = Name.OperatorFunctionId.SymbolLocations[0];
4839     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4840       = Name.EndLocation.getRawEncoding();
4841     return NameInfo;
4842 
4843   case UnqualifiedId::IK_LiteralOperatorId:
4844     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4845                                                            Name.Identifier));
4846     NameInfo.setLoc(Name.StartLocation);
4847     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4848     return NameInfo;
4849 
4850   case UnqualifiedId::IK_ConversionFunctionId: {
4851     TypeSourceInfo *TInfo;
4852     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4853     if (Ty.isNull())
4854       return DeclarationNameInfo();
4855     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4856                                                Context.getCanonicalType(Ty)));
4857     NameInfo.setLoc(Name.StartLocation);
4858     NameInfo.setNamedTypeInfo(TInfo);
4859     return NameInfo;
4860   }
4861 
4862   case UnqualifiedId::IK_ConstructorName: {
4863     TypeSourceInfo *TInfo;
4864     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4865     if (Ty.isNull())
4866       return DeclarationNameInfo();
4867     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4868                                               Context.getCanonicalType(Ty)));
4869     NameInfo.setLoc(Name.StartLocation);
4870     NameInfo.setNamedTypeInfo(TInfo);
4871     return NameInfo;
4872   }
4873 
4874   case UnqualifiedId::IK_ConstructorTemplateId: {
4875     // In well-formed code, we can only have a constructor
4876     // template-id that refers to the current context, so go there
4877     // to find the actual type being constructed.
4878     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4879     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4880       return DeclarationNameInfo();
4881 
4882     // Determine the type of the class being constructed.
4883     QualType CurClassType = Context.getTypeDeclType(CurClass);
4884 
4885     // FIXME: Check two things: that the template-id names the same type as
4886     // CurClassType, and that the template-id does not occur when the name
4887     // was qualified.
4888 
4889     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4890                                     Context.getCanonicalType(CurClassType)));
4891     NameInfo.setLoc(Name.StartLocation);
4892     // FIXME: should we retrieve TypeSourceInfo?
4893     NameInfo.setNamedTypeInfo(nullptr);
4894     return NameInfo;
4895   }
4896 
4897   case UnqualifiedId::IK_DestructorName: {
4898     TypeSourceInfo *TInfo;
4899     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4900     if (Ty.isNull())
4901       return DeclarationNameInfo();
4902     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4903                                               Context.getCanonicalType(Ty)));
4904     NameInfo.setLoc(Name.StartLocation);
4905     NameInfo.setNamedTypeInfo(TInfo);
4906     return NameInfo;
4907   }
4908 
4909   case UnqualifiedId::IK_TemplateId: {
4910     TemplateName TName = Name.TemplateId->Template.get();
4911     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4912     return Context.getNameForTemplate(TName, TNameLoc);
4913   }
4914 
4915   } // switch (Name.getKind())
4916 
4917   llvm_unreachable("Unknown name kind");
4918 }
4919 
4920 static QualType getCoreType(QualType Ty) {
4921   do {
4922     if (Ty->isPointerType() || Ty->isReferenceType())
4923       Ty = Ty->getPointeeType();
4924     else if (Ty->isArrayType())
4925       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4926     else
4927       return Ty.withoutLocalFastQualifiers();
4928   } while (true);
4929 }
4930 
4931 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4932 /// and Definition have "nearly" matching parameters. This heuristic is
4933 /// used to improve diagnostics in the case where an out-of-line function
4934 /// definition doesn't match any declaration within the class or namespace.
4935 /// Also sets Params to the list of indices to the parameters that differ
4936 /// between the declaration and the definition. If hasSimilarParameters
4937 /// returns true and Params is empty, then all of the parameters match.
4938 static bool hasSimilarParameters(ASTContext &Context,
4939                                      FunctionDecl *Declaration,
4940                                      FunctionDecl *Definition,
4941                                      SmallVectorImpl<unsigned> &Params) {
4942   Params.clear();
4943   if (Declaration->param_size() != Definition->param_size())
4944     return false;
4945   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4946     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4947     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4948 
4949     // The parameter types are identical
4950     if (Context.hasSameType(DefParamTy, DeclParamTy))
4951       continue;
4952 
4953     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4954     QualType DefParamBaseTy = getCoreType(DefParamTy);
4955     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4956     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4957 
4958     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4959         (DeclTyName && DeclTyName == DefTyName))
4960       Params.push_back(Idx);
4961     else  // The two parameters aren't even close
4962       return false;
4963   }
4964 
4965   return true;
4966 }
4967 
4968 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4969 /// declarator needs to be rebuilt in the current instantiation.
4970 /// Any bits of declarator which appear before the name are valid for
4971 /// consideration here.  That's specifically the type in the decl spec
4972 /// and the base type in any member-pointer chunks.
4973 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4974                                                     DeclarationName Name) {
4975   // The types we specifically need to rebuild are:
4976   //   - typenames, typeofs, and decltypes
4977   //   - types which will become injected class names
4978   // Of course, we also need to rebuild any type referencing such a
4979   // type.  It's safest to just say "dependent", but we call out a
4980   // few cases here.
4981 
4982   DeclSpec &DS = D.getMutableDeclSpec();
4983   switch (DS.getTypeSpecType()) {
4984   case DeclSpec::TST_typename:
4985   case DeclSpec::TST_typeofType:
4986   case DeclSpec::TST_underlyingType:
4987   case DeclSpec::TST_atomic: {
4988     // Grab the type from the parser.
4989     TypeSourceInfo *TSI = nullptr;
4990     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4991     if (T.isNull() || !T->isDependentType()) break;
4992 
4993     // Make sure there's a type source info.  This isn't really much
4994     // of a waste; most dependent types should have type source info
4995     // attached already.
4996     if (!TSI)
4997       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4998 
4999     // Rebuild the type in the current instantiation.
5000     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5001     if (!TSI) return true;
5002 
5003     // Store the new type back in the decl spec.
5004     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5005     DS.UpdateTypeRep(LocType);
5006     break;
5007   }
5008 
5009   case DeclSpec::TST_decltype:
5010   case DeclSpec::TST_typeofExpr: {
5011     Expr *E = DS.getRepAsExpr();
5012     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5013     if (Result.isInvalid()) return true;
5014     DS.UpdateExprRep(Result.get());
5015     break;
5016   }
5017 
5018   default:
5019     // Nothing to do for these decl specs.
5020     break;
5021   }
5022 
5023   // It doesn't matter what order we do this in.
5024   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5025     DeclaratorChunk &Chunk = D.getTypeObject(I);
5026 
5027     // The only type information in the declarator which can come
5028     // before the declaration name is the base type of a member
5029     // pointer.
5030     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5031       continue;
5032 
5033     // Rebuild the scope specifier in-place.
5034     CXXScopeSpec &SS = Chunk.Mem.Scope();
5035     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5036       return true;
5037   }
5038 
5039   return false;
5040 }
5041 
5042 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5043   D.setFunctionDefinitionKind(FDK_Declaration);
5044   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5045 
5046   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5047       Dcl && Dcl->getDeclContext()->isFileContext())
5048     Dcl->setTopLevelDeclInObjCContainer();
5049 
5050   if (getLangOpts().OpenCL)
5051     setCurrentOpenCLExtensionForDecl(Dcl);
5052 
5053   return Dcl;
5054 }
5055 
5056 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5057 ///   If T is the name of a class, then each of the following shall have a
5058 ///   name different from T:
5059 ///     - every static data member of class T;
5060 ///     - every member function of class T
5061 ///     - every member of class T that is itself a type;
5062 /// \returns true if the declaration name violates these rules.
5063 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5064                                    DeclarationNameInfo NameInfo) {
5065   DeclarationName Name = NameInfo.getName();
5066 
5067   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5068   while (Record && Record->isAnonymousStructOrUnion())
5069     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5070   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5071     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5072     return true;
5073   }
5074 
5075   return false;
5076 }
5077 
5078 /// \brief Diagnose a declaration whose declarator-id has the given
5079 /// nested-name-specifier.
5080 ///
5081 /// \param SS The nested-name-specifier of the declarator-id.
5082 ///
5083 /// \param DC The declaration context to which the nested-name-specifier
5084 /// resolves.
5085 ///
5086 /// \param Name The name of the entity being declared.
5087 ///
5088 /// \param Loc The location of the name of the entity being declared.
5089 ///
5090 /// \returns true if we cannot safely recover from this error, false otherwise.
5091 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5092                                         DeclarationName Name,
5093                                         SourceLocation Loc) {
5094   DeclContext *Cur = CurContext;
5095   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5096     Cur = Cur->getParent();
5097 
5098   // If the user provided a superfluous scope specifier that refers back to the
5099   // class in which the entity is already declared, diagnose and ignore it.
5100   //
5101   // class X {
5102   //   void X::f();
5103   // };
5104   //
5105   // Note, it was once ill-formed to give redundant qualification in all
5106   // contexts, but that rule was removed by DR482.
5107   if (Cur->Equals(DC)) {
5108     if (Cur->isRecord()) {
5109       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5110                                       : diag::err_member_extra_qualification)
5111         << Name << FixItHint::CreateRemoval(SS.getRange());
5112       SS.clear();
5113     } else {
5114       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5115     }
5116     return false;
5117   }
5118 
5119   // Check whether the qualifying scope encloses the scope of the original
5120   // declaration.
5121   if (!Cur->Encloses(DC)) {
5122     if (Cur->isRecord())
5123       Diag(Loc, diag::err_member_qualification)
5124         << Name << SS.getRange();
5125     else if (isa<TranslationUnitDecl>(DC))
5126       Diag(Loc, diag::err_invalid_declarator_global_scope)
5127         << Name << SS.getRange();
5128     else if (isa<FunctionDecl>(Cur))
5129       Diag(Loc, diag::err_invalid_declarator_in_function)
5130         << Name << SS.getRange();
5131     else if (isa<BlockDecl>(Cur))
5132       Diag(Loc, diag::err_invalid_declarator_in_block)
5133         << Name << SS.getRange();
5134     else
5135       Diag(Loc, diag::err_invalid_declarator_scope)
5136       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5137 
5138     return true;
5139   }
5140 
5141   if (Cur->isRecord()) {
5142     // Cannot qualify members within a class.
5143     Diag(Loc, diag::err_member_qualification)
5144       << Name << SS.getRange();
5145     SS.clear();
5146 
5147     // C++ constructors and destructors with incorrect scopes can break
5148     // our AST invariants by having the wrong underlying types. If
5149     // that's the case, then drop this declaration entirely.
5150     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5151          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5152         !Context.hasSameType(Name.getCXXNameType(),
5153                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5154       return true;
5155 
5156     return false;
5157   }
5158 
5159   // C++11 [dcl.meaning]p1:
5160   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5161   //   not begin with a decltype-specifer"
5162   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5163   while (SpecLoc.getPrefix())
5164     SpecLoc = SpecLoc.getPrefix();
5165   if (dyn_cast_or_null<DecltypeType>(
5166         SpecLoc.getNestedNameSpecifier()->getAsType()))
5167     Diag(Loc, diag::err_decltype_in_declarator)
5168       << SpecLoc.getTypeLoc().getSourceRange();
5169 
5170   return false;
5171 }
5172 
5173 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5174                                   MultiTemplateParamsArg TemplateParamLists) {
5175   // TODO: consider using NameInfo for diagnostic.
5176   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5177   DeclarationName Name = NameInfo.getName();
5178 
5179   // All of these full declarators require an identifier.  If it doesn't have
5180   // one, the ParsedFreeStandingDeclSpec action should be used.
5181   if (D.isDecompositionDeclarator()) {
5182     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5183   } else if (!Name) {
5184     if (!D.isInvalidType())  // Reject this if we think it is valid.
5185       Diag(D.getDeclSpec().getLocStart(),
5186            diag::err_declarator_need_ident)
5187         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5188     return nullptr;
5189   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5190     return nullptr;
5191 
5192   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5193   // we find one that is.
5194   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5195          (S->getFlags() & Scope::TemplateParamScope) != 0)
5196     S = S->getParent();
5197 
5198   DeclContext *DC = CurContext;
5199   if (D.getCXXScopeSpec().isInvalid())
5200     D.setInvalidType();
5201   else if (D.getCXXScopeSpec().isSet()) {
5202     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5203                                         UPPC_DeclarationQualifier))
5204       return nullptr;
5205 
5206     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5207     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5208     if (!DC || isa<EnumDecl>(DC)) {
5209       // If we could not compute the declaration context, it's because the
5210       // declaration context is dependent but does not refer to a class,
5211       // class template, or class template partial specialization. Complain
5212       // and return early, to avoid the coming semantic disaster.
5213       Diag(D.getIdentifierLoc(),
5214            diag::err_template_qualified_declarator_no_match)
5215         << D.getCXXScopeSpec().getScopeRep()
5216         << D.getCXXScopeSpec().getRange();
5217       return nullptr;
5218     }
5219     bool IsDependentContext = DC->isDependentContext();
5220 
5221     if (!IsDependentContext &&
5222         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5223       return nullptr;
5224 
5225     // If a class is incomplete, do not parse entities inside it.
5226     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5227       Diag(D.getIdentifierLoc(),
5228            diag::err_member_def_undefined_record)
5229         << Name << DC << D.getCXXScopeSpec().getRange();
5230       return nullptr;
5231     }
5232     if (!D.getDeclSpec().isFriendSpecified()) {
5233       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5234                                       Name, D.getIdentifierLoc())) {
5235         if (DC->isRecord())
5236           return nullptr;
5237 
5238         D.setInvalidType();
5239       }
5240     }
5241 
5242     // Check whether we need to rebuild the type of the given
5243     // declaration in the current instantiation.
5244     if (EnteringContext && IsDependentContext &&
5245         TemplateParamLists.size() != 0) {
5246       ContextRAII SavedContext(*this, DC);
5247       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5248         D.setInvalidType();
5249     }
5250   }
5251 
5252   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5253   QualType R = TInfo->getType();
5254 
5255   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5256     // If this is a typedef, we'll end up spewing multiple diagnostics.
5257     // Just return early; it's safer. If this is a function, let the
5258     // "constructor cannot have a return type" diagnostic handle it.
5259     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5260       return nullptr;
5261 
5262   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5263                                       UPPC_DeclarationType))
5264     D.setInvalidType();
5265 
5266   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5267                         ForRedeclaration);
5268 
5269   // See if this is a redefinition of a variable in the same scope.
5270   if (!D.getCXXScopeSpec().isSet()) {
5271     bool IsLinkageLookup = false;
5272     bool CreateBuiltins = false;
5273 
5274     // If the declaration we're planning to build will be a function
5275     // or object with linkage, then look for another declaration with
5276     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5277     //
5278     // If the declaration we're planning to build will be declared with
5279     // external linkage in the translation unit, create any builtin with
5280     // the same name.
5281     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5282       /* Do nothing*/;
5283     else if (CurContext->isFunctionOrMethod() &&
5284              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5285               R->isFunctionType())) {
5286       IsLinkageLookup = true;
5287       CreateBuiltins =
5288           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5289     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5290                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5291       CreateBuiltins = true;
5292 
5293     if (IsLinkageLookup)
5294       Previous.clear(LookupRedeclarationWithLinkage);
5295 
5296     LookupName(Previous, S, CreateBuiltins);
5297   } else { // Something like "int foo::x;"
5298     LookupQualifiedName(Previous, DC);
5299 
5300     // C++ [dcl.meaning]p1:
5301     //   When the declarator-id is qualified, the declaration shall refer to a
5302     //  previously declared member of the class or namespace to which the
5303     //  qualifier refers (or, in the case of a namespace, of an element of the
5304     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5305     //  thereof; [...]
5306     //
5307     // Note that we already checked the context above, and that we do not have
5308     // enough information to make sure that Previous contains the declaration
5309     // we want to match. For example, given:
5310     //
5311     //   class X {
5312     //     void f();
5313     //     void f(float);
5314     //   };
5315     //
5316     //   void X::f(int) { } // ill-formed
5317     //
5318     // In this case, Previous will point to the overload set
5319     // containing the two f's declared in X, but neither of them
5320     // matches.
5321 
5322     // C++ [dcl.meaning]p1:
5323     //   [...] the member shall not merely have been introduced by a
5324     //   using-declaration in the scope of the class or namespace nominated by
5325     //   the nested-name-specifier of the declarator-id.
5326     RemoveUsingDecls(Previous);
5327   }
5328 
5329   if (Previous.isSingleResult() &&
5330       Previous.getFoundDecl()->isTemplateParameter()) {
5331     // Maybe we will complain about the shadowed template parameter.
5332     if (!D.isInvalidType())
5333       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5334                                       Previous.getFoundDecl());
5335 
5336     // Just pretend that we didn't see the previous declaration.
5337     Previous.clear();
5338   }
5339 
5340   // In C++, the previous declaration we find might be a tag type
5341   // (class or enum). In this case, the new declaration will hide the
5342   // tag type. Note that this does does not apply if we're declaring a
5343   // typedef (C++ [dcl.typedef]p4).
5344   if (Previous.isSingleTagDecl() &&
5345       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5346     Previous.clear();
5347 
5348   // Check that there are no default arguments other than in the parameters
5349   // of a function declaration (C++ only).
5350   if (getLangOpts().CPlusPlus)
5351     CheckExtraCXXDefaultArguments(D);
5352 
5353   if (D.getDeclSpec().isConceptSpecified()) {
5354     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5355     // applied only to the definition of a function template or variable
5356     // template, declared in namespace scope
5357     if (!TemplateParamLists.size()) {
5358       Diag(D.getDeclSpec().getConceptSpecLoc(),
5359            diag:: err_concept_wrong_decl_kind);
5360       return nullptr;
5361     }
5362 
5363     if (!DC->getRedeclContext()->isFileContext()) {
5364       Diag(D.getIdentifierLoc(),
5365            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5366       return nullptr;
5367     }
5368   }
5369 
5370   NamedDecl *New;
5371 
5372   bool AddToScope = true;
5373   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5374     if (TemplateParamLists.size()) {
5375       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5376       return nullptr;
5377     }
5378 
5379     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5380   } else if (R->isFunctionType()) {
5381     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5382                                   TemplateParamLists,
5383                                   AddToScope);
5384   } else {
5385     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5386                                   AddToScope);
5387   }
5388 
5389   if (!New)
5390     return nullptr;
5391 
5392   // If this has an identifier and is not a function template specialization,
5393   // add it to the scope stack.
5394   if (New->getDeclName() && AddToScope) {
5395     // Only make a locally-scoped extern declaration visible if it is the first
5396     // declaration of this entity. Qualified lookup for such an entity should
5397     // only find this declaration if there is no visible declaration of it.
5398     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5399     PushOnScopeChains(New, S, AddToContext);
5400     if (!AddToContext)
5401       CurContext->addHiddenDecl(New);
5402   }
5403 
5404   if (isInOpenMPDeclareTargetContext())
5405     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5406 
5407   return New;
5408 }
5409 
5410 /// Helper method to turn variable array types into constant array
5411 /// types in certain situations which would otherwise be errors (for
5412 /// GCC compatibility).
5413 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5414                                                     ASTContext &Context,
5415                                                     bool &SizeIsNegative,
5416                                                     llvm::APSInt &Oversized) {
5417   // This method tries to turn a variable array into a constant
5418   // array even when the size isn't an ICE.  This is necessary
5419   // for compatibility with code that depends on gcc's buggy
5420   // constant expression folding, like struct {char x[(int)(char*)2];}
5421   SizeIsNegative = false;
5422   Oversized = 0;
5423 
5424   if (T->isDependentType())
5425     return QualType();
5426 
5427   QualifierCollector Qs;
5428   const Type *Ty = Qs.strip(T);
5429 
5430   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5431     QualType Pointee = PTy->getPointeeType();
5432     QualType FixedType =
5433         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5434                                             Oversized);
5435     if (FixedType.isNull()) return FixedType;
5436     FixedType = Context.getPointerType(FixedType);
5437     return Qs.apply(Context, FixedType);
5438   }
5439   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5440     QualType Inner = PTy->getInnerType();
5441     QualType FixedType =
5442         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5443                                             Oversized);
5444     if (FixedType.isNull()) return FixedType;
5445     FixedType = Context.getParenType(FixedType);
5446     return Qs.apply(Context, FixedType);
5447   }
5448 
5449   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5450   if (!VLATy)
5451     return QualType();
5452   // FIXME: We should probably handle this case
5453   if (VLATy->getElementType()->isVariablyModifiedType())
5454     return QualType();
5455 
5456   llvm::APSInt Res;
5457   if (!VLATy->getSizeExpr() ||
5458       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5459     return QualType();
5460 
5461   // Check whether the array size is negative.
5462   if (Res.isSigned() && Res.isNegative()) {
5463     SizeIsNegative = true;
5464     return QualType();
5465   }
5466 
5467   // Check whether the array is too large to be addressed.
5468   unsigned ActiveSizeBits
5469     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5470                                               Res);
5471   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5472     Oversized = Res;
5473     return QualType();
5474   }
5475 
5476   return Context.getConstantArrayType(VLATy->getElementType(),
5477                                       Res, ArrayType::Normal, 0);
5478 }
5479 
5480 static void
5481 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5482   SrcTL = SrcTL.getUnqualifiedLoc();
5483   DstTL = DstTL.getUnqualifiedLoc();
5484   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5485     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5486     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5487                                       DstPTL.getPointeeLoc());
5488     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5489     return;
5490   }
5491   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5492     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5493     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5494                                       DstPTL.getInnerLoc());
5495     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5496     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5497     return;
5498   }
5499   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5500   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5501   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5502   TypeLoc DstElemTL = DstATL.getElementLoc();
5503   DstElemTL.initializeFullCopy(SrcElemTL);
5504   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5505   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5506   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5507 }
5508 
5509 /// Helper method to turn variable array types into constant array
5510 /// types in certain situations which would otherwise be errors (for
5511 /// GCC compatibility).
5512 static TypeSourceInfo*
5513 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5514                                               ASTContext &Context,
5515                                               bool &SizeIsNegative,
5516                                               llvm::APSInt &Oversized) {
5517   QualType FixedTy
5518     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5519                                           SizeIsNegative, Oversized);
5520   if (FixedTy.isNull())
5521     return nullptr;
5522   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5523   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5524                                     FixedTInfo->getTypeLoc());
5525   return FixedTInfo;
5526 }
5527 
5528 /// \brief Register the given locally-scoped extern "C" declaration so
5529 /// that it can be found later for redeclarations. We include any extern "C"
5530 /// declaration that is not visible in the translation unit here, not just
5531 /// function-scope declarations.
5532 void
5533 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5534   if (!getLangOpts().CPlusPlus &&
5535       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5536     // Don't need to track declarations in the TU in C.
5537     return;
5538 
5539   // Note that we have a locally-scoped external with this name.
5540   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5541 }
5542 
5543 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5544   // FIXME: We can have multiple results via __attribute__((overloadable)).
5545   auto Result = Context.getExternCContextDecl()->lookup(Name);
5546   return Result.empty() ? nullptr : *Result.begin();
5547 }
5548 
5549 /// \brief Diagnose function specifiers on a declaration of an identifier that
5550 /// does not identify a function.
5551 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5552   // FIXME: We should probably indicate the identifier in question to avoid
5553   // confusion for constructs like "virtual int a(), b;"
5554   if (DS.isVirtualSpecified())
5555     Diag(DS.getVirtualSpecLoc(),
5556          diag::err_virtual_non_function);
5557 
5558   if (DS.isExplicitSpecified())
5559     Diag(DS.getExplicitSpecLoc(),
5560          diag::err_explicit_non_function);
5561 
5562   if (DS.isNoreturnSpecified())
5563     Diag(DS.getNoreturnSpecLoc(),
5564          diag::err_noreturn_non_function);
5565 }
5566 
5567 NamedDecl*
5568 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5569                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5570   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5571   if (D.getCXXScopeSpec().isSet()) {
5572     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5573       << D.getCXXScopeSpec().getRange();
5574     D.setInvalidType();
5575     // Pretend we didn't see the scope specifier.
5576     DC = CurContext;
5577     Previous.clear();
5578   }
5579 
5580   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5581 
5582   if (D.getDeclSpec().isInlineSpecified())
5583     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5584         << getLangOpts().CPlusPlus1z;
5585   if (D.getDeclSpec().isConstexprSpecified())
5586     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5587       << 1;
5588   if (D.getDeclSpec().isConceptSpecified())
5589     Diag(D.getDeclSpec().getConceptSpecLoc(),
5590          diag::err_concept_wrong_decl_kind);
5591 
5592   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5593     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5594       Diag(D.getName().StartLocation,
5595            diag::err_deduction_guide_invalid_specifier)
5596           << "typedef";
5597     else
5598       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5599           << D.getName().getSourceRange();
5600     return nullptr;
5601   }
5602 
5603   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5604   if (!NewTD) return nullptr;
5605 
5606   // Handle attributes prior to checking for duplicates in MergeVarDecl
5607   ProcessDeclAttributes(S, NewTD, D);
5608 
5609   CheckTypedefForVariablyModifiedType(S, NewTD);
5610 
5611   bool Redeclaration = D.isRedeclaration();
5612   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5613   D.setRedeclaration(Redeclaration);
5614   return ND;
5615 }
5616 
5617 void
5618 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5619   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5620   // then it shall have block scope.
5621   // Note that variably modified types must be fixed before merging the decl so
5622   // that redeclarations will match.
5623   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5624   QualType T = TInfo->getType();
5625   if (T->isVariablyModifiedType()) {
5626     getCurFunction()->setHasBranchProtectedScope();
5627 
5628     if (S->getFnParent() == nullptr) {
5629       bool SizeIsNegative;
5630       llvm::APSInt Oversized;
5631       TypeSourceInfo *FixedTInfo =
5632         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5633                                                       SizeIsNegative,
5634                                                       Oversized);
5635       if (FixedTInfo) {
5636         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5637         NewTD->setTypeSourceInfo(FixedTInfo);
5638       } else {
5639         if (SizeIsNegative)
5640           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5641         else if (T->isVariableArrayType())
5642           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5643         else if (Oversized.getBoolValue())
5644           Diag(NewTD->getLocation(), diag::err_array_too_large)
5645             << Oversized.toString(10);
5646         else
5647           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5648         NewTD->setInvalidDecl();
5649       }
5650     }
5651   }
5652 }
5653 
5654 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5655 /// declares a typedef-name, either using the 'typedef' type specifier or via
5656 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5657 NamedDecl*
5658 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5659                            LookupResult &Previous, bool &Redeclaration) {
5660 
5661   // Find the shadowed declaration before filtering for scope.
5662   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5663 
5664   // Merge the decl with the existing one if appropriate. If the decl is
5665   // in an outer scope, it isn't the same thing.
5666   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5667                        /*AllowInlineNamespace*/false);
5668   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5669   if (!Previous.empty()) {
5670     Redeclaration = true;
5671     MergeTypedefNameDecl(S, NewTD, Previous);
5672   }
5673 
5674   if (ShadowedDecl && !Redeclaration)
5675     CheckShadow(NewTD, ShadowedDecl, Previous);
5676 
5677   // If this is the C FILE type, notify the AST context.
5678   if (IdentifierInfo *II = NewTD->getIdentifier())
5679     if (!NewTD->isInvalidDecl() &&
5680         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5681       if (II->isStr("FILE"))
5682         Context.setFILEDecl(NewTD);
5683       else if (II->isStr("jmp_buf"))
5684         Context.setjmp_bufDecl(NewTD);
5685       else if (II->isStr("sigjmp_buf"))
5686         Context.setsigjmp_bufDecl(NewTD);
5687       else if (II->isStr("ucontext_t"))
5688         Context.setucontext_tDecl(NewTD);
5689     }
5690 
5691   return NewTD;
5692 }
5693 
5694 /// \brief Determines whether the given declaration is an out-of-scope
5695 /// previous declaration.
5696 ///
5697 /// This routine should be invoked when name lookup has found a
5698 /// previous declaration (PrevDecl) that is not in the scope where a
5699 /// new declaration by the same name is being introduced. If the new
5700 /// declaration occurs in a local scope, previous declarations with
5701 /// linkage may still be considered previous declarations (C99
5702 /// 6.2.2p4-5, C++ [basic.link]p6).
5703 ///
5704 /// \param PrevDecl the previous declaration found by name
5705 /// lookup
5706 ///
5707 /// \param DC the context in which the new declaration is being
5708 /// declared.
5709 ///
5710 /// \returns true if PrevDecl is an out-of-scope previous declaration
5711 /// for a new delcaration with the same name.
5712 static bool
5713 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5714                                 ASTContext &Context) {
5715   if (!PrevDecl)
5716     return false;
5717 
5718   if (!PrevDecl->hasLinkage())
5719     return false;
5720 
5721   if (Context.getLangOpts().CPlusPlus) {
5722     // C++ [basic.link]p6:
5723     //   If there is a visible declaration of an entity with linkage
5724     //   having the same name and type, ignoring entities declared
5725     //   outside the innermost enclosing namespace scope, the block
5726     //   scope declaration declares that same entity and receives the
5727     //   linkage of the previous declaration.
5728     DeclContext *OuterContext = DC->getRedeclContext();
5729     if (!OuterContext->isFunctionOrMethod())
5730       // This rule only applies to block-scope declarations.
5731       return false;
5732 
5733     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5734     if (PrevOuterContext->isRecord())
5735       // We found a member function: ignore it.
5736       return false;
5737 
5738     // Find the innermost enclosing namespace for the new and
5739     // previous declarations.
5740     OuterContext = OuterContext->getEnclosingNamespaceContext();
5741     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5742 
5743     // The previous declaration is in a different namespace, so it
5744     // isn't the same function.
5745     if (!OuterContext->Equals(PrevOuterContext))
5746       return false;
5747   }
5748 
5749   return true;
5750 }
5751 
5752 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5753   CXXScopeSpec &SS = D.getCXXScopeSpec();
5754   if (!SS.isSet()) return;
5755   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5756 }
5757 
5758 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5759   QualType type = decl->getType();
5760   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5761   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5762     // Various kinds of declaration aren't allowed to be __autoreleasing.
5763     unsigned kind = -1U;
5764     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5765       if (var->hasAttr<BlocksAttr>())
5766         kind = 0; // __block
5767       else if (!var->hasLocalStorage())
5768         kind = 1; // global
5769     } else if (isa<ObjCIvarDecl>(decl)) {
5770       kind = 3; // ivar
5771     } else if (isa<FieldDecl>(decl)) {
5772       kind = 2; // field
5773     }
5774 
5775     if (kind != -1U) {
5776       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5777         << kind;
5778     }
5779   } else if (lifetime == Qualifiers::OCL_None) {
5780     // Try to infer lifetime.
5781     if (!type->isObjCLifetimeType())
5782       return false;
5783 
5784     lifetime = type->getObjCARCImplicitLifetime();
5785     type = Context.getLifetimeQualifiedType(type, lifetime);
5786     decl->setType(type);
5787   }
5788 
5789   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5790     // Thread-local variables cannot have lifetime.
5791     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5792         var->getTLSKind()) {
5793       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5794         << var->getType();
5795       return true;
5796     }
5797   }
5798 
5799   return false;
5800 }
5801 
5802 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5803   // Ensure that an auto decl is deduced otherwise the checks below might cache
5804   // the wrong linkage.
5805   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5806 
5807   // 'weak' only applies to declarations with external linkage.
5808   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5809     if (!ND.isExternallyVisible()) {
5810       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5811       ND.dropAttr<WeakAttr>();
5812     }
5813   }
5814   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5815     if (ND.isExternallyVisible()) {
5816       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5817       ND.dropAttr<WeakRefAttr>();
5818       ND.dropAttr<AliasAttr>();
5819     }
5820   }
5821 
5822   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5823     if (VD->hasInit()) {
5824       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5825         assert(VD->isThisDeclarationADefinition() &&
5826                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5827         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5828         VD->dropAttr<AliasAttr>();
5829       }
5830     }
5831   }
5832 
5833   // 'selectany' only applies to externally visible variable declarations.
5834   // It does not apply to functions.
5835   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5836     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5837       S.Diag(Attr->getLocation(),
5838              diag::err_attribute_selectany_non_extern_data);
5839       ND.dropAttr<SelectAnyAttr>();
5840     }
5841   }
5842 
5843   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5844     // dll attributes require external linkage. Static locals may have external
5845     // linkage but still cannot be explicitly imported or exported.
5846     auto *VD = dyn_cast<VarDecl>(&ND);
5847     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5848       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5849         << &ND << Attr;
5850       ND.setInvalidDecl();
5851     }
5852   }
5853 
5854   // Virtual functions cannot be marked as 'notail'.
5855   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5856     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5857       if (MD->isVirtual()) {
5858         S.Diag(ND.getLocation(),
5859                diag::err_invalid_attribute_on_virtual_function)
5860             << Attr;
5861         ND.dropAttr<NotTailCalledAttr>();
5862       }
5863 }
5864 
5865 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5866                                            NamedDecl *NewDecl,
5867                                            bool IsSpecialization,
5868                                            bool IsDefinition) {
5869   if (OldDecl->isInvalidDecl())
5870     return;
5871 
5872   bool IsTemplate = false;
5873   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5874     OldDecl = OldTD->getTemplatedDecl();
5875     IsTemplate = true;
5876     if (!IsSpecialization)
5877       IsDefinition = false;
5878   }
5879   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5880     NewDecl = NewTD->getTemplatedDecl();
5881     IsTemplate = true;
5882   }
5883 
5884   if (!OldDecl || !NewDecl)
5885     return;
5886 
5887   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5888   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5889   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5890   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5891 
5892   // dllimport and dllexport are inheritable attributes so we have to exclude
5893   // inherited attribute instances.
5894   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5895                     (NewExportAttr && !NewExportAttr->isInherited());
5896 
5897   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5898   // the only exception being explicit specializations.
5899   // Implicitly generated declarations are also excluded for now because there
5900   // is no other way to switch these to use dllimport or dllexport.
5901   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5902 
5903   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5904     // Allow with a warning for free functions and global variables.
5905     bool JustWarn = false;
5906     if (!OldDecl->isCXXClassMember()) {
5907       auto *VD = dyn_cast<VarDecl>(OldDecl);
5908       if (VD && !VD->getDescribedVarTemplate())
5909         JustWarn = true;
5910       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5911       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5912         JustWarn = true;
5913     }
5914 
5915     // We cannot change a declaration that's been used because IR has already
5916     // been emitted. Dllimported functions will still work though (modulo
5917     // address equality) as they can use the thunk.
5918     if (OldDecl->isUsed())
5919       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5920         JustWarn = false;
5921 
5922     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5923                                : diag::err_attribute_dll_redeclaration;
5924     S.Diag(NewDecl->getLocation(), DiagID)
5925         << NewDecl
5926         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5927     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5928     if (!JustWarn) {
5929       NewDecl->setInvalidDecl();
5930       return;
5931     }
5932   }
5933 
5934   // A redeclaration is not allowed to drop a dllimport attribute, the only
5935   // exceptions being inline function definitions (except for function
5936   // templates), local extern declarations, qualified friend declarations or
5937   // special MSVC extension: in the last case, the declaration is treated as if
5938   // it were marked dllexport.
5939   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5940   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5941   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5942     // Ignore static data because out-of-line definitions are diagnosed
5943     // separately.
5944     IsStaticDataMember = VD->isStaticDataMember();
5945     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5946                    VarDecl::DeclarationOnly;
5947   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5948     IsInline = FD->isInlined();
5949     IsQualifiedFriend = FD->getQualifier() &&
5950                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5951   }
5952 
5953   if (OldImportAttr && !HasNewAttr &&
5954       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5955       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5956     if (IsMicrosoft && IsDefinition) {
5957       S.Diag(NewDecl->getLocation(),
5958              diag::warn_redeclaration_without_import_attribute)
5959           << NewDecl;
5960       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5961       NewDecl->dropAttr<DLLImportAttr>();
5962       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5963           NewImportAttr->getRange(), S.Context,
5964           NewImportAttr->getSpellingListIndex()));
5965     } else {
5966       S.Diag(NewDecl->getLocation(),
5967              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5968           << NewDecl << OldImportAttr;
5969       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5970       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5971       OldDecl->dropAttr<DLLImportAttr>();
5972       NewDecl->dropAttr<DLLImportAttr>();
5973     }
5974   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5975     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5976     OldDecl->dropAttr<DLLImportAttr>();
5977     NewDecl->dropAttr<DLLImportAttr>();
5978     S.Diag(NewDecl->getLocation(),
5979            diag::warn_dllimport_dropped_from_inline_function)
5980         << NewDecl << OldImportAttr;
5981   }
5982 }
5983 
5984 /// Given that we are within the definition of the given function,
5985 /// will that definition behave like C99's 'inline', where the
5986 /// definition is discarded except for optimization purposes?
5987 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5988   // Try to avoid calling GetGVALinkageForFunction.
5989 
5990   // All cases of this require the 'inline' keyword.
5991   if (!FD->isInlined()) return false;
5992 
5993   // This is only possible in C++ with the gnu_inline attribute.
5994   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5995     return false;
5996 
5997   // Okay, go ahead and call the relatively-more-expensive function.
5998   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5999 }
6000 
6001 /// Determine whether a variable is extern "C" prior to attaching
6002 /// an initializer. We can't just call isExternC() here, because that
6003 /// will also compute and cache whether the declaration is externally
6004 /// visible, which might change when we attach the initializer.
6005 ///
6006 /// This can only be used if the declaration is known to not be a
6007 /// redeclaration of an internal linkage declaration.
6008 ///
6009 /// For instance:
6010 ///
6011 ///   auto x = []{};
6012 ///
6013 /// Attaching the initializer here makes this declaration not externally
6014 /// visible, because its type has internal linkage.
6015 ///
6016 /// FIXME: This is a hack.
6017 template<typename T>
6018 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6019   if (S.getLangOpts().CPlusPlus) {
6020     // In C++, the overloadable attribute negates the effects of extern "C".
6021     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6022       return false;
6023 
6024     // So do CUDA's host/device attributes.
6025     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6026                                  D->template hasAttr<CUDAHostAttr>()))
6027       return false;
6028   }
6029   return D->isExternC();
6030 }
6031 
6032 static bool shouldConsiderLinkage(const VarDecl *VD) {
6033   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6034   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6035     return VD->hasExternalStorage();
6036   if (DC->isFileContext())
6037     return true;
6038   if (DC->isRecord())
6039     return false;
6040   llvm_unreachable("Unexpected context");
6041 }
6042 
6043 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6044   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6045   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6046       isa<OMPDeclareReductionDecl>(DC))
6047     return true;
6048   if (DC->isRecord())
6049     return false;
6050   llvm_unreachable("Unexpected context");
6051 }
6052 
6053 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6054                           AttributeList::Kind Kind) {
6055   for (const AttributeList *L = AttrList; L; L = L->getNext())
6056     if (L->getKind() == Kind)
6057       return true;
6058   return false;
6059 }
6060 
6061 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6062                           AttributeList::Kind Kind) {
6063   // Check decl attributes on the DeclSpec.
6064   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6065     return true;
6066 
6067   // Walk the declarator structure, checking decl attributes that were in a type
6068   // position to the decl itself.
6069   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6070     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6071       return true;
6072   }
6073 
6074   // Finally, check attributes on the decl itself.
6075   return hasParsedAttr(S, PD.getAttributes(), Kind);
6076 }
6077 
6078 /// Adjust the \c DeclContext for a function or variable that might be a
6079 /// function-local external declaration.
6080 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6081   if (!DC->isFunctionOrMethod())
6082     return false;
6083 
6084   // If this is a local extern function or variable declared within a function
6085   // template, don't add it into the enclosing namespace scope until it is
6086   // instantiated; it might have a dependent type right now.
6087   if (DC->isDependentContext())
6088     return true;
6089 
6090   // C++11 [basic.link]p7:
6091   //   When a block scope declaration of an entity with linkage is not found to
6092   //   refer to some other declaration, then that entity is a member of the
6093   //   innermost enclosing namespace.
6094   //
6095   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6096   // semantically-enclosing namespace, not a lexically-enclosing one.
6097   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6098     DC = DC->getParent();
6099   return true;
6100 }
6101 
6102 /// \brief Returns true if given declaration has external C language linkage.
6103 static bool isDeclExternC(const Decl *D) {
6104   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6105     return FD->isExternC();
6106   if (const auto *VD = dyn_cast<VarDecl>(D))
6107     return VD->isExternC();
6108 
6109   llvm_unreachable("Unknown type of decl!");
6110 }
6111 
6112 NamedDecl *Sema::ActOnVariableDeclarator(
6113     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6114     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6115     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6116   QualType R = TInfo->getType();
6117   DeclarationName Name = GetNameForDeclarator(D).getName();
6118 
6119   IdentifierInfo *II = Name.getAsIdentifierInfo();
6120 
6121   if (D.isDecompositionDeclarator()) {
6122     AddToScope = false;
6123     // Take the name of the first declarator as our name for diagnostic
6124     // purposes.
6125     auto &Decomp = D.getDecompositionDeclarator();
6126     if (!Decomp.bindings().empty()) {
6127       II = Decomp.bindings()[0].Name;
6128       Name = II;
6129     }
6130   } else if (!II) {
6131     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6132     return nullptr;
6133   }
6134 
6135   if (getLangOpts().OpenCL) {
6136     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6137     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6138     // argument.
6139     if (R->isImageType() || R->isPipeType()) {
6140       Diag(D.getIdentifierLoc(),
6141            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6142           << R;
6143       D.setInvalidType();
6144       return nullptr;
6145     }
6146 
6147     // OpenCL v1.2 s6.9.r:
6148     // The event type cannot be used to declare a program scope variable.
6149     // OpenCL v2.0 s6.9.q:
6150     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6151     if (NULL == S->getParent()) {
6152       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6153         Diag(D.getIdentifierLoc(),
6154              diag::err_invalid_type_for_program_scope_var) << R;
6155         D.setInvalidType();
6156         return nullptr;
6157       }
6158     }
6159 
6160     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6161     QualType NR = R;
6162     while (NR->isPointerType()) {
6163       if (NR->isFunctionPointerType()) {
6164         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6165         D.setInvalidType();
6166         break;
6167       }
6168       NR = NR->getPointeeType();
6169     }
6170 
6171     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6172       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6173       // half array type (unless the cl_khr_fp16 extension is enabled).
6174       if (Context.getBaseElementType(R)->isHalfType()) {
6175         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6176         D.setInvalidType();
6177       }
6178     }
6179 
6180     if (R->isSamplerT()) {
6181       // OpenCL v1.2 s6.9.b p4:
6182       // The sampler type cannot be used with the __local and __global address
6183       // space qualifiers.
6184       if (R.getAddressSpace() == LangAS::opencl_local ||
6185           R.getAddressSpace() == LangAS::opencl_global) {
6186         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6187       }
6188 
6189       // OpenCL v1.2 s6.12.14.1:
6190       // A global sampler must be declared with either the constant address
6191       // space qualifier or with the const qualifier.
6192       if (DC->isTranslationUnit() &&
6193           !(R.getAddressSpace() == LangAS::opencl_constant ||
6194           R.isConstQualified())) {
6195         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6196         D.setInvalidType();
6197       }
6198     }
6199 
6200     // OpenCL v1.2 s6.9.r:
6201     // The event type cannot be used with the __local, __constant and __global
6202     // address space qualifiers.
6203     if (R->isEventT()) {
6204       if (R.getAddressSpace()) {
6205         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6206         D.setInvalidType();
6207       }
6208     }
6209   }
6210 
6211   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6212   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6213 
6214   // dllimport globals without explicit storage class are treated as extern. We
6215   // have to change the storage class this early to get the right DeclContext.
6216   if (SC == SC_None && !DC->isRecord() &&
6217       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6218       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6219     SC = SC_Extern;
6220 
6221   DeclContext *OriginalDC = DC;
6222   bool IsLocalExternDecl = SC == SC_Extern &&
6223                            adjustContextForLocalExternDecl(DC);
6224 
6225   if (SCSpec == DeclSpec::SCS_mutable) {
6226     // mutable can only appear on non-static class members, so it's always
6227     // an error here
6228     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6229     D.setInvalidType();
6230     SC = SC_None;
6231   }
6232 
6233   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6234       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6235                               D.getDeclSpec().getStorageClassSpecLoc())) {
6236     // In C++11, the 'register' storage class specifier is deprecated.
6237     // Suppress the warning in system macros, it's used in macros in some
6238     // popular C system headers, such as in glibc's htonl() macro.
6239     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6240          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6241                                    : diag::warn_deprecated_register)
6242       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6243   }
6244 
6245   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6246 
6247   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6248     // C99 6.9p2: The storage-class specifiers auto and register shall not
6249     // appear in the declaration specifiers in an external declaration.
6250     // Global Register+Asm is a GNU extension we support.
6251     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6252       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6253       D.setInvalidType();
6254     }
6255   }
6256 
6257   bool IsMemberSpecialization = false;
6258   bool IsVariableTemplateSpecialization = false;
6259   bool IsPartialSpecialization = false;
6260   bool IsVariableTemplate = false;
6261   VarDecl *NewVD = nullptr;
6262   VarTemplateDecl *NewTemplate = nullptr;
6263   TemplateParameterList *TemplateParams = nullptr;
6264   if (!getLangOpts().CPlusPlus) {
6265     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6266                             D.getIdentifierLoc(), II,
6267                             R, TInfo, SC);
6268 
6269     if (R->getContainedDeducedType())
6270       ParsingInitForAutoVars.insert(NewVD);
6271 
6272     if (D.isInvalidType())
6273       NewVD->setInvalidDecl();
6274   } else {
6275     bool Invalid = false;
6276 
6277     if (DC->isRecord() && !CurContext->isRecord()) {
6278       // This is an out-of-line definition of a static data member.
6279       switch (SC) {
6280       case SC_None:
6281         break;
6282       case SC_Static:
6283         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6284              diag::err_static_out_of_line)
6285           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6286         break;
6287       case SC_Auto:
6288       case SC_Register:
6289       case SC_Extern:
6290         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6291         // to names of variables declared in a block or to function parameters.
6292         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6293         // of class members
6294 
6295         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6296              diag::err_storage_class_for_static_member)
6297           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6298         break;
6299       case SC_PrivateExtern:
6300         llvm_unreachable("C storage class in c++!");
6301       }
6302     }
6303 
6304     if (SC == SC_Static && CurContext->isRecord()) {
6305       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6306         if (RD->isLocalClass())
6307           Diag(D.getIdentifierLoc(),
6308                diag::err_static_data_member_not_allowed_in_local_class)
6309             << Name << RD->getDeclName();
6310 
6311         // C++98 [class.union]p1: If a union contains a static data member,
6312         // the program is ill-formed. C++11 drops this restriction.
6313         if (RD->isUnion())
6314           Diag(D.getIdentifierLoc(),
6315                getLangOpts().CPlusPlus11
6316                  ? diag::warn_cxx98_compat_static_data_member_in_union
6317                  : diag::ext_static_data_member_in_union) << Name;
6318         // We conservatively disallow static data members in anonymous structs.
6319         else if (!RD->getDeclName())
6320           Diag(D.getIdentifierLoc(),
6321                diag::err_static_data_member_not_allowed_in_anon_struct)
6322             << Name << RD->isUnion();
6323       }
6324     }
6325 
6326     // Match up the template parameter lists with the scope specifier, then
6327     // determine whether we have a template or a template specialization.
6328     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6329         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6330         D.getCXXScopeSpec(),
6331         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6332             ? D.getName().TemplateId
6333             : nullptr,
6334         TemplateParamLists,
6335         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6336 
6337     if (TemplateParams) {
6338       if (!TemplateParams->size() &&
6339           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6340         // There is an extraneous 'template<>' for this variable. Complain
6341         // about it, but allow the declaration of the variable.
6342         Diag(TemplateParams->getTemplateLoc(),
6343              diag::err_template_variable_noparams)
6344           << II
6345           << SourceRange(TemplateParams->getTemplateLoc(),
6346                          TemplateParams->getRAngleLoc());
6347         TemplateParams = nullptr;
6348       } else {
6349         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6350           // This is an explicit specialization or a partial specialization.
6351           // FIXME: Check that we can declare a specialization here.
6352           IsVariableTemplateSpecialization = true;
6353           IsPartialSpecialization = TemplateParams->size() > 0;
6354         } else { // if (TemplateParams->size() > 0)
6355           // This is a template declaration.
6356           IsVariableTemplate = true;
6357 
6358           // Check that we can declare a template here.
6359           if (CheckTemplateDeclScope(S, TemplateParams))
6360             return nullptr;
6361 
6362           // Only C++1y supports variable templates (N3651).
6363           Diag(D.getIdentifierLoc(),
6364                getLangOpts().CPlusPlus14
6365                    ? diag::warn_cxx11_compat_variable_template
6366                    : diag::ext_variable_template);
6367         }
6368       }
6369     } else {
6370       assert(
6371           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6372           "should have a 'template<>' for this decl");
6373     }
6374 
6375     if (IsVariableTemplateSpecialization) {
6376       SourceLocation TemplateKWLoc =
6377           TemplateParamLists.size() > 0
6378               ? TemplateParamLists[0]->getTemplateLoc()
6379               : SourceLocation();
6380       DeclResult Res = ActOnVarTemplateSpecialization(
6381           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6382           IsPartialSpecialization);
6383       if (Res.isInvalid())
6384         return nullptr;
6385       NewVD = cast<VarDecl>(Res.get());
6386       AddToScope = false;
6387     } else if (D.isDecompositionDeclarator()) {
6388       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6389                                         D.getIdentifierLoc(), R, TInfo, SC,
6390                                         Bindings);
6391     } else
6392       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6393                               D.getIdentifierLoc(), II, R, TInfo, SC);
6394 
6395     // If this is supposed to be a variable template, create it as such.
6396     if (IsVariableTemplate) {
6397       NewTemplate =
6398           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6399                                   TemplateParams, NewVD);
6400       NewVD->setDescribedVarTemplate(NewTemplate);
6401     }
6402 
6403     // If this decl has an auto type in need of deduction, make a note of the
6404     // Decl so we can diagnose uses of it in its own initializer.
6405     if (R->getContainedDeducedType())
6406       ParsingInitForAutoVars.insert(NewVD);
6407 
6408     if (D.isInvalidType() || Invalid) {
6409       NewVD->setInvalidDecl();
6410       if (NewTemplate)
6411         NewTemplate->setInvalidDecl();
6412     }
6413 
6414     SetNestedNameSpecifier(NewVD, D);
6415 
6416     // If we have any template parameter lists that don't directly belong to
6417     // the variable (matching the scope specifier), store them.
6418     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6419     if (TemplateParamLists.size() > VDTemplateParamLists)
6420       NewVD->setTemplateParameterListsInfo(
6421           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6422 
6423     if (D.getDeclSpec().isConstexprSpecified()) {
6424       NewVD->setConstexpr(true);
6425       // C++1z [dcl.spec.constexpr]p1:
6426       //   A static data member declared with the constexpr specifier is
6427       //   implicitly an inline variable.
6428       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6429         NewVD->setImplicitlyInline();
6430     }
6431 
6432     if (D.getDeclSpec().isConceptSpecified()) {
6433       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6434         VTD->setConcept();
6435 
6436       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6437       // be declared with the thread_local, inline, friend, or constexpr
6438       // specifiers, [...]
6439       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6440         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6441              diag::err_concept_decl_invalid_specifiers)
6442             << 0 << 0;
6443         NewVD->setInvalidDecl(true);
6444       }
6445 
6446       if (D.getDeclSpec().isConstexprSpecified()) {
6447         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6448              diag::err_concept_decl_invalid_specifiers)
6449             << 0 << 3;
6450         NewVD->setInvalidDecl(true);
6451       }
6452 
6453       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6454       // applied only to the definition of a function template or variable
6455       // template, declared in namespace scope.
6456       if (IsVariableTemplateSpecialization) {
6457         Diag(D.getDeclSpec().getConceptSpecLoc(),
6458              diag::err_concept_specified_specialization)
6459             << (IsPartialSpecialization ? 2 : 1);
6460       }
6461 
6462       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6463       // following restrictions:
6464       // - The declared type shall have the type bool.
6465       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6466           !NewVD->isInvalidDecl()) {
6467         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6468         NewVD->setInvalidDecl(true);
6469       }
6470     }
6471   }
6472 
6473   if (D.getDeclSpec().isInlineSpecified()) {
6474     if (!getLangOpts().CPlusPlus) {
6475       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6476           << 0;
6477     } else if (CurContext->isFunctionOrMethod()) {
6478       // 'inline' is not allowed on block scope variable declaration.
6479       Diag(D.getDeclSpec().getInlineSpecLoc(),
6480            diag::err_inline_declaration_block_scope) << Name
6481         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6482     } else {
6483       Diag(D.getDeclSpec().getInlineSpecLoc(),
6484            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6485                                      : diag::ext_inline_variable);
6486       NewVD->setInlineSpecified();
6487     }
6488   }
6489 
6490   // Set the lexical context. If the declarator has a C++ scope specifier, the
6491   // lexical context will be different from the semantic context.
6492   NewVD->setLexicalDeclContext(CurContext);
6493   if (NewTemplate)
6494     NewTemplate->setLexicalDeclContext(CurContext);
6495 
6496   if (IsLocalExternDecl) {
6497     if (D.isDecompositionDeclarator())
6498       for (auto *B : Bindings)
6499         B->setLocalExternDecl();
6500     else
6501       NewVD->setLocalExternDecl();
6502   }
6503 
6504   bool EmitTLSUnsupportedError = false;
6505   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6506     // C++11 [dcl.stc]p4:
6507     //   When thread_local is applied to a variable of block scope the
6508     //   storage-class-specifier static is implied if it does not appear
6509     //   explicitly.
6510     // Core issue: 'static' is not implied if the variable is declared
6511     //   'extern'.
6512     if (NewVD->hasLocalStorage() &&
6513         (SCSpec != DeclSpec::SCS_unspecified ||
6514          TSCS != DeclSpec::TSCS_thread_local ||
6515          !DC->isFunctionOrMethod()))
6516       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6517            diag::err_thread_non_global)
6518         << DeclSpec::getSpecifierName(TSCS);
6519     else if (!Context.getTargetInfo().isTLSSupported()) {
6520       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6521         // Postpone error emission until we've collected attributes required to
6522         // figure out whether it's a host or device variable and whether the
6523         // error should be ignored.
6524         EmitTLSUnsupportedError = true;
6525         // We still need to mark the variable as TLS so it shows up in AST with
6526         // proper storage class for other tools to use even if we're not going
6527         // to emit any code for it.
6528         NewVD->setTSCSpec(TSCS);
6529       } else
6530         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6531              diag::err_thread_unsupported);
6532     } else
6533       NewVD->setTSCSpec(TSCS);
6534   }
6535 
6536   // C99 6.7.4p3
6537   //   An inline definition of a function with external linkage shall
6538   //   not contain a definition of a modifiable object with static or
6539   //   thread storage duration...
6540   // We only apply this when the function is required to be defined
6541   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6542   // that a local variable with thread storage duration still has to
6543   // be marked 'static'.  Also note that it's possible to get these
6544   // semantics in C++ using __attribute__((gnu_inline)).
6545   if (SC == SC_Static && S->getFnParent() != nullptr &&
6546       !NewVD->getType().isConstQualified()) {
6547     FunctionDecl *CurFD = getCurFunctionDecl();
6548     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6549       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6550            diag::warn_static_local_in_extern_inline);
6551       MaybeSuggestAddingStaticToDecl(CurFD);
6552     }
6553   }
6554 
6555   if (D.getDeclSpec().isModulePrivateSpecified()) {
6556     if (IsVariableTemplateSpecialization)
6557       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6558           << (IsPartialSpecialization ? 1 : 0)
6559           << FixItHint::CreateRemoval(
6560                  D.getDeclSpec().getModulePrivateSpecLoc());
6561     else if (IsMemberSpecialization)
6562       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6563         << 2
6564         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6565     else if (NewVD->hasLocalStorage())
6566       Diag(NewVD->getLocation(), diag::err_module_private_local)
6567         << 0 << NewVD->getDeclName()
6568         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6569         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6570     else {
6571       NewVD->setModulePrivate();
6572       if (NewTemplate)
6573         NewTemplate->setModulePrivate();
6574       for (auto *B : Bindings)
6575         B->setModulePrivate();
6576     }
6577   }
6578 
6579   // Handle attributes prior to checking for duplicates in MergeVarDecl
6580   ProcessDeclAttributes(S, NewVD, D);
6581 
6582   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6583     if (EmitTLSUnsupportedError &&
6584         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6585          (getLangOpts().OpenMPIsDevice &&
6586           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6587       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6588            diag::err_thread_unsupported);
6589     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6590     // storage [duration]."
6591     if (SC == SC_None && S->getFnParent() != nullptr &&
6592         (NewVD->hasAttr<CUDASharedAttr>() ||
6593          NewVD->hasAttr<CUDAConstantAttr>())) {
6594       NewVD->setStorageClass(SC_Static);
6595     }
6596   }
6597 
6598   // Ensure that dllimport globals without explicit storage class are treated as
6599   // extern. The storage class is set above using parsed attributes. Now we can
6600   // check the VarDecl itself.
6601   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6602          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6603          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6604 
6605   // In auto-retain/release, infer strong retension for variables of
6606   // retainable type.
6607   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6608     NewVD->setInvalidDecl();
6609 
6610   // Handle GNU asm-label extension (encoded as an attribute).
6611   if (Expr *E = (Expr*)D.getAsmLabel()) {
6612     // The parser guarantees this is a string.
6613     StringLiteral *SE = cast<StringLiteral>(E);
6614     StringRef Label = SE->getString();
6615     if (S->getFnParent() != nullptr) {
6616       switch (SC) {
6617       case SC_None:
6618       case SC_Auto:
6619         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6620         break;
6621       case SC_Register:
6622         // Local Named register
6623         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6624             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6625           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6626         break;
6627       case SC_Static:
6628       case SC_Extern:
6629       case SC_PrivateExtern:
6630         break;
6631       }
6632     } else if (SC == SC_Register) {
6633       // Global Named register
6634       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6635         const auto &TI = Context.getTargetInfo();
6636         bool HasSizeMismatch;
6637 
6638         if (!TI.isValidGCCRegisterName(Label))
6639           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6640         else if (!TI.validateGlobalRegisterVariable(Label,
6641                                                     Context.getTypeSize(R),
6642                                                     HasSizeMismatch))
6643           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6644         else if (HasSizeMismatch)
6645           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6646       }
6647 
6648       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6649         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6650         NewVD->setInvalidDecl(true);
6651       }
6652     }
6653 
6654     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6655                                                 Context, Label, 0));
6656   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6657     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6658       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6659     if (I != ExtnameUndeclaredIdentifiers.end()) {
6660       if (isDeclExternC(NewVD)) {
6661         NewVD->addAttr(I->second);
6662         ExtnameUndeclaredIdentifiers.erase(I);
6663       } else
6664         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6665             << /*Variable*/1 << NewVD;
6666     }
6667   }
6668 
6669   // Find the shadowed declaration before filtering for scope.
6670   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6671                                 ? getShadowedDeclaration(NewVD, Previous)
6672                                 : nullptr;
6673 
6674   // Don't consider existing declarations that are in a different
6675   // scope and are out-of-semantic-context declarations (if the new
6676   // declaration has linkage).
6677   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6678                        D.getCXXScopeSpec().isNotEmpty() ||
6679                        IsMemberSpecialization ||
6680                        IsVariableTemplateSpecialization);
6681 
6682   // Check whether the previous declaration is in the same block scope. This
6683   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6684   if (getLangOpts().CPlusPlus &&
6685       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6686     NewVD->setPreviousDeclInSameBlockScope(
6687         Previous.isSingleResult() && !Previous.isShadowed() &&
6688         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6689 
6690   if (!getLangOpts().CPlusPlus) {
6691     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6692   } else {
6693     // If this is an explicit specialization of a static data member, check it.
6694     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6695         CheckMemberSpecialization(NewVD, Previous))
6696       NewVD->setInvalidDecl();
6697 
6698     // Merge the decl with the existing one if appropriate.
6699     if (!Previous.empty()) {
6700       if (Previous.isSingleResult() &&
6701           isa<FieldDecl>(Previous.getFoundDecl()) &&
6702           D.getCXXScopeSpec().isSet()) {
6703         // The user tried to define a non-static data member
6704         // out-of-line (C++ [dcl.meaning]p1).
6705         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6706           << D.getCXXScopeSpec().getRange();
6707         Previous.clear();
6708         NewVD->setInvalidDecl();
6709       }
6710     } else if (D.getCXXScopeSpec().isSet()) {
6711       // No previous declaration in the qualifying scope.
6712       Diag(D.getIdentifierLoc(), diag::err_no_member)
6713         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6714         << D.getCXXScopeSpec().getRange();
6715       NewVD->setInvalidDecl();
6716     }
6717 
6718     if (!IsVariableTemplateSpecialization)
6719       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6720 
6721     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6722     // an explicit specialization (14.8.3) or a partial specialization of a
6723     // concept definition.
6724     if (IsVariableTemplateSpecialization &&
6725         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6726         Previous.isSingleResult()) {
6727       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6728       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6729         if (VarTmpl->isConcept()) {
6730           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6731               << 1                            /*variable*/
6732               << (IsPartialSpecialization ? 2 /*partially specialized*/
6733                                           : 1 /*explicitly specialized*/);
6734           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6735           NewVD->setInvalidDecl();
6736         }
6737       }
6738     }
6739 
6740     if (NewTemplate) {
6741       VarTemplateDecl *PrevVarTemplate =
6742           NewVD->getPreviousDecl()
6743               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6744               : nullptr;
6745 
6746       // Check the template parameter list of this declaration, possibly
6747       // merging in the template parameter list from the previous variable
6748       // template declaration.
6749       if (CheckTemplateParameterList(
6750               TemplateParams,
6751               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6752                               : nullptr,
6753               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6754                DC->isDependentContext())
6755                   ? TPC_ClassTemplateMember
6756                   : TPC_VarTemplate))
6757         NewVD->setInvalidDecl();
6758 
6759       // If we are providing an explicit specialization of a static variable
6760       // template, make a note of that.
6761       if (PrevVarTemplate &&
6762           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6763         PrevVarTemplate->setMemberSpecialization();
6764     }
6765   }
6766 
6767   // Diagnose shadowed variables iff this isn't a redeclaration.
6768   if (ShadowedDecl && !D.isRedeclaration())
6769     CheckShadow(NewVD, ShadowedDecl, Previous);
6770 
6771   ProcessPragmaWeak(S, NewVD);
6772 
6773   // If this is the first declaration of an extern C variable, update
6774   // the map of such variables.
6775   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6776       isIncompleteDeclExternC(*this, NewVD))
6777     RegisterLocallyScopedExternCDecl(NewVD, S);
6778 
6779   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6780     Decl *ManglingContextDecl;
6781     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6782             NewVD->getDeclContext(), ManglingContextDecl)) {
6783       Context.setManglingNumber(
6784           NewVD, MCtx->getManglingNumber(
6785                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6786       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6787     }
6788   }
6789 
6790   // Special handling of variable named 'main'.
6791   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6792       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6793       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6794 
6795     // C++ [basic.start.main]p3
6796     // A program that declares a variable main at global scope is ill-formed.
6797     if (getLangOpts().CPlusPlus)
6798       Diag(D.getLocStart(), diag::err_main_global_variable);
6799 
6800     // In C, and external-linkage variable named main results in undefined
6801     // behavior.
6802     else if (NewVD->hasExternalFormalLinkage())
6803       Diag(D.getLocStart(), diag::warn_main_redefined);
6804   }
6805 
6806   if (D.isRedeclaration() && !Previous.empty()) {
6807     checkDLLAttributeRedeclaration(
6808         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6809         IsMemberSpecialization, D.isFunctionDefinition());
6810   }
6811 
6812   if (NewTemplate) {
6813     if (NewVD->isInvalidDecl())
6814       NewTemplate->setInvalidDecl();
6815     ActOnDocumentableDecl(NewTemplate);
6816     return NewTemplate;
6817   }
6818 
6819   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6820     CompleteMemberSpecialization(NewVD, Previous);
6821 
6822   return NewVD;
6823 }
6824 
6825 /// Enum describing the %select options in diag::warn_decl_shadow.
6826 enum ShadowedDeclKind {
6827   SDK_Local,
6828   SDK_Global,
6829   SDK_StaticMember,
6830   SDK_Field,
6831   SDK_Typedef,
6832   SDK_Using
6833 };
6834 
6835 /// Determine what kind of declaration we're shadowing.
6836 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6837                                                 const DeclContext *OldDC) {
6838   if (isa<TypeAliasDecl>(ShadowedDecl))
6839     return SDK_Using;
6840   else if (isa<TypedefDecl>(ShadowedDecl))
6841     return SDK_Typedef;
6842   else if (isa<RecordDecl>(OldDC))
6843     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6844 
6845   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6846 }
6847 
6848 /// Return the location of the capture if the given lambda captures the given
6849 /// variable \p VD, or an invalid source location otherwise.
6850 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6851                                          const VarDecl *VD) {
6852   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6853     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6854       return Capture.getLocation();
6855   }
6856   return SourceLocation();
6857 }
6858 
6859 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6860                                      const LookupResult &R) {
6861   // Only diagnose if we're shadowing an unambiguous field or variable.
6862   if (R.getResultKind() != LookupResult::Found)
6863     return false;
6864 
6865   // Return false if warning is ignored.
6866   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6867 }
6868 
6869 /// \brief Return the declaration shadowed by the given variable \p D, or null
6870 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6871 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6872                                         const LookupResult &R) {
6873   if (!shouldWarnIfShadowedDecl(Diags, R))
6874     return nullptr;
6875 
6876   // Don't diagnose declarations at file scope.
6877   if (D->hasGlobalStorage())
6878     return nullptr;
6879 
6880   NamedDecl *ShadowedDecl = R.getFoundDecl();
6881   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6882              ? ShadowedDecl
6883              : nullptr;
6884 }
6885 
6886 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6887 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6888 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6889                                         const LookupResult &R) {
6890   // Don't warn if typedef declaration is part of a class
6891   if (D->getDeclContext()->isRecord())
6892     return nullptr;
6893 
6894   if (!shouldWarnIfShadowedDecl(Diags, R))
6895     return nullptr;
6896 
6897   NamedDecl *ShadowedDecl = R.getFoundDecl();
6898   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6899 }
6900 
6901 /// \brief Diagnose variable or built-in function shadowing.  Implements
6902 /// -Wshadow.
6903 ///
6904 /// This method is called whenever a VarDecl is added to a "useful"
6905 /// scope.
6906 ///
6907 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6908 /// \param R the lookup of the name
6909 ///
6910 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6911                        const LookupResult &R) {
6912   DeclContext *NewDC = D->getDeclContext();
6913 
6914   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6915     // Fields are not shadowed by variables in C++ static methods.
6916     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6917       if (MD->isStatic())
6918         return;
6919 
6920     // Fields shadowed by constructor parameters are a special case. Usually
6921     // the constructor initializes the field with the parameter.
6922     if (isa<CXXConstructorDecl>(NewDC))
6923       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6924         // Remember that this was shadowed so we can either warn about its
6925         // modification or its existence depending on warning settings.
6926         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6927         return;
6928       }
6929   }
6930 
6931   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6932     if (shadowedVar->isExternC()) {
6933       // For shadowing external vars, make sure that we point to the global
6934       // declaration, not a locally scoped extern declaration.
6935       for (auto I : shadowedVar->redecls())
6936         if (I->isFileVarDecl()) {
6937           ShadowedDecl = I;
6938           break;
6939         }
6940     }
6941 
6942   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6943 
6944   unsigned WarningDiag = diag::warn_decl_shadow;
6945   SourceLocation CaptureLoc;
6946   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6947       isa<CXXMethodDecl>(NewDC)) {
6948     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6949       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6950         if (RD->getLambdaCaptureDefault() == LCD_None) {
6951           // Try to avoid warnings for lambdas with an explicit capture list.
6952           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6953           // Warn only when the lambda captures the shadowed decl explicitly.
6954           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6955           if (CaptureLoc.isInvalid())
6956             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6957         } else {
6958           // Remember that this was shadowed so we can avoid the warning if the
6959           // shadowed decl isn't captured and the warning settings allow it.
6960           cast<LambdaScopeInfo>(getCurFunction())
6961               ->ShadowingDecls.push_back(
6962                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6963           return;
6964         }
6965       }
6966     }
6967   }
6968 
6969   // Only warn about certain kinds of shadowing for class members.
6970   if (NewDC && NewDC->isRecord()) {
6971     // In particular, don't warn about shadowing non-class members.
6972     if (!OldDC->isRecord())
6973       return;
6974 
6975     // TODO: should we warn about static data members shadowing
6976     // static data members from base classes?
6977 
6978     // TODO: don't diagnose for inaccessible shadowed members.
6979     // This is hard to do perfectly because we might friend the
6980     // shadowing context, but that's just a false negative.
6981   }
6982 
6983 
6984   DeclarationName Name = R.getLookupName();
6985 
6986   // Emit warning and note.
6987   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6988     return;
6989   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6990   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6991   if (!CaptureLoc.isInvalid())
6992     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6993         << Name << /*explicitly*/ 1;
6994   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6995 }
6996 
6997 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6998 /// when these variables are captured by the lambda.
6999 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7000   for (const auto &Shadow : LSI->ShadowingDecls) {
7001     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7002     // Try to avoid the warning when the shadowed decl isn't captured.
7003     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7004     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7005     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7006                                        ? diag::warn_decl_shadow_uncaptured_local
7007                                        : diag::warn_decl_shadow)
7008         << Shadow.VD->getDeclName()
7009         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7010     if (!CaptureLoc.isInvalid())
7011       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7012           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7013     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7014   }
7015 }
7016 
7017 /// \brief Check -Wshadow without the advantage of a previous lookup.
7018 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7019   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7020     return;
7021 
7022   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7023                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7024   LookupName(R, S);
7025   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7026     CheckShadow(D, ShadowedDecl, R);
7027 }
7028 
7029 /// Check if 'E', which is an expression that is about to be modified, refers
7030 /// to a constructor parameter that shadows a field.
7031 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7032   // Quickly ignore expressions that can't be shadowing ctor parameters.
7033   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7034     return;
7035   E = E->IgnoreParenImpCasts();
7036   auto *DRE = dyn_cast<DeclRefExpr>(E);
7037   if (!DRE)
7038     return;
7039   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7040   auto I = ShadowingDecls.find(D);
7041   if (I == ShadowingDecls.end())
7042     return;
7043   const NamedDecl *ShadowedDecl = I->second;
7044   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7045   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7046   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7047   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048 
7049   // Avoid issuing multiple warnings about the same decl.
7050   ShadowingDecls.erase(I);
7051 }
7052 
7053 /// Check for conflict between this global or extern "C" declaration and
7054 /// previous global or extern "C" declarations. This is only used in C++.
7055 template<typename T>
7056 static bool checkGlobalOrExternCConflict(
7057     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7058   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7059   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7060 
7061   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7062     // The common case: this global doesn't conflict with any extern "C"
7063     // declaration.
7064     return false;
7065   }
7066 
7067   if (Prev) {
7068     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7069       // Both the old and new declarations have C language linkage. This is a
7070       // redeclaration.
7071       Previous.clear();
7072       Previous.addDecl(Prev);
7073       return true;
7074     }
7075 
7076     // This is a global, non-extern "C" declaration, and there is a previous
7077     // non-global extern "C" declaration. Diagnose if this is a variable
7078     // declaration.
7079     if (!isa<VarDecl>(ND))
7080       return false;
7081   } else {
7082     // The declaration is extern "C". Check for any declaration in the
7083     // translation unit which might conflict.
7084     if (IsGlobal) {
7085       // We have already performed the lookup into the translation unit.
7086       IsGlobal = false;
7087       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7088            I != E; ++I) {
7089         if (isa<VarDecl>(*I)) {
7090           Prev = *I;
7091           break;
7092         }
7093       }
7094     } else {
7095       DeclContext::lookup_result R =
7096           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7097       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7098            I != E; ++I) {
7099         if (isa<VarDecl>(*I)) {
7100           Prev = *I;
7101           break;
7102         }
7103         // FIXME: If we have any other entity with this name in global scope,
7104         // the declaration is ill-formed, but that is a defect: it breaks the
7105         // 'stat' hack, for instance. Only variables can have mangled name
7106         // clashes with extern "C" declarations, so only they deserve a
7107         // diagnostic.
7108       }
7109     }
7110 
7111     if (!Prev)
7112       return false;
7113   }
7114 
7115   // Use the first declaration's location to ensure we point at something which
7116   // is lexically inside an extern "C" linkage-spec.
7117   assert(Prev && "should have found a previous declaration to diagnose");
7118   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7119     Prev = FD->getFirstDecl();
7120   else
7121     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7122 
7123   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7124     << IsGlobal << ND;
7125   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7126     << IsGlobal;
7127   return false;
7128 }
7129 
7130 /// Apply special rules for handling extern "C" declarations. Returns \c true
7131 /// if we have found that this is a redeclaration of some prior entity.
7132 ///
7133 /// Per C++ [dcl.link]p6:
7134 ///   Two declarations [for a function or variable] with C language linkage
7135 ///   with the same name that appear in different scopes refer to the same
7136 ///   [entity]. An entity with C language linkage shall not be declared with
7137 ///   the same name as an entity in global scope.
7138 template<typename T>
7139 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7140                                                   LookupResult &Previous) {
7141   if (!S.getLangOpts().CPlusPlus) {
7142     // In C, when declaring a global variable, look for a corresponding 'extern'
7143     // variable declared in function scope. We don't need this in C++, because
7144     // we find local extern decls in the surrounding file-scope DeclContext.
7145     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7146       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7147         Previous.clear();
7148         Previous.addDecl(Prev);
7149         return true;
7150       }
7151     }
7152     return false;
7153   }
7154 
7155   // A declaration in the translation unit can conflict with an extern "C"
7156   // declaration.
7157   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7158     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7159 
7160   // An extern "C" declaration can conflict with a declaration in the
7161   // translation unit or can be a redeclaration of an extern "C" declaration
7162   // in another scope.
7163   if (isIncompleteDeclExternC(S,ND))
7164     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7165 
7166   // Neither global nor extern "C": nothing to do.
7167   return false;
7168 }
7169 
7170 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7171   // If the decl is already known invalid, don't check it.
7172   if (NewVD->isInvalidDecl())
7173     return;
7174 
7175   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7176   QualType T = TInfo->getType();
7177 
7178   // Defer checking an 'auto' type until its initializer is attached.
7179   if (T->isUndeducedType())
7180     return;
7181 
7182   if (NewVD->hasAttrs())
7183     CheckAlignasUnderalignment(NewVD);
7184 
7185   if (T->isObjCObjectType()) {
7186     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7187       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7188     T = Context.getObjCObjectPointerType(T);
7189     NewVD->setType(T);
7190   }
7191 
7192   // Emit an error if an address space was applied to decl with local storage.
7193   // This includes arrays of objects with address space qualifiers, but not
7194   // automatic variables that point to other address spaces.
7195   // ISO/IEC TR 18037 S5.1.2
7196   if (!getLangOpts().OpenCL
7197       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7198     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7199     NewVD->setInvalidDecl();
7200     return;
7201   }
7202 
7203   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7204   // scope.
7205   if (getLangOpts().OpenCLVersion == 120 &&
7206       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7207       NewVD->isStaticLocal()) {
7208     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7209     NewVD->setInvalidDecl();
7210     return;
7211   }
7212 
7213   if (getLangOpts().OpenCL) {
7214     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7215     if (NewVD->hasAttr<BlocksAttr>()) {
7216       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7217       return;
7218     }
7219 
7220     if (T->isBlockPointerType()) {
7221       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7222       // can't use 'extern' storage class.
7223       if (!T.isConstQualified()) {
7224         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7225             << 0 /*const*/;
7226         NewVD->setInvalidDecl();
7227         return;
7228       }
7229       if (NewVD->hasExternalStorage()) {
7230         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7231         NewVD->setInvalidDecl();
7232         return;
7233       }
7234     }
7235     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7236     // __constant address space.
7237     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7238     // variables inside a function can also be declared in the global
7239     // address space.
7240     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7241         NewVD->hasExternalStorage()) {
7242       if (!T->isSamplerT() &&
7243           !(T.getAddressSpace() == LangAS::opencl_constant ||
7244             (T.getAddressSpace() == LangAS::opencl_global &&
7245              getLangOpts().OpenCLVersion == 200))) {
7246         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7247         if (getLangOpts().OpenCLVersion == 200)
7248           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7249               << Scope << "global or constant";
7250         else
7251           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7252               << Scope << "constant";
7253         NewVD->setInvalidDecl();
7254         return;
7255       }
7256     } else {
7257       if (T.getAddressSpace() == LangAS::opencl_global) {
7258         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7259             << 1 /*is any function*/ << "global";
7260         NewVD->setInvalidDecl();
7261         return;
7262       }
7263       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7264       // in functions.
7265       if (T.getAddressSpace() == LangAS::opencl_constant ||
7266           T.getAddressSpace() == LangAS::opencl_local) {
7267         FunctionDecl *FD = getCurFunctionDecl();
7268         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7269           if (T.getAddressSpace() == LangAS::opencl_constant)
7270             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7271                 << 0 /*non-kernel only*/ << "constant";
7272           else
7273             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7274                 << 0 /*non-kernel only*/ << "local";
7275           NewVD->setInvalidDecl();
7276           return;
7277         }
7278       } else if (T.getAddressSpace() != LangAS::Default) {
7279         // Do not allow other address spaces on automatic variable.
7280         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7281         NewVD->setInvalidDecl();
7282         return;
7283       }
7284     }
7285   }
7286 
7287   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7288       && !NewVD->hasAttr<BlocksAttr>()) {
7289     if (getLangOpts().getGC() != LangOptions::NonGC)
7290       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7291     else {
7292       assert(!getLangOpts().ObjCAutoRefCount);
7293       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7294     }
7295   }
7296 
7297   bool isVM = T->isVariablyModifiedType();
7298   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7299       NewVD->hasAttr<BlocksAttr>())
7300     getCurFunction()->setHasBranchProtectedScope();
7301 
7302   if ((isVM && NewVD->hasLinkage()) ||
7303       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7304     bool SizeIsNegative;
7305     llvm::APSInt Oversized;
7306     TypeSourceInfo *FixedTInfo =
7307       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7308                                                     SizeIsNegative, Oversized);
7309     if (!FixedTInfo && T->isVariableArrayType()) {
7310       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7311       // FIXME: This won't give the correct result for
7312       // int a[10][n];
7313       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7314 
7315       if (NewVD->isFileVarDecl())
7316         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7317         << SizeRange;
7318       else if (NewVD->isStaticLocal())
7319         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7320         << SizeRange;
7321       else
7322         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7323         << SizeRange;
7324       NewVD->setInvalidDecl();
7325       return;
7326     }
7327 
7328     if (!FixedTInfo) {
7329       if (NewVD->isFileVarDecl())
7330         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7331       else
7332         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7333       NewVD->setInvalidDecl();
7334       return;
7335     }
7336 
7337     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7338     NewVD->setType(FixedTInfo->getType());
7339     NewVD->setTypeSourceInfo(FixedTInfo);
7340   }
7341 
7342   if (T->isVoidType()) {
7343     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7344     //                    of objects and functions.
7345     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7346       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7347         << T;
7348       NewVD->setInvalidDecl();
7349       return;
7350     }
7351   }
7352 
7353   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7354     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7355     NewVD->setInvalidDecl();
7356     return;
7357   }
7358 
7359   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7360     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7361     NewVD->setInvalidDecl();
7362     return;
7363   }
7364 
7365   if (NewVD->isConstexpr() && !T->isDependentType() &&
7366       RequireLiteralType(NewVD->getLocation(), T,
7367                          diag::err_constexpr_var_non_literal)) {
7368     NewVD->setInvalidDecl();
7369     return;
7370   }
7371 }
7372 
7373 /// \brief Perform semantic checking on a newly-created variable
7374 /// declaration.
7375 ///
7376 /// This routine performs all of the type-checking required for a
7377 /// variable declaration once it has been built. It is used both to
7378 /// check variables after they have been parsed and their declarators
7379 /// have been translated into a declaration, and to check variables
7380 /// that have been instantiated from a template.
7381 ///
7382 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7383 ///
7384 /// Returns true if the variable declaration is a redeclaration.
7385 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7386   CheckVariableDeclarationType(NewVD);
7387 
7388   // If the decl is already known invalid, don't check it.
7389   if (NewVD->isInvalidDecl())
7390     return false;
7391 
7392   // If we did not find anything by this name, look for a non-visible
7393   // extern "C" declaration with the same name.
7394   if (Previous.empty() &&
7395       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7396     Previous.setShadowed();
7397 
7398   if (!Previous.empty()) {
7399     MergeVarDecl(NewVD, Previous);
7400     return true;
7401   }
7402   return false;
7403 }
7404 
7405 namespace {
7406 struct FindOverriddenMethod {
7407   Sema *S;
7408   CXXMethodDecl *Method;
7409 
7410   /// Member lookup function that determines whether a given C++
7411   /// method overrides a method in a base class, to be used with
7412   /// CXXRecordDecl::lookupInBases().
7413   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7414     RecordDecl *BaseRecord =
7415         Specifier->getType()->getAs<RecordType>()->getDecl();
7416 
7417     DeclarationName Name = Method->getDeclName();
7418 
7419     // FIXME: Do we care about other names here too?
7420     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7421       // We really want to find the base class destructor here.
7422       QualType T = S->Context.getTypeDeclType(BaseRecord);
7423       CanQualType CT = S->Context.getCanonicalType(T);
7424 
7425       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7426     }
7427 
7428     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7429          Path.Decls = Path.Decls.slice(1)) {
7430       NamedDecl *D = Path.Decls.front();
7431       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7432         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7433           return true;
7434       }
7435     }
7436 
7437     return false;
7438   }
7439 };
7440 
7441 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7442 } // end anonymous namespace
7443 
7444 /// \brief Report an error regarding overriding, along with any relevant
7445 /// overriden methods.
7446 ///
7447 /// \param DiagID the primary error to report.
7448 /// \param MD the overriding method.
7449 /// \param OEK which overrides to include as notes.
7450 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7451                             OverrideErrorKind OEK = OEK_All) {
7452   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7453   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7454                                       E = MD->end_overridden_methods();
7455        I != E; ++I) {
7456     // This check (& the OEK parameter) could be replaced by a predicate, but
7457     // without lambdas that would be overkill. This is still nicer than writing
7458     // out the diag loop 3 times.
7459     if ((OEK == OEK_All) ||
7460         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7461         (OEK == OEK_Deleted && (*I)->isDeleted()))
7462       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7463   }
7464 }
7465 
7466 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7467 /// and if so, check that it's a valid override and remember it.
7468 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7469   // Look for methods in base classes that this method might override.
7470   CXXBasePaths Paths;
7471   FindOverriddenMethod FOM;
7472   FOM.Method = MD;
7473   FOM.S = this;
7474   bool hasDeletedOverridenMethods = false;
7475   bool hasNonDeletedOverridenMethods = false;
7476   bool AddedAny = false;
7477   if (DC->lookupInBases(FOM, Paths)) {
7478     for (auto *I : Paths.found_decls()) {
7479       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7480         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7481         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7482             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7483             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7484             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7485           hasDeletedOverridenMethods |= OldMD->isDeleted();
7486           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7487           AddedAny = true;
7488         }
7489       }
7490     }
7491   }
7492 
7493   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7494     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7495   }
7496   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7497     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7498   }
7499 
7500   return AddedAny;
7501 }
7502 
7503 namespace {
7504   // Struct for holding all of the extra arguments needed by
7505   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7506   struct ActOnFDArgs {
7507     Scope *S;
7508     Declarator &D;
7509     MultiTemplateParamsArg TemplateParamLists;
7510     bool AddToScope;
7511   };
7512 } // end anonymous namespace
7513 
7514 namespace {
7515 
7516 // Callback to only accept typo corrections that have a non-zero edit distance.
7517 // Also only accept corrections that have the same parent decl.
7518 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7519  public:
7520   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7521                             CXXRecordDecl *Parent)
7522       : Context(Context), OriginalFD(TypoFD),
7523         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7524 
7525   bool ValidateCandidate(const TypoCorrection &candidate) override {
7526     if (candidate.getEditDistance() == 0)
7527       return false;
7528 
7529     SmallVector<unsigned, 1> MismatchedParams;
7530     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7531                                           CDeclEnd = candidate.end();
7532          CDecl != CDeclEnd; ++CDecl) {
7533       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7534 
7535       if (FD && !FD->hasBody() &&
7536           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7537         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7538           CXXRecordDecl *Parent = MD->getParent();
7539           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7540             return true;
7541         } else if (!ExpectedParent) {
7542           return true;
7543         }
7544       }
7545     }
7546 
7547     return false;
7548   }
7549 
7550  private:
7551   ASTContext &Context;
7552   FunctionDecl *OriginalFD;
7553   CXXRecordDecl *ExpectedParent;
7554 };
7555 
7556 } // end anonymous namespace
7557 
7558 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7559   TypoCorrectedFunctionDefinitions.insert(F);
7560 }
7561 
7562 /// \brief Generate diagnostics for an invalid function redeclaration.
7563 ///
7564 /// This routine handles generating the diagnostic messages for an invalid
7565 /// function redeclaration, including finding possible similar declarations
7566 /// or performing typo correction if there are no previous declarations with
7567 /// the same name.
7568 ///
7569 /// Returns a NamedDecl iff typo correction was performed and substituting in
7570 /// the new declaration name does not cause new errors.
7571 static NamedDecl *DiagnoseInvalidRedeclaration(
7572     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7573     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7574   DeclarationName Name = NewFD->getDeclName();
7575   DeclContext *NewDC = NewFD->getDeclContext();
7576   SmallVector<unsigned, 1> MismatchedParams;
7577   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7578   TypoCorrection Correction;
7579   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7580   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7581                                    : diag::err_member_decl_does_not_match;
7582   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7583                     IsLocalFriend ? Sema::LookupLocalFriendName
7584                                   : Sema::LookupOrdinaryName,
7585                     Sema::ForRedeclaration);
7586 
7587   NewFD->setInvalidDecl();
7588   if (IsLocalFriend)
7589     SemaRef.LookupName(Prev, S);
7590   else
7591     SemaRef.LookupQualifiedName(Prev, NewDC);
7592   assert(!Prev.isAmbiguous() &&
7593          "Cannot have an ambiguity in previous-declaration lookup");
7594   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7595   if (!Prev.empty()) {
7596     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7597          Func != FuncEnd; ++Func) {
7598       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7599       if (FD &&
7600           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7601         // Add 1 to the index so that 0 can mean the mismatch didn't
7602         // involve a parameter
7603         unsigned ParamNum =
7604             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7605         NearMatches.push_back(std::make_pair(FD, ParamNum));
7606       }
7607     }
7608   // If the qualified name lookup yielded nothing, try typo correction
7609   } else if ((Correction = SemaRef.CorrectTypo(
7610                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7611                   &ExtraArgs.D.getCXXScopeSpec(),
7612                   llvm::make_unique<DifferentNameValidatorCCC>(
7613                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7614                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7615     // Set up everything for the call to ActOnFunctionDeclarator
7616     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7617                               ExtraArgs.D.getIdentifierLoc());
7618     Previous.clear();
7619     Previous.setLookupName(Correction.getCorrection());
7620     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7621                                     CDeclEnd = Correction.end();
7622          CDecl != CDeclEnd; ++CDecl) {
7623       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7624       if (FD && !FD->hasBody() &&
7625           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7626         Previous.addDecl(FD);
7627       }
7628     }
7629     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7630 
7631     NamedDecl *Result;
7632     // Retry building the function declaration with the new previous
7633     // declarations, and with errors suppressed.
7634     {
7635       // Trap errors.
7636       Sema::SFINAETrap Trap(SemaRef);
7637 
7638       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7639       // pieces need to verify the typo-corrected C++ declaration and hopefully
7640       // eliminate the need for the parameter pack ExtraArgs.
7641       Result = SemaRef.ActOnFunctionDeclarator(
7642           ExtraArgs.S, ExtraArgs.D,
7643           Correction.getCorrectionDecl()->getDeclContext(),
7644           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7645           ExtraArgs.AddToScope);
7646 
7647       if (Trap.hasErrorOccurred())
7648         Result = nullptr;
7649     }
7650 
7651     if (Result) {
7652       // Determine which correction we picked.
7653       Decl *Canonical = Result->getCanonicalDecl();
7654       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7655            I != E; ++I)
7656         if ((*I)->getCanonicalDecl() == Canonical)
7657           Correction.setCorrectionDecl(*I);
7658 
7659       // Let Sema know about the correction.
7660       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7661       SemaRef.diagnoseTypo(
7662           Correction,
7663           SemaRef.PDiag(IsLocalFriend
7664                           ? diag::err_no_matching_local_friend_suggest
7665                           : diag::err_member_decl_does_not_match_suggest)
7666             << Name << NewDC << IsDefinition);
7667       return Result;
7668     }
7669 
7670     // Pretend the typo correction never occurred
7671     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7672                               ExtraArgs.D.getIdentifierLoc());
7673     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7674     Previous.clear();
7675     Previous.setLookupName(Name);
7676   }
7677 
7678   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7679       << Name << NewDC << IsDefinition << NewFD->getLocation();
7680 
7681   bool NewFDisConst = false;
7682   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7683     NewFDisConst = NewMD->isConst();
7684 
7685   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7686        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7687        NearMatch != NearMatchEnd; ++NearMatch) {
7688     FunctionDecl *FD = NearMatch->first;
7689     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7690     bool FDisConst = MD && MD->isConst();
7691     bool IsMember = MD || !IsLocalFriend;
7692 
7693     // FIXME: These notes are poorly worded for the local friend case.
7694     if (unsigned Idx = NearMatch->second) {
7695       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7696       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7697       if (Loc.isInvalid()) Loc = FD->getLocation();
7698       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7699                                  : diag::note_local_decl_close_param_match)
7700         << Idx << FDParam->getType()
7701         << NewFD->getParamDecl(Idx - 1)->getType();
7702     } else if (FDisConst != NewFDisConst) {
7703       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7704           << NewFDisConst << FD->getSourceRange().getEnd();
7705     } else
7706       SemaRef.Diag(FD->getLocation(),
7707                    IsMember ? diag::note_member_def_close_match
7708                             : diag::note_local_decl_close_match);
7709   }
7710   return nullptr;
7711 }
7712 
7713 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7714   switch (D.getDeclSpec().getStorageClassSpec()) {
7715   default: llvm_unreachable("Unknown storage class!");
7716   case DeclSpec::SCS_auto:
7717   case DeclSpec::SCS_register:
7718   case DeclSpec::SCS_mutable:
7719     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7720                  diag::err_typecheck_sclass_func);
7721     D.getMutableDeclSpec().ClearStorageClassSpecs();
7722     D.setInvalidType();
7723     break;
7724   case DeclSpec::SCS_unspecified: break;
7725   case DeclSpec::SCS_extern:
7726     if (D.getDeclSpec().isExternInLinkageSpec())
7727       return SC_None;
7728     return SC_Extern;
7729   case DeclSpec::SCS_static: {
7730     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7731       // C99 6.7.1p5:
7732       //   The declaration of an identifier for a function that has
7733       //   block scope shall have no explicit storage-class specifier
7734       //   other than extern
7735       // See also (C++ [dcl.stc]p4).
7736       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7737                    diag::err_static_block_func);
7738       break;
7739     } else
7740       return SC_Static;
7741   }
7742   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7743   }
7744 
7745   // No explicit storage class has already been returned
7746   return SC_None;
7747 }
7748 
7749 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7750                                            DeclContext *DC, QualType &R,
7751                                            TypeSourceInfo *TInfo,
7752                                            StorageClass SC,
7753                                            bool &IsVirtualOkay) {
7754   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7755   DeclarationName Name = NameInfo.getName();
7756 
7757   FunctionDecl *NewFD = nullptr;
7758   bool isInline = D.getDeclSpec().isInlineSpecified();
7759 
7760   if (!SemaRef.getLangOpts().CPlusPlus) {
7761     // Determine whether the function was written with a
7762     // prototype. This true when:
7763     //   - there is a prototype in the declarator, or
7764     //   - the type R of the function is some kind of typedef or other non-
7765     //     attributed reference to a type name (which eventually refers to a
7766     //     function type).
7767     bool HasPrototype =
7768       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7769       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7770 
7771     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7772                                  D.getLocStart(), NameInfo, R,
7773                                  TInfo, SC, isInline,
7774                                  HasPrototype, false);
7775     if (D.isInvalidType())
7776       NewFD->setInvalidDecl();
7777 
7778     return NewFD;
7779   }
7780 
7781   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7782   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7783 
7784   // Check that the return type is not an abstract class type.
7785   // For record types, this is done by the AbstractClassUsageDiagnoser once
7786   // the class has been completely parsed.
7787   if (!DC->isRecord() &&
7788       SemaRef.RequireNonAbstractType(
7789           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7790           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7791     D.setInvalidType();
7792 
7793   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7794     // This is a C++ constructor declaration.
7795     assert(DC->isRecord() &&
7796            "Constructors can only be declared in a member context");
7797 
7798     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7799     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7800                                       D.getLocStart(), NameInfo,
7801                                       R, TInfo, isExplicit, isInline,
7802                                       /*isImplicitlyDeclared=*/false,
7803                                       isConstexpr);
7804 
7805   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7806     // This is a C++ destructor declaration.
7807     if (DC->isRecord()) {
7808       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7809       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7810       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7811                                         SemaRef.Context, Record,
7812                                         D.getLocStart(),
7813                                         NameInfo, R, TInfo, isInline,
7814                                         /*isImplicitlyDeclared=*/false);
7815 
7816       // If the class is complete, then we now create the implicit exception
7817       // specification. If the class is incomplete or dependent, we can't do
7818       // it yet.
7819       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7820           Record->getDefinition() && !Record->isBeingDefined() &&
7821           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7822         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7823       }
7824 
7825       IsVirtualOkay = true;
7826       return NewDD;
7827 
7828     } else {
7829       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7830       D.setInvalidType();
7831 
7832       // Create a FunctionDecl to satisfy the function definition parsing
7833       // code path.
7834       return FunctionDecl::Create(SemaRef.Context, DC,
7835                                   D.getLocStart(),
7836                                   D.getIdentifierLoc(), Name, R, TInfo,
7837                                   SC, isInline,
7838                                   /*hasPrototype=*/true, isConstexpr);
7839     }
7840 
7841   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7842     if (!DC->isRecord()) {
7843       SemaRef.Diag(D.getIdentifierLoc(),
7844            diag::err_conv_function_not_member);
7845       return nullptr;
7846     }
7847 
7848     SemaRef.CheckConversionDeclarator(D, R, SC);
7849     IsVirtualOkay = true;
7850     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7851                                      D.getLocStart(), NameInfo,
7852                                      R, TInfo, isInline, isExplicit,
7853                                      isConstexpr, SourceLocation());
7854 
7855   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7856     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7857 
7858     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7859                                          isExplicit, NameInfo, R, TInfo,
7860                                          D.getLocEnd());
7861   } else if (DC->isRecord()) {
7862     // If the name of the function is the same as the name of the record,
7863     // then this must be an invalid constructor that has a return type.
7864     // (The parser checks for a return type and makes the declarator a
7865     // constructor if it has no return type).
7866     if (Name.getAsIdentifierInfo() &&
7867         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7868       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7869         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7870         << SourceRange(D.getIdentifierLoc());
7871       return nullptr;
7872     }
7873 
7874     // This is a C++ method declaration.
7875     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7876                                                cast<CXXRecordDecl>(DC),
7877                                                D.getLocStart(), NameInfo, R,
7878                                                TInfo, SC, isInline,
7879                                                isConstexpr, SourceLocation());
7880     IsVirtualOkay = !Ret->isStatic();
7881     return Ret;
7882   } else {
7883     bool isFriend =
7884         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7885     if (!isFriend && SemaRef.CurContext->isRecord())
7886       return nullptr;
7887 
7888     // Determine whether the function was written with a
7889     // prototype. This true when:
7890     //   - we're in C++ (where every function has a prototype),
7891     return FunctionDecl::Create(SemaRef.Context, DC,
7892                                 D.getLocStart(),
7893                                 NameInfo, R, TInfo, SC, isInline,
7894                                 true/*HasPrototype*/, isConstexpr);
7895   }
7896 }
7897 
7898 enum OpenCLParamType {
7899   ValidKernelParam,
7900   PtrPtrKernelParam,
7901   PtrKernelParam,
7902   InvalidAddrSpacePtrKernelParam,
7903   InvalidKernelParam,
7904   RecordKernelParam
7905 };
7906 
7907 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7908   if (PT->isPointerType()) {
7909     QualType PointeeType = PT->getPointeeType();
7910     if (PointeeType->isPointerType())
7911       return PtrPtrKernelParam;
7912     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7913         PointeeType.getAddressSpace() == 0)
7914       return InvalidAddrSpacePtrKernelParam;
7915     return PtrKernelParam;
7916   }
7917 
7918   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7919   // be used as builtin types.
7920 
7921   if (PT->isImageType())
7922     return PtrKernelParam;
7923 
7924   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7925     return InvalidKernelParam;
7926 
7927   // OpenCL extension spec v1.2 s9.5:
7928   // This extension adds support for half scalar and vector types as built-in
7929   // types that can be used for arithmetic operations, conversions etc.
7930   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7931     return InvalidKernelParam;
7932 
7933   if (PT->isRecordType())
7934     return RecordKernelParam;
7935 
7936   return ValidKernelParam;
7937 }
7938 
7939 static void checkIsValidOpenCLKernelParameter(
7940   Sema &S,
7941   Declarator &D,
7942   ParmVarDecl *Param,
7943   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7944   QualType PT = Param->getType();
7945 
7946   // Cache the valid types we encounter to avoid rechecking structs that are
7947   // used again
7948   if (ValidTypes.count(PT.getTypePtr()))
7949     return;
7950 
7951   switch (getOpenCLKernelParameterType(S, PT)) {
7952   case PtrPtrKernelParam:
7953     // OpenCL v1.2 s6.9.a:
7954     // A kernel function argument cannot be declared as a
7955     // pointer to a pointer type.
7956     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7957     D.setInvalidType();
7958     return;
7959 
7960   case InvalidAddrSpacePtrKernelParam:
7961     // OpenCL v1.0 s6.5:
7962     // __kernel function arguments declared to be a pointer of a type can point
7963     // to one of the following address spaces only : __global, __local or
7964     // __constant.
7965     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7966     D.setInvalidType();
7967     return;
7968 
7969     // OpenCL v1.2 s6.9.k:
7970     // Arguments to kernel functions in a program cannot be declared with the
7971     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7972     // uintptr_t or a struct and/or union that contain fields declared to be
7973     // one of these built-in scalar types.
7974 
7975   case InvalidKernelParam:
7976     // OpenCL v1.2 s6.8 n:
7977     // A kernel function argument cannot be declared
7978     // of event_t type.
7979     // Do not diagnose half type since it is diagnosed as invalid argument
7980     // type for any function elsewhere.
7981     if (!PT->isHalfType())
7982       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7983     D.setInvalidType();
7984     return;
7985 
7986   case PtrKernelParam:
7987   case ValidKernelParam:
7988     ValidTypes.insert(PT.getTypePtr());
7989     return;
7990 
7991   case RecordKernelParam:
7992     break;
7993   }
7994 
7995   // Track nested structs we will inspect
7996   SmallVector<const Decl *, 4> VisitStack;
7997 
7998   // Track where we are in the nested structs. Items will migrate from
7999   // VisitStack to HistoryStack as we do the DFS for bad field.
8000   SmallVector<const FieldDecl *, 4> HistoryStack;
8001   HistoryStack.push_back(nullptr);
8002 
8003   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8004   VisitStack.push_back(PD);
8005 
8006   assert(VisitStack.back() && "First decl null?");
8007 
8008   do {
8009     const Decl *Next = VisitStack.pop_back_val();
8010     if (!Next) {
8011       assert(!HistoryStack.empty());
8012       // Found a marker, we have gone up a level
8013       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8014         ValidTypes.insert(Hist->getType().getTypePtr());
8015 
8016       continue;
8017     }
8018 
8019     // Adds everything except the original parameter declaration (which is not a
8020     // field itself) to the history stack.
8021     const RecordDecl *RD;
8022     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8023       HistoryStack.push_back(Field);
8024       RD = Field->getType()->castAs<RecordType>()->getDecl();
8025     } else {
8026       RD = cast<RecordDecl>(Next);
8027     }
8028 
8029     // Add a null marker so we know when we've gone back up a level
8030     VisitStack.push_back(nullptr);
8031 
8032     for (const auto *FD : RD->fields()) {
8033       QualType QT = FD->getType();
8034 
8035       if (ValidTypes.count(QT.getTypePtr()))
8036         continue;
8037 
8038       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8039       if (ParamType == ValidKernelParam)
8040         continue;
8041 
8042       if (ParamType == RecordKernelParam) {
8043         VisitStack.push_back(FD);
8044         continue;
8045       }
8046 
8047       // OpenCL v1.2 s6.9.p:
8048       // Arguments to kernel functions that are declared to be a struct or union
8049       // do not allow OpenCL objects to be passed as elements of the struct or
8050       // union.
8051       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8052           ParamType == InvalidAddrSpacePtrKernelParam) {
8053         S.Diag(Param->getLocation(),
8054                diag::err_record_with_pointers_kernel_param)
8055           << PT->isUnionType()
8056           << PT;
8057       } else {
8058         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8059       }
8060 
8061       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8062         << PD->getDeclName();
8063 
8064       // We have an error, now let's go back up through history and show where
8065       // the offending field came from
8066       for (ArrayRef<const FieldDecl *>::const_iterator
8067                I = HistoryStack.begin() + 1,
8068                E = HistoryStack.end();
8069            I != E; ++I) {
8070         const FieldDecl *OuterField = *I;
8071         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8072           << OuterField->getType();
8073       }
8074 
8075       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8076         << QT->isPointerType()
8077         << QT;
8078       D.setInvalidType();
8079       return;
8080     }
8081   } while (!VisitStack.empty());
8082 }
8083 
8084 /// Find the DeclContext in which a tag is implicitly declared if we see an
8085 /// elaborated type specifier in the specified context, and lookup finds
8086 /// nothing.
8087 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8088   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8089     DC = DC->getParent();
8090   return DC;
8091 }
8092 
8093 /// Find the Scope in which a tag is implicitly declared if we see an
8094 /// elaborated type specifier in the specified context, and lookup finds
8095 /// nothing.
8096 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8097   while (S->isClassScope() ||
8098          (LangOpts.CPlusPlus &&
8099           S->isFunctionPrototypeScope()) ||
8100          ((S->getFlags() & Scope::DeclScope) == 0) ||
8101          (S->getEntity() && S->getEntity()->isTransparentContext()))
8102     S = S->getParent();
8103   return S;
8104 }
8105 
8106 NamedDecl*
8107 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8108                               TypeSourceInfo *TInfo, LookupResult &Previous,
8109                               MultiTemplateParamsArg TemplateParamLists,
8110                               bool &AddToScope) {
8111   QualType R = TInfo->getType();
8112 
8113   assert(R.getTypePtr()->isFunctionType());
8114 
8115   // TODO: consider using NameInfo for diagnostic.
8116   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8117   DeclarationName Name = NameInfo.getName();
8118   StorageClass SC = getFunctionStorageClass(*this, D);
8119 
8120   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8121     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8122          diag::err_invalid_thread)
8123       << DeclSpec::getSpecifierName(TSCS);
8124 
8125   if (D.isFirstDeclarationOfMember())
8126     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8127                            D.getIdentifierLoc());
8128 
8129   bool isFriend = false;
8130   FunctionTemplateDecl *FunctionTemplate = nullptr;
8131   bool isMemberSpecialization = false;
8132   bool isFunctionTemplateSpecialization = false;
8133 
8134   bool isDependentClassScopeExplicitSpecialization = false;
8135   bool HasExplicitTemplateArgs = false;
8136   TemplateArgumentListInfo TemplateArgs;
8137 
8138   bool isVirtualOkay = false;
8139 
8140   DeclContext *OriginalDC = DC;
8141   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8142 
8143   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8144                                               isVirtualOkay);
8145   if (!NewFD) return nullptr;
8146 
8147   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8148     NewFD->setTopLevelDeclInObjCContainer();
8149 
8150   // Set the lexical context. If this is a function-scope declaration, or has a
8151   // C++ scope specifier, or is the object of a friend declaration, the lexical
8152   // context will be different from the semantic context.
8153   NewFD->setLexicalDeclContext(CurContext);
8154 
8155   if (IsLocalExternDecl)
8156     NewFD->setLocalExternDecl();
8157 
8158   if (getLangOpts().CPlusPlus) {
8159     bool isInline = D.getDeclSpec().isInlineSpecified();
8160     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8161     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8162     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8163     bool isConcept = D.getDeclSpec().isConceptSpecified();
8164     isFriend = D.getDeclSpec().isFriendSpecified();
8165     if (isFriend && !isInline && D.isFunctionDefinition()) {
8166       // C++ [class.friend]p5
8167       //   A function can be defined in a friend declaration of a
8168       //   class . . . . Such a function is implicitly inline.
8169       NewFD->setImplicitlyInline();
8170     }
8171 
8172     // If this is a method defined in an __interface, and is not a constructor
8173     // or an overloaded operator, then set the pure flag (isVirtual will already
8174     // return true).
8175     if (const CXXRecordDecl *Parent =
8176           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8177       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8178         NewFD->setPure(true);
8179 
8180       // C++ [class.union]p2
8181       //   A union can have member functions, but not virtual functions.
8182       if (isVirtual && Parent->isUnion())
8183         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8184     }
8185 
8186     SetNestedNameSpecifier(NewFD, D);
8187     isMemberSpecialization = false;
8188     isFunctionTemplateSpecialization = false;
8189     if (D.isInvalidType())
8190       NewFD->setInvalidDecl();
8191 
8192     // Match up the template parameter lists with the scope specifier, then
8193     // determine whether we have a template or a template specialization.
8194     bool Invalid = false;
8195     if (TemplateParameterList *TemplateParams =
8196             MatchTemplateParametersToScopeSpecifier(
8197                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8198                 D.getCXXScopeSpec(),
8199                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8200                     ? D.getName().TemplateId
8201                     : nullptr,
8202                 TemplateParamLists, isFriend, isMemberSpecialization,
8203                 Invalid)) {
8204       if (TemplateParams->size() > 0) {
8205         // This is a function template
8206 
8207         // Check that we can declare a template here.
8208         if (CheckTemplateDeclScope(S, TemplateParams))
8209           NewFD->setInvalidDecl();
8210 
8211         // A destructor cannot be a template.
8212         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8213           Diag(NewFD->getLocation(), diag::err_destructor_template);
8214           NewFD->setInvalidDecl();
8215         }
8216 
8217         // If we're adding a template to a dependent context, we may need to
8218         // rebuilding some of the types used within the template parameter list,
8219         // now that we know what the current instantiation is.
8220         if (DC->isDependentContext()) {
8221           ContextRAII SavedContext(*this, DC);
8222           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8223             Invalid = true;
8224         }
8225 
8226         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8227                                                         NewFD->getLocation(),
8228                                                         Name, TemplateParams,
8229                                                         NewFD);
8230         FunctionTemplate->setLexicalDeclContext(CurContext);
8231         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8232 
8233         // For source fidelity, store the other template param lists.
8234         if (TemplateParamLists.size() > 1) {
8235           NewFD->setTemplateParameterListsInfo(Context,
8236                                                TemplateParamLists.drop_back(1));
8237         }
8238       } else {
8239         // This is a function template specialization.
8240         isFunctionTemplateSpecialization = true;
8241         // For source fidelity, store all the template param lists.
8242         if (TemplateParamLists.size() > 0)
8243           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8244 
8245         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8246         if (isFriend) {
8247           // We want to remove the "template<>", found here.
8248           SourceRange RemoveRange = TemplateParams->getSourceRange();
8249 
8250           // If we remove the template<> and the name is not a
8251           // template-id, we're actually silently creating a problem:
8252           // the friend declaration will refer to an untemplated decl,
8253           // and clearly the user wants a template specialization.  So
8254           // we need to insert '<>' after the name.
8255           SourceLocation InsertLoc;
8256           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8257             InsertLoc = D.getName().getSourceRange().getEnd();
8258             InsertLoc = getLocForEndOfToken(InsertLoc);
8259           }
8260 
8261           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8262             << Name << RemoveRange
8263             << FixItHint::CreateRemoval(RemoveRange)
8264             << FixItHint::CreateInsertion(InsertLoc, "<>");
8265         }
8266       }
8267     }
8268     else {
8269       // All template param lists were matched against the scope specifier:
8270       // this is NOT (an explicit specialization of) a template.
8271       if (TemplateParamLists.size() > 0)
8272         // For source fidelity, store all the template param lists.
8273         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8274     }
8275 
8276     if (Invalid) {
8277       NewFD->setInvalidDecl();
8278       if (FunctionTemplate)
8279         FunctionTemplate->setInvalidDecl();
8280     }
8281 
8282     // C++ [dcl.fct.spec]p5:
8283     //   The virtual specifier shall only be used in declarations of
8284     //   nonstatic class member functions that appear within a
8285     //   member-specification of a class declaration; see 10.3.
8286     //
8287     if (isVirtual && !NewFD->isInvalidDecl()) {
8288       if (!isVirtualOkay) {
8289         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8290              diag::err_virtual_non_function);
8291       } else if (!CurContext->isRecord()) {
8292         // 'virtual' was specified outside of the class.
8293         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8294              diag::err_virtual_out_of_class)
8295           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8296       } else if (NewFD->getDescribedFunctionTemplate()) {
8297         // C++ [temp.mem]p3:
8298         //  A member function template shall not be virtual.
8299         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8300              diag::err_virtual_member_function_template)
8301           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8302       } else {
8303         // Okay: Add virtual to the method.
8304         NewFD->setVirtualAsWritten(true);
8305       }
8306 
8307       if (getLangOpts().CPlusPlus14 &&
8308           NewFD->getReturnType()->isUndeducedType())
8309         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8310     }
8311 
8312     if (getLangOpts().CPlusPlus14 &&
8313         (NewFD->isDependentContext() ||
8314          (isFriend && CurContext->isDependentContext())) &&
8315         NewFD->getReturnType()->isUndeducedType()) {
8316       // If the function template is referenced directly (for instance, as a
8317       // member of the current instantiation), pretend it has a dependent type.
8318       // This is not really justified by the standard, but is the only sane
8319       // thing to do.
8320       // FIXME: For a friend function, we have not marked the function as being
8321       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8322       const FunctionProtoType *FPT =
8323           NewFD->getType()->castAs<FunctionProtoType>();
8324       QualType Result =
8325           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8326       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8327                                              FPT->getExtProtoInfo()));
8328     }
8329 
8330     // C++ [dcl.fct.spec]p3:
8331     //  The inline specifier shall not appear on a block scope function
8332     //  declaration.
8333     if (isInline && !NewFD->isInvalidDecl()) {
8334       if (CurContext->isFunctionOrMethod()) {
8335         // 'inline' is not allowed on block scope function declaration.
8336         Diag(D.getDeclSpec().getInlineSpecLoc(),
8337              diag::err_inline_declaration_block_scope) << Name
8338           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8339       }
8340     }
8341 
8342     // C++ [dcl.fct.spec]p6:
8343     //  The explicit specifier shall be used only in the declaration of a
8344     //  constructor or conversion function within its class definition;
8345     //  see 12.3.1 and 12.3.2.
8346     if (isExplicit && !NewFD->isInvalidDecl() &&
8347         !isa<CXXDeductionGuideDecl>(NewFD)) {
8348       if (!CurContext->isRecord()) {
8349         // 'explicit' was specified outside of the class.
8350         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8351              diag::err_explicit_out_of_class)
8352           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8353       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8354                  !isa<CXXConversionDecl>(NewFD)) {
8355         // 'explicit' was specified on a function that wasn't a constructor
8356         // or conversion function.
8357         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8358              diag::err_explicit_non_ctor_or_conv_function)
8359           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8360       }
8361     }
8362 
8363     if (isConstexpr) {
8364       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8365       // are implicitly inline.
8366       NewFD->setImplicitlyInline();
8367 
8368       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8369       // be either constructors or to return a literal type. Therefore,
8370       // destructors cannot be declared constexpr.
8371       if (isa<CXXDestructorDecl>(NewFD))
8372         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8373     }
8374 
8375     if (isConcept) {
8376       // This is a function concept.
8377       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8378         FTD->setConcept();
8379 
8380       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8381       // applied only to the definition of a function template [...]
8382       if (!D.isFunctionDefinition()) {
8383         Diag(D.getDeclSpec().getConceptSpecLoc(),
8384              diag::err_function_concept_not_defined);
8385         NewFD->setInvalidDecl();
8386       }
8387 
8388       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8389       // have no exception-specification and is treated as if it were specified
8390       // with noexcept(true) (15.4). [...]
8391       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8392         if (FPT->hasExceptionSpec()) {
8393           SourceRange Range;
8394           if (D.isFunctionDeclarator())
8395             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8396           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8397               << FixItHint::CreateRemoval(Range);
8398           NewFD->setInvalidDecl();
8399         } else {
8400           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8401         }
8402 
8403         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8404         // following restrictions:
8405         // - The declared return type shall have the type bool.
8406         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8407           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8408           NewFD->setInvalidDecl();
8409         }
8410 
8411         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8412         // following restrictions:
8413         // - The declaration's parameter list shall be equivalent to an empty
8414         //   parameter list.
8415         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8416           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8417       }
8418 
8419       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8420       // implicity defined to be a constexpr declaration (implicitly inline)
8421       NewFD->setImplicitlyInline();
8422 
8423       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8424       // be declared with the thread_local, inline, friend, or constexpr
8425       // specifiers, [...]
8426       if (isInline) {
8427         Diag(D.getDeclSpec().getInlineSpecLoc(),
8428              diag::err_concept_decl_invalid_specifiers)
8429             << 1 << 1;
8430         NewFD->setInvalidDecl(true);
8431       }
8432 
8433       if (isFriend) {
8434         Diag(D.getDeclSpec().getFriendSpecLoc(),
8435              diag::err_concept_decl_invalid_specifiers)
8436             << 1 << 2;
8437         NewFD->setInvalidDecl(true);
8438       }
8439 
8440       if (isConstexpr) {
8441         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8442              diag::err_concept_decl_invalid_specifiers)
8443             << 1 << 3;
8444         NewFD->setInvalidDecl(true);
8445       }
8446 
8447       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8448       // applied only to the definition of a function template or variable
8449       // template, declared in namespace scope.
8450       if (isFunctionTemplateSpecialization) {
8451         Diag(D.getDeclSpec().getConceptSpecLoc(),
8452              diag::err_concept_specified_specialization) << 1;
8453         NewFD->setInvalidDecl(true);
8454         return NewFD;
8455       }
8456     }
8457 
8458     // If __module_private__ was specified, mark the function accordingly.
8459     if (D.getDeclSpec().isModulePrivateSpecified()) {
8460       if (isFunctionTemplateSpecialization) {
8461         SourceLocation ModulePrivateLoc
8462           = D.getDeclSpec().getModulePrivateSpecLoc();
8463         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8464           << 0
8465           << FixItHint::CreateRemoval(ModulePrivateLoc);
8466       } else {
8467         NewFD->setModulePrivate();
8468         if (FunctionTemplate)
8469           FunctionTemplate->setModulePrivate();
8470       }
8471     }
8472 
8473     if (isFriend) {
8474       if (FunctionTemplate) {
8475         FunctionTemplate->setObjectOfFriendDecl();
8476         FunctionTemplate->setAccess(AS_public);
8477       }
8478       NewFD->setObjectOfFriendDecl();
8479       NewFD->setAccess(AS_public);
8480     }
8481 
8482     // If a function is defined as defaulted or deleted, mark it as such now.
8483     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8484     // definition kind to FDK_Definition.
8485     switch (D.getFunctionDefinitionKind()) {
8486       case FDK_Declaration:
8487       case FDK_Definition:
8488         break;
8489 
8490       case FDK_Defaulted:
8491         NewFD->setDefaulted();
8492         break;
8493 
8494       case FDK_Deleted:
8495         NewFD->setDeletedAsWritten();
8496         break;
8497     }
8498 
8499     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8500         D.isFunctionDefinition()) {
8501       // C++ [class.mfct]p2:
8502       //   A member function may be defined (8.4) in its class definition, in
8503       //   which case it is an inline member function (7.1.2)
8504       NewFD->setImplicitlyInline();
8505     }
8506 
8507     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8508         !CurContext->isRecord()) {
8509       // C++ [class.static]p1:
8510       //   A data or function member of a class may be declared static
8511       //   in a class definition, in which case it is a static member of
8512       //   the class.
8513 
8514       // Complain about the 'static' specifier if it's on an out-of-line
8515       // member function definition.
8516       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8517            diag::err_static_out_of_line)
8518         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8519     }
8520 
8521     // C++11 [except.spec]p15:
8522     //   A deallocation function with no exception-specification is treated
8523     //   as if it were specified with noexcept(true).
8524     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8525     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8526          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8527         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8528       NewFD->setType(Context.getFunctionType(
8529           FPT->getReturnType(), FPT->getParamTypes(),
8530           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8531   }
8532 
8533   // Filter out previous declarations that don't match the scope.
8534   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8535                        D.getCXXScopeSpec().isNotEmpty() ||
8536                        isMemberSpecialization ||
8537                        isFunctionTemplateSpecialization);
8538 
8539   // Handle GNU asm-label extension (encoded as an attribute).
8540   if (Expr *E = (Expr*) D.getAsmLabel()) {
8541     // The parser guarantees this is a string.
8542     StringLiteral *SE = cast<StringLiteral>(E);
8543     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8544                                                 SE->getString(), 0));
8545   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8546     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8547       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8548     if (I != ExtnameUndeclaredIdentifiers.end()) {
8549       if (isDeclExternC(NewFD)) {
8550         NewFD->addAttr(I->second);
8551         ExtnameUndeclaredIdentifiers.erase(I);
8552       } else
8553         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8554             << /*Variable*/0 << NewFD;
8555     }
8556   }
8557 
8558   // Copy the parameter declarations from the declarator D to the function
8559   // declaration NewFD, if they are available.  First scavenge them into Params.
8560   SmallVector<ParmVarDecl*, 16> Params;
8561   unsigned FTIIdx;
8562   if (D.isFunctionDeclarator(FTIIdx)) {
8563     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8564 
8565     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8566     // function that takes no arguments, not a function that takes a
8567     // single void argument.
8568     // We let through "const void" here because Sema::GetTypeForDeclarator
8569     // already checks for that case.
8570     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8571       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8572         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8573         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8574         Param->setDeclContext(NewFD);
8575         Params.push_back(Param);
8576 
8577         if (Param->isInvalidDecl())
8578           NewFD->setInvalidDecl();
8579       }
8580     }
8581 
8582     if (!getLangOpts().CPlusPlus) {
8583       // In C, find all the tag declarations from the prototype and move them
8584       // into the function DeclContext. Remove them from the surrounding tag
8585       // injection context of the function, which is typically but not always
8586       // the TU.
8587       DeclContext *PrototypeTagContext =
8588           getTagInjectionContext(NewFD->getLexicalDeclContext());
8589       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8590         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8591 
8592         // We don't want to reparent enumerators. Look at their parent enum
8593         // instead.
8594         if (!TD) {
8595           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8596             TD = cast<EnumDecl>(ECD->getDeclContext());
8597         }
8598         if (!TD)
8599           continue;
8600         DeclContext *TagDC = TD->getLexicalDeclContext();
8601         if (!TagDC->containsDecl(TD))
8602           continue;
8603         TagDC->removeDecl(TD);
8604         TD->setDeclContext(NewFD);
8605         NewFD->addDecl(TD);
8606 
8607         // Preserve the lexical DeclContext if it is not the surrounding tag
8608         // injection context of the FD. In this example, the semantic context of
8609         // E will be f and the lexical context will be S, while both the
8610         // semantic and lexical contexts of S will be f:
8611         //   void f(struct S { enum E { a } f; } s);
8612         if (TagDC != PrototypeTagContext)
8613           TD->setLexicalDeclContext(TagDC);
8614       }
8615     }
8616   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8617     // When we're declaring a function with a typedef, typeof, etc as in the
8618     // following example, we'll need to synthesize (unnamed)
8619     // parameters for use in the declaration.
8620     //
8621     // @code
8622     // typedef void fn(int);
8623     // fn f;
8624     // @endcode
8625 
8626     // Synthesize a parameter for each argument type.
8627     for (const auto &AI : FT->param_types()) {
8628       ParmVarDecl *Param =
8629           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8630       Param->setScopeInfo(0, Params.size());
8631       Params.push_back(Param);
8632     }
8633   } else {
8634     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8635            "Should not need args for typedef of non-prototype fn");
8636   }
8637 
8638   // Finally, we know we have the right number of parameters, install them.
8639   NewFD->setParams(Params);
8640 
8641   if (D.getDeclSpec().isNoreturnSpecified())
8642     NewFD->addAttr(
8643         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8644                                        Context, 0));
8645 
8646   // Functions returning a variably modified type violate C99 6.7.5.2p2
8647   // because all functions have linkage.
8648   if (!NewFD->isInvalidDecl() &&
8649       NewFD->getReturnType()->isVariablyModifiedType()) {
8650     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8651     NewFD->setInvalidDecl();
8652   }
8653 
8654   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8655   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8656       !NewFD->hasAttr<SectionAttr>()) {
8657     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8658                                                  PragmaClangTextSection.SectionName,
8659                                                  PragmaClangTextSection.PragmaLocation));
8660   }
8661 
8662   // Apply an implicit SectionAttr if #pragma code_seg is active.
8663   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8664       !NewFD->hasAttr<SectionAttr>()) {
8665     NewFD->addAttr(
8666         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8667                                     CodeSegStack.CurrentValue->getString(),
8668                                     CodeSegStack.CurrentPragmaLocation));
8669     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8670                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8671                          ASTContext::PSF_Read,
8672                      NewFD))
8673       NewFD->dropAttr<SectionAttr>();
8674   }
8675 
8676   // Handle attributes.
8677   ProcessDeclAttributes(S, NewFD, D);
8678 
8679   if (getLangOpts().OpenCL) {
8680     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8681     // type declaration will generate a compilation error.
8682     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8683     if (AddressSpace == LangAS::opencl_local ||
8684         AddressSpace == LangAS::opencl_global ||
8685         AddressSpace == LangAS::opencl_constant) {
8686       Diag(NewFD->getLocation(),
8687            diag::err_opencl_return_value_with_address_space);
8688       NewFD->setInvalidDecl();
8689     }
8690   }
8691 
8692   if (!getLangOpts().CPlusPlus) {
8693     // Perform semantic checking on the function declaration.
8694     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8695       CheckMain(NewFD, D.getDeclSpec());
8696 
8697     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8698       CheckMSVCRTEntryPoint(NewFD);
8699 
8700     if (!NewFD->isInvalidDecl())
8701       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8702                                                   isMemberSpecialization));
8703     else if (!Previous.empty())
8704       // Recover gracefully from an invalid redeclaration.
8705       D.setRedeclaration(true);
8706     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8707             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8708            "previous declaration set still overloaded");
8709 
8710     // Diagnose no-prototype function declarations with calling conventions that
8711     // don't support variadic calls. Only do this in C and do it after merging
8712     // possibly prototyped redeclarations.
8713     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8714     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8715       CallingConv CC = FT->getExtInfo().getCC();
8716       if (!supportsVariadicCall(CC)) {
8717         // Windows system headers sometimes accidentally use stdcall without
8718         // (void) parameters, so we relax this to a warning.
8719         int DiagID =
8720             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8721         Diag(NewFD->getLocation(), DiagID)
8722             << FunctionType::getNameForCallConv(CC);
8723       }
8724     }
8725   } else {
8726     // C++11 [replacement.functions]p3:
8727     //  The program's definitions shall not be specified as inline.
8728     //
8729     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8730     //
8731     // Suppress the diagnostic if the function is __attribute__((used)), since
8732     // that forces an external definition to be emitted.
8733     if (D.getDeclSpec().isInlineSpecified() &&
8734         NewFD->isReplaceableGlobalAllocationFunction() &&
8735         !NewFD->hasAttr<UsedAttr>())
8736       Diag(D.getDeclSpec().getInlineSpecLoc(),
8737            diag::ext_operator_new_delete_declared_inline)
8738         << NewFD->getDeclName();
8739 
8740     // If the declarator is a template-id, translate the parser's template
8741     // argument list into our AST format.
8742     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8743       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8744       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8745       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8746       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8747                                          TemplateId->NumArgs);
8748       translateTemplateArguments(TemplateArgsPtr,
8749                                  TemplateArgs);
8750 
8751       HasExplicitTemplateArgs = true;
8752 
8753       if (NewFD->isInvalidDecl()) {
8754         HasExplicitTemplateArgs = false;
8755       } else if (FunctionTemplate) {
8756         // Function template with explicit template arguments.
8757         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8758           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8759 
8760         HasExplicitTemplateArgs = false;
8761       } else {
8762         assert((isFunctionTemplateSpecialization ||
8763                 D.getDeclSpec().isFriendSpecified()) &&
8764                "should have a 'template<>' for this decl");
8765         // "friend void foo<>(int);" is an implicit specialization decl.
8766         isFunctionTemplateSpecialization = true;
8767       }
8768     } else if (isFriend && isFunctionTemplateSpecialization) {
8769       // This combination is only possible in a recovery case;  the user
8770       // wrote something like:
8771       //   template <> friend void foo(int);
8772       // which we're recovering from as if the user had written:
8773       //   friend void foo<>(int);
8774       // Go ahead and fake up a template id.
8775       HasExplicitTemplateArgs = true;
8776       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8777       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8778     }
8779 
8780     // We do not add HD attributes to specializations here because
8781     // they may have different constexpr-ness compared to their
8782     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8783     // may end up with different effective targets. Instead, a
8784     // specialization inherits its target attributes from its template
8785     // in the CheckFunctionTemplateSpecialization() call below.
8786     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8787       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8788 
8789     // If it's a friend (and only if it's a friend), it's possible
8790     // that either the specialized function type or the specialized
8791     // template is dependent, and therefore matching will fail.  In
8792     // this case, don't check the specialization yet.
8793     bool InstantiationDependent = false;
8794     if (isFunctionTemplateSpecialization && isFriend &&
8795         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8796          TemplateSpecializationType::anyDependentTemplateArguments(
8797             TemplateArgs,
8798             InstantiationDependent))) {
8799       assert(HasExplicitTemplateArgs &&
8800              "friend function specialization without template args");
8801       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8802                                                        Previous))
8803         NewFD->setInvalidDecl();
8804     } else if (isFunctionTemplateSpecialization) {
8805       if (CurContext->isDependentContext() && CurContext->isRecord()
8806           && !isFriend) {
8807         isDependentClassScopeExplicitSpecialization = true;
8808         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8809           diag::ext_function_specialization_in_class :
8810           diag::err_function_specialization_in_class)
8811           << NewFD->getDeclName();
8812       } else if (CheckFunctionTemplateSpecialization(NewFD,
8813                                   (HasExplicitTemplateArgs ? &TemplateArgs
8814                                                            : nullptr),
8815                                                      Previous))
8816         NewFD->setInvalidDecl();
8817 
8818       // C++ [dcl.stc]p1:
8819       //   A storage-class-specifier shall not be specified in an explicit
8820       //   specialization (14.7.3)
8821       FunctionTemplateSpecializationInfo *Info =
8822           NewFD->getTemplateSpecializationInfo();
8823       if (Info && SC != SC_None) {
8824         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8825           Diag(NewFD->getLocation(),
8826                diag::err_explicit_specialization_inconsistent_storage_class)
8827             << SC
8828             << FixItHint::CreateRemoval(
8829                                       D.getDeclSpec().getStorageClassSpecLoc());
8830 
8831         else
8832           Diag(NewFD->getLocation(),
8833                diag::ext_explicit_specialization_storage_class)
8834             << FixItHint::CreateRemoval(
8835                                       D.getDeclSpec().getStorageClassSpecLoc());
8836       }
8837     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8838       if (CheckMemberSpecialization(NewFD, Previous))
8839           NewFD->setInvalidDecl();
8840     }
8841 
8842     // Perform semantic checking on the function declaration.
8843     if (!isDependentClassScopeExplicitSpecialization) {
8844       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8845         CheckMain(NewFD, D.getDeclSpec());
8846 
8847       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8848         CheckMSVCRTEntryPoint(NewFD);
8849 
8850       if (!NewFD->isInvalidDecl())
8851         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8852                                                     isMemberSpecialization));
8853       else if (!Previous.empty())
8854         // Recover gracefully from an invalid redeclaration.
8855         D.setRedeclaration(true);
8856     }
8857 
8858     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8859             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8860            "previous declaration set still overloaded");
8861 
8862     NamedDecl *PrincipalDecl = (FunctionTemplate
8863                                 ? cast<NamedDecl>(FunctionTemplate)
8864                                 : NewFD);
8865 
8866     if (isFriend && NewFD->getPreviousDecl()) {
8867       AccessSpecifier Access = AS_public;
8868       if (!NewFD->isInvalidDecl())
8869         Access = NewFD->getPreviousDecl()->getAccess();
8870 
8871       NewFD->setAccess(Access);
8872       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8873     }
8874 
8875     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8876         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8877       PrincipalDecl->setNonMemberOperator();
8878 
8879     // If we have a function template, check the template parameter
8880     // list. This will check and merge default template arguments.
8881     if (FunctionTemplate) {
8882       FunctionTemplateDecl *PrevTemplate =
8883                                      FunctionTemplate->getPreviousDecl();
8884       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8885                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8886                                     : nullptr,
8887                             D.getDeclSpec().isFriendSpecified()
8888                               ? (D.isFunctionDefinition()
8889                                    ? TPC_FriendFunctionTemplateDefinition
8890                                    : TPC_FriendFunctionTemplate)
8891                               : (D.getCXXScopeSpec().isSet() &&
8892                                  DC && DC->isRecord() &&
8893                                  DC->isDependentContext())
8894                                   ? TPC_ClassTemplateMember
8895                                   : TPC_FunctionTemplate);
8896     }
8897 
8898     if (NewFD->isInvalidDecl()) {
8899       // Ignore all the rest of this.
8900     } else if (!D.isRedeclaration()) {
8901       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8902                                        AddToScope };
8903       // Fake up an access specifier if it's supposed to be a class member.
8904       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8905         NewFD->setAccess(AS_public);
8906 
8907       // Qualified decls generally require a previous declaration.
8908       if (D.getCXXScopeSpec().isSet()) {
8909         // ...with the major exception of templated-scope or
8910         // dependent-scope friend declarations.
8911 
8912         // TODO: we currently also suppress this check in dependent
8913         // contexts because (1) the parameter depth will be off when
8914         // matching friend templates and (2) we might actually be
8915         // selecting a friend based on a dependent factor.  But there
8916         // are situations where these conditions don't apply and we
8917         // can actually do this check immediately.
8918         if (isFriend &&
8919             (TemplateParamLists.size() ||
8920              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8921              CurContext->isDependentContext())) {
8922           // ignore these
8923         } else {
8924           // The user tried to provide an out-of-line definition for a
8925           // function that is a member of a class or namespace, but there
8926           // was no such member function declared (C++ [class.mfct]p2,
8927           // C++ [namespace.memdef]p2). For example:
8928           //
8929           // class X {
8930           //   void f() const;
8931           // };
8932           //
8933           // void X::f() { } // ill-formed
8934           //
8935           // Complain about this problem, and attempt to suggest close
8936           // matches (e.g., those that differ only in cv-qualifiers and
8937           // whether the parameter types are references).
8938 
8939           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8940                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8941             AddToScope = ExtraArgs.AddToScope;
8942             return Result;
8943           }
8944         }
8945 
8946         // Unqualified local friend declarations are required to resolve
8947         // to something.
8948       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8949         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8950                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8951           AddToScope = ExtraArgs.AddToScope;
8952           return Result;
8953         }
8954       }
8955     } else if (!D.isFunctionDefinition() &&
8956                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8957                !isFriend && !isFunctionTemplateSpecialization &&
8958                !isMemberSpecialization) {
8959       // An out-of-line member function declaration must also be a
8960       // definition (C++ [class.mfct]p2).
8961       // Note that this is not the case for explicit specializations of
8962       // function templates or member functions of class templates, per
8963       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8964       // extension for compatibility with old SWIG code which likes to
8965       // generate them.
8966       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8967         << D.getCXXScopeSpec().getRange();
8968     }
8969   }
8970 
8971   ProcessPragmaWeak(S, NewFD);
8972   checkAttributesAfterMerging(*this, *NewFD);
8973 
8974   AddKnownFunctionAttributes(NewFD);
8975 
8976   if (NewFD->hasAttr<OverloadableAttr>() &&
8977       !NewFD->getType()->getAs<FunctionProtoType>()) {
8978     Diag(NewFD->getLocation(),
8979          diag::err_attribute_overloadable_no_prototype)
8980       << NewFD;
8981 
8982     // Turn this into a variadic function with no parameters.
8983     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8984     FunctionProtoType::ExtProtoInfo EPI(
8985         Context.getDefaultCallingConvention(true, false));
8986     EPI.Variadic = true;
8987     EPI.ExtInfo = FT->getExtInfo();
8988 
8989     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8990     NewFD->setType(R);
8991   }
8992 
8993   // If there's a #pragma GCC visibility in scope, and this isn't a class
8994   // member, set the visibility of this function.
8995   if (!DC->isRecord() && NewFD->isExternallyVisible())
8996     AddPushedVisibilityAttribute(NewFD);
8997 
8998   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8999   // marking the function.
9000   AddCFAuditedAttribute(NewFD);
9001 
9002   // If this is a function definition, check if we have to apply optnone due to
9003   // a pragma.
9004   if(D.isFunctionDefinition())
9005     AddRangeBasedOptnone(NewFD);
9006 
9007   // If this is the first declaration of an extern C variable, update
9008   // the map of such variables.
9009   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9010       isIncompleteDeclExternC(*this, NewFD))
9011     RegisterLocallyScopedExternCDecl(NewFD, S);
9012 
9013   // Set this FunctionDecl's range up to the right paren.
9014   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9015 
9016   if (D.isRedeclaration() && !Previous.empty()) {
9017     checkDLLAttributeRedeclaration(
9018         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9019         isMemberSpecialization || isFunctionTemplateSpecialization,
9020         D.isFunctionDefinition());
9021   }
9022 
9023   if (getLangOpts().CUDA) {
9024     IdentifierInfo *II = NewFD->getIdentifier();
9025     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9026         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9027       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9028         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9029 
9030       Context.setcudaConfigureCallDecl(NewFD);
9031     }
9032 
9033     // Variadic functions, other than a *declaration* of printf, are not allowed
9034     // in device-side CUDA code, unless someone passed
9035     // -fcuda-allow-variadic-functions.
9036     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9037         (NewFD->hasAttr<CUDADeviceAttr>() ||
9038          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9039         !(II && II->isStr("printf") && NewFD->isExternC() &&
9040           !D.isFunctionDefinition())) {
9041       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9042     }
9043   }
9044 
9045   MarkUnusedFileScopedDecl(NewFD);
9046 
9047   if (getLangOpts().CPlusPlus) {
9048     if (FunctionTemplate) {
9049       if (NewFD->isInvalidDecl())
9050         FunctionTemplate->setInvalidDecl();
9051       return FunctionTemplate;
9052     }
9053 
9054     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9055       CompleteMemberSpecialization(NewFD, Previous);
9056   }
9057 
9058   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9059     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9060     if ((getLangOpts().OpenCLVersion >= 120)
9061         && (SC == SC_Static)) {
9062       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9063       D.setInvalidType();
9064     }
9065 
9066     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9067     if (!NewFD->getReturnType()->isVoidType()) {
9068       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9069       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9070           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9071                                 : FixItHint());
9072       D.setInvalidType();
9073     }
9074 
9075     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9076     for (auto Param : NewFD->parameters())
9077       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9078   }
9079   for (const ParmVarDecl *Param : NewFD->parameters()) {
9080     QualType PT = Param->getType();
9081 
9082     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9083     // types.
9084     if (getLangOpts().OpenCLVersion >= 200) {
9085       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9086         QualType ElemTy = PipeTy->getElementType();
9087           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9088             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9089             D.setInvalidType();
9090           }
9091       }
9092     }
9093   }
9094 
9095   // Here we have an function template explicit specialization at class scope.
9096   // The actually specialization will be postponed to template instatiation
9097   // time via the ClassScopeFunctionSpecializationDecl node.
9098   if (isDependentClassScopeExplicitSpecialization) {
9099     ClassScopeFunctionSpecializationDecl *NewSpec =
9100                          ClassScopeFunctionSpecializationDecl::Create(
9101                                 Context, CurContext, SourceLocation(),
9102                                 cast<CXXMethodDecl>(NewFD),
9103                                 HasExplicitTemplateArgs, TemplateArgs);
9104     CurContext->addDecl(NewSpec);
9105     AddToScope = false;
9106   }
9107 
9108   return NewFD;
9109 }
9110 
9111 /// \brief Checks if the new declaration declared in dependent context must be
9112 /// put in the same redeclaration chain as the specified declaration.
9113 ///
9114 /// \param D Declaration that is checked.
9115 /// \param PrevDecl Previous declaration found with proper lookup method for the
9116 ///                 same declaration name.
9117 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9118 ///          belongs to.
9119 ///
9120 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9121   // Any declarations should be put into redeclaration chains except for
9122   // friend declaration in a dependent context that names a function in
9123   // namespace scope.
9124   //
9125   // This allows to compile code like:
9126   //
9127   //       void func();
9128   //       template<typename T> class C1 { friend void func() { } };
9129   //       template<typename T> class C2 { friend void func() { } };
9130   //
9131   // This code snippet is a valid code unless both templates are instantiated.
9132   return !(D->getLexicalDeclContext()->isDependentContext() &&
9133            D->getDeclContext()->isFileContext() &&
9134            D->getFriendObjectKind() != Decl::FOK_None);
9135 }
9136 
9137 /// \brief Perform semantic checking of a new function declaration.
9138 ///
9139 /// Performs semantic analysis of the new function declaration
9140 /// NewFD. This routine performs all semantic checking that does not
9141 /// require the actual declarator involved in the declaration, and is
9142 /// used both for the declaration of functions as they are parsed
9143 /// (called via ActOnDeclarator) and for the declaration of functions
9144 /// that have been instantiated via C++ template instantiation (called
9145 /// via InstantiateDecl).
9146 ///
9147 /// \param IsMemberSpecialization whether this new function declaration is
9148 /// a member specialization (that replaces any definition provided by the
9149 /// previous declaration).
9150 ///
9151 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9152 ///
9153 /// \returns true if the function declaration is a redeclaration.
9154 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9155                                     LookupResult &Previous,
9156                                     bool IsMemberSpecialization) {
9157   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9158          "Variably modified return types are not handled here");
9159 
9160   // Determine whether the type of this function should be merged with
9161   // a previous visible declaration. This never happens for functions in C++,
9162   // and always happens in C if the previous declaration was visible.
9163   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9164                                !Previous.isShadowed();
9165 
9166   bool Redeclaration = false;
9167   NamedDecl *OldDecl = nullptr;
9168 
9169   // Merge or overload the declaration with an existing declaration of
9170   // the same name, if appropriate.
9171   if (!Previous.empty()) {
9172     // Determine whether NewFD is an overload of PrevDecl or
9173     // a declaration that requires merging. If it's an overload,
9174     // there's no more work to do here; we'll just add the new
9175     // function to the scope.
9176     if (!AllowOverloadingOfFunction(Previous, Context)) {
9177       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9178       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9179         Redeclaration = true;
9180         OldDecl = Candidate;
9181       }
9182     } else {
9183       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9184                             /*NewIsUsingDecl*/ false)) {
9185       case Ovl_Match:
9186         Redeclaration = true;
9187         break;
9188 
9189       case Ovl_NonFunction:
9190         Redeclaration = true;
9191         break;
9192 
9193       case Ovl_Overload:
9194         Redeclaration = false;
9195         break;
9196       }
9197 
9198       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9199         // If a function name is overloadable in C, then every function
9200         // with that name must be marked "overloadable".
9201         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9202           << Redeclaration << NewFD;
9203         NamedDecl *OverloadedDecl =
9204             Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9205         Diag(OverloadedDecl->getLocation(),
9206              diag::note_attribute_overloadable_prev_overload);
9207         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9208       }
9209     }
9210   }
9211 
9212   // Check for a previous extern "C" declaration with this name.
9213   if (!Redeclaration &&
9214       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9215     if (!Previous.empty()) {
9216       // This is an extern "C" declaration with the same name as a previous
9217       // declaration, and thus redeclares that entity...
9218       Redeclaration = true;
9219       OldDecl = Previous.getFoundDecl();
9220       MergeTypeWithPrevious = false;
9221 
9222       // ... except in the presence of __attribute__((overloadable)).
9223       if (OldDecl->hasAttr<OverloadableAttr>()) {
9224         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9225           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9226             << Redeclaration << NewFD;
9227           Diag(Previous.getFoundDecl()->getLocation(),
9228                diag::note_attribute_overloadable_prev_overload);
9229           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9230         }
9231         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9232           Redeclaration = false;
9233           OldDecl = nullptr;
9234         }
9235       }
9236     }
9237   }
9238 
9239   // C++11 [dcl.constexpr]p8:
9240   //   A constexpr specifier for a non-static member function that is not
9241   //   a constructor declares that member function to be const.
9242   //
9243   // This needs to be delayed until we know whether this is an out-of-line
9244   // definition of a static member function.
9245   //
9246   // This rule is not present in C++1y, so we produce a backwards
9247   // compatibility warning whenever it happens in C++11.
9248   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9249   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9250       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9251       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9252     CXXMethodDecl *OldMD = nullptr;
9253     if (OldDecl)
9254       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9255     if (!OldMD || !OldMD->isStatic()) {
9256       const FunctionProtoType *FPT =
9257         MD->getType()->castAs<FunctionProtoType>();
9258       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9259       EPI.TypeQuals |= Qualifiers::Const;
9260       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9261                                           FPT->getParamTypes(), EPI));
9262 
9263       // Warn that we did this, if we're not performing template instantiation.
9264       // In that case, we'll have warned already when the template was defined.
9265       if (!inTemplateInstantiation()) {
9266         SourceLocation AddConstLoc;
9267         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9268                 .IgnoreParens().getAs<FunctionTypeLoc>())
9269           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9270 
9271         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9272           << FixItHint::CreateInsertion(AddConstLoc, " const");
9273       }
9274     }
9275   }
9276 
9277   if (Redeclaration) {
9278     // NewFD and OldDecl represent declarations that need to be
9279     // merged.
9280     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9281       NewFD->setInvalidDecl();
9282       return Redeclaration;
9283     }
9284 
9285     Previous.clear();
9286     Previous.addDecl(OldDecl);
9287 
9288     if (FunctionTemplateDecl *OldTemplateDecl
9289                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9290       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9291       FunctionTemplateDecl *NewTemplateDecl
9292         = NewFD->getDescribedFunctionTemplate();
9293       assert(NewTemplateDecl && "Template/non-template mismatch");
9294       if (CXXMethodDecl *Method
9295             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9296         Method->setAccess(OldTemplateDecl->getAccess());
9297         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9298       }
9299 
9300       // If this is an explicit specialization of a member that is a function
9301       // template, mark it as a member specialization.
9302       if (IsMemberSpecialization &&
9303           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9304         NewTemplateDecl->setMemberSpecialization();
9305         assert(OldTemplateDecl->isMemberSpecialization());
9306         // Explicit specializations of a member template do not inherit deleted
9307         // status from the parent member template that they are specializing.
9308         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9309           FunctionDecl *const OldTemplatedDecl =
9310               OldTemplateDecl->getTemplatedDecl();
9311           // FIXME: This assert will not hold in the presence of modules.
9312           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9313           // FIXME: We need an update record for this AST mutation.
9314           OldTemplatedDecl->setDeletedAsWritten(false);
9315         }
9316       }
9317 
9318     } else {
9319       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9320         // This needs to happen first so that 'inline' propagates.
9321         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9322         if (isa<CXXMethodDecl>(NewFD))
9323           NewFD->setAccess(OldDecl->getAccess());
9324       }
9325     }
9326   }
9327 
9328   // Semantic checking for this function declaration (in isolation).
9329 
9330   if (getLangOpts().CPlusPlus) {
9331     // C++-specific checks.
9332     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9333       CheckConstructor(Constructor);
9334     } else if (CXXDestructorDecl *Destructor =
9335                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9336       CXXRecordDecl *Record = Destructor->getParent();
9337       QualType ClassType = Context.getTypeDeclType(Record);
9338 
9339       // FIXME: Shouldn't we be able to perform this check even when the class
9340       // type is dependent? Both gcc and edg can handle that.
9341       if (!ClassType->isDependentType()) {
9342         DeclarationName Name
9343           = Context.DeclarationNames.getCXXDestructorName(
9344                                         Context.getCanonicalType(ClassType));
9345         if (NewFD->getDeclName() != Name) {
9346           Diag(NewFD->getLocation(), diag::err_destructor_name);
9347           NewFD->setInvalidDecl();
9348           return Redeclaration;
9349         }
9350       }
9351     } else if (CXXConversionDecl *Conversion
9352                = dyn_cast<CXXConversionDecl>(NewFD)) {
9353       ActOnConversionDeclarator(Conversion);
9354     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9355       if (auto *TD = Guide->getDescribedFunctionTemplate())
9356         CheckDeductionGuideTemplate(TD);
9357 
9358       // A deduction guide is not on the list of entities that can be
9359       // explicitly specialized.
9360       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9361         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9362             << /*explicit specialization*/ 1;
9363     }
9364 
9365     // Find any virtual functions that this function overrides.
9366     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9367       if (!Method->isFunctionTemplateSpecialization() &&
9368           !Method->getDescribedFunctionTemplate() &&
9369           Method->isCanonicalDecl()) {
9370         if (AddOverriddenMethods(Method->getParent(), Method)) {
9371           // If the function was marked as "static", we have a problem.
9372           if (NewFD->getStorageClass() == SC_Static) {
9373             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9374           }
9375         }
9376       }
9377 
9378       if (Method->isStatic())
9379         checkThisInStaticMemberFunctionType(Method);
9380     }
9381 
9382     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9383     if (NewFD->isOverloadedOperator() &&
9384         CheckOverloadedOperatorDeclaration(NewFD)) {
9385       NewFD->setInvalidDecl();
9386       return Redeclaration;
9387     }
9388 
9389     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9390     if (NewFD->getLiteralIdentifier() &&
9391         CheckLiteralOperatorDeclaration(NewFD)) {
9392       NewFD->setInvalidDecl();
9393       return Redeclaration;
9394     }
9395 
9396     // In C++, check default arguments now that we have merged decls. Unless
9397     // the lexical context is the class, because in this case this is done
9398     // during delayed parsing anyway.
9399     if (!CurContext->isRecord())
9400       CheckCXXDefaultArguments(NewFD);
9401 
9402     // If this function declares a builtin function, check the type of this
9403     // declaration against the expected type for the builtin.
9404     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9405       ASTContext::GetBuiltinTypeError Error;
9406       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9407       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9408       // If the type of the builtin differs only in its exception
9409       // specification, that's OK.
9410       // FIXME: If the types do differ in this way, it would be better to
9411       // retain the 'noexcept' form of the type.
9412       if (!T.isNull() &&
9413           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9414                                                             NewFD->getType()))
9415         // The type of this function differs from the type of the builtin,
9416         // so forget about the builtin entirely.
9417         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9418     }
9419 
9420     // If this function is declared as being extern "C", then check to see if
9421     // the function returns a UDT (class, struct, or union type) that is not C
9422     // compatible, and if it does, warn the user.
9423     // But, issue any diagnostic on the first declaration only.
9424     if (Previous.empty() && NewFD->isExternC()) {
9425       QualType R = NewFD->getReturnType();
9426       if (R->isIncompleteType() && !R->isVoidType())
9427         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9428             << NewFD << R;
9429       else if (!R.isPODType(Context) && !R->isVoidType() &&
9430                !R->isObjCObjectPointerType())
9431         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9432     }
9433 
9434     // C++1z [dcl.fct]p6:
9435     //   [...] whether the function has a non-throwing exception-specification
9436     //   [is] part of the function type
9437     //
9438     // This results in an ABI break between C++14 and C++17 for functions whose
9439     // declared type includes an exception-specification in a parameter or
9440     // return type. (Exception specifications on the function itself are OK in
9441     // most cases, and exception specifications are not permitted in most other
9442     // contexts where they could make it into a mangling.)
9443     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9444       auto HasNoexcept = [&](QualType T) -> bool {
9445         // Strip off declarator chunks that could be between us and a function
9446         // type. We don't need to look far, exception specifications are very
9447         // restricted prior to C++17.
9448         if (auto *RT = T->getAs<ReferenceType>())
9449           T = RT->getPointeeType();
9450         else if (T->isAnyPointerType())
9451           T = T->getPointeeType();
9452         else if (auto *MPT = T->getAs<MemberPointerType>())
9453           T = MPT->getPointeeType();
9454         if (auto *FPT = T->getAs<FunctionProtoType>())
9455           if (FPT->isNothrow(Context))
9456             return true;
9457         return false;
9458       };
9459 
9460       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9461       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9462       for (QualType T : FPT->param_types())
9463         AnyNoexcept |= HasNoexcept(T);
9464       if (AnyNoexcept)
9465         Diag(NewFD->getLocation(),
9466              diag::warn_cxx1z_compat_exception_spec_in_signature)
9467             << NewFD;
9468     }
9469 
9470     if (!Redeclaration && LangOpts.CUDA)
9471       checkCUDATargetOverload(NewFD, Previous);
9472   }
9473   return Redeclaration;
9474 }
9475 
9476 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9477   // C++11 [basic.start.main]p3:
9478   //   A program that [...] declares main to be inline, static or
9479   //   constexpr is ill-formed.
9480   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9481   //   appear in a declaration of main.
9482   // static main is not an error under C99, but we should warn about it.
9483   // We accept _Noreturn main as an extension.
9484   if (FD->getStorageClass() == SC_Static)
9485     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9486          ? diag::err_static_main : diag::warn_static_main)
9487       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9488   if (FD->isInlineSpecified())
9489     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9490       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9491   if (DS.isNoreturnSpecified()) {
9492     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9493     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9494     Diag(NoreturnLoc, diag::ext_noreturn_main);
9495     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9496       << FixItHint::CreateRemoval(NoreturnRange);
9497   }
9498   if (FD->isConstexpr()) {
9499     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9500       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9501     FD->setConstexpr(false);
9502   }
9503 
9504   if (getLangOpts().OpenCL) {
9505     Diag(FD->getLocation(), diag::err_opencl_no_main)
9506         << FD->hasAttr<OpenCLKernelAttr>();
9507     FD->setInvalidDecl();
9508     return;
9509   }
9510 
9511   QualType T = FD->getType();
9512   assert(T->isFunctionType() && "function decl is not of function type");
9513   const FunctionType* FT = T->castAs<FunctionType>();
9514 
9515   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9516     // In C with GNU extensions we allow main() to have non-integer return
9517     // type, but we should warn about the extension, and we disable the
9518     // implicit-return-zero rule.
9519 
9520     // GCC in C mode accepts qualified 'int'.
9521     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9522       FD->setHasImplicitReturnZero(true);
9523     else {
9524       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9525       SourceRange RTRange = FD->getReturnTypeSourceRange();
9526       if (RTRange.isValid())
9527         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9528             << FixItHint::CreateReplacement(RTRange, "int");
9529     }
9530   } else {
9531     // In C and C++, main magically returns 0 if you fall off the end;
9532     // set the flag which tells us that.
9533     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9534 
9535     // All the standards say that main() should return 'int'.
9536     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9537       FD->setHasImplicitReturnZero(true);
9538     else {
9539       // Otherwise, this is just a flat-out error.
9540       SourceRange RTRange = FD->getReturnTypeSourceRange();
9541       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9542           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9543                                 : FixItHint());
9544       FD->setInvalidDecl(true);
9545     }
9546   }
9547 
9548   // Treat protoless main() as nullary.
9549   if (isa<FunctionNoProtoType>(FT)) return;
9550 
9551   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9552   unsigned nparams = FTP->getNumParams();
9553   assert(FD->getNumParams() == nparams);
9554 
9555   bool HasExtraParameters = (nparams > 3);
9556 
9557   if (FTP->isVariadic()) {
9558     Diag(FD->getLocation(), diag::ext_variadic_main);
9559     // FIXME: if we had information about the location of the ellipsis, we
9560     // could add a FixIt hint to remove it as a parameter.
9561   }
9562 
9563   // Darwin passes an undocumented fourth argument of type char**.  If
9564   // other platforms start sprouting these, the logic below will start
9565   // getting shifty.
9566   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9567     HasExtraParameters = false;
9568 
9569   if (HasExtraParameters) {
9570     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9571     FD->setInvalidDecl(true);
9572     nparams = 3;
9573   }
9574 
9575   // FIXME: a lot of the following diagnostics would be improved
9576   // if we had some location information about types.
9577 
9578   QualType CharPP =
9579     Context.getPointerType(Context.getPointerType(Context.CharTy));
9580   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9581 
9582   for (unsigned i = 0; i < nparams; ++i) {
9583     QualType AT = FTP->getParamType(i);
9584 
9585     bool mismatch = true;
9586 
9587     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9588       mismatch = false;
9589     else if (Expected[i] == CharPP) {
9590       // As an extension, the following forms are okay:
9591       //   char const **
9592       //   char const * const *
9593       //   char * const *
9594 
9595       QualifierCollector qs;
9596       const PointerType* PT;
9597       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9598           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9599           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9600                               Context.CharTy)) {
9601         qs.removeConst();
9602         mismatch = !qs.empty();
9603       }
9604     }
9605 
9606     if (mismatch) {
9607       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9608       // TODO: suggest replacing given type with expected type
9609       FD->setInvalidDecl(true);
9610     }
9611   }
9612 
9613   if (nparams == 1 && !FD->isInvalidDecl()) {
9614     Diag(FD->getLocation(), diag::warn_main_one_arg);
9615   }
9616 
9617   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9618     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9619     FD->setInvalidDecl();
9620   }
9621 }
9622 
9623 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9624   QualType T = FD->getType();
9625   assert(T->isFunctionType() && "function decl is not of function type");
9626   const FunctionType *FT = T->castAs<FunctionType>();
9627 
9628   // Set an implicit return of 'zero' if the function can return some integral,
9629   // enumeration, pointer or nullptr type.
9630   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9631       FT->getReturnType()->isAnyPointerType() ||
9632       FT->getReturnType()->isNullPtrType())
9633     // DllMain is exempt because a return value of zero means it failed.
9634     if (FD->getName() != "DllMain")
9635       FD->setHasImplicitReturnZero(true);
9636 
9637   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9638     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9639     FD->setInvalidDecl();
9640   }
9641 }
9642 
9643 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9644   // FIXME: Need strict checking.  In C89, we need to check for
9645   // any assignment, increment, decrement, function-calls, or
9646   // commas outside of a sizeof.  In C99, it's the same list,
9647   // except that the aforementioned are allowed in unevaluated
9648   // expressions.  Everything else falls under the
9649   // "may accept other forms of constant expressions" exception.
9650   // (We never end up here for C++, so the constant expression
9651   // rules there don't matter.)
9652   const Expr *Culprit;
9653   if (Init->isConstantInitializer(Context, false, &Culprit))
9654     return false;
9655   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9656     << Culprit->getSourceRange();
9657   return true;
9658 }
9659 
9660 namespace {
9661   // Visits an initialization expression to see if OrigDecl is evaluated in
9662   // its own initialization and throws a warning if it does.
9663   class SelfReferenceChecker
9664       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9665     Sema &S;
9666     Decl *OrigDecl;
9667     bool isRecordType;
9668     bool isPODType;
9669     bool isReferenceType;
9670 
9671     bool isInitList;
9672     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9673 
9674   public:
9675     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9676 
9677     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9678                                                     S(S), OrigDecl(OrigDecl) {
9679       isPODType = false;
9680       isRecordType = false;
9681       isReferenceType = false;
9682       isInitList = false;
9683       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9684         isPODType = VD->getType().isPODType(S.Context);
9685         isRecordType = VD->getType()->isRecordType();
9686         isReferenceType = VD->getType()->isReferenceType();
9687       }
9688     }
9689 
9690     // For most expressions, just call the visitor.  For initializer lists,
9691     // track the index of the field being initialized since fields are
9692     // initialized in order allowing use of previously initialized fields.
9693     void CheckExpr(Expr *E) {
9694       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9695       if (!InitList) {
9696         Visit(E);
9697         return;
9698       }
9699 
9700       // Track and increment the index here.
9701       isInitList = true;
9702       InitFieldIndex.push_back(0);
9703       for (auto Child : InitList->children()) {
9704         CheckExpr(cast<Expr>(Child));
9705         ++InitFieldIndex.back();
9706       }
9707       InitFieldIndex.pop_back();
9708     }
9709 
9710     // Returns true if MemberExpr is checked and no further checking is needed.
9711     // Returns false if additional checking is required.
9712     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9713       llvm::SmallVector<FieldDecl*, 4> Fields;
9714       Expr *Base = E;
9715       bool ReferenceField = false;
9716 
9717       // Get the field memebers used.
9718       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9719         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9720         if (!FD)
9721           return false;
9722         Fields.push_back(FD);
9723         if (FD->getType()->isReferenceType())
9724           ReferenceField = true;
9725         Base = ME->getBase()->IgnoreParenImpCasts();
9726       }
9727 
9728       // Keep checking only if the base Decl is the same.
9729       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9730       if (!DRE || DRE->getDecl() != OrigDecl)
9731         return false;
9732 
9733       // A reference field can be bound to an unininitialized field.
9734       if (CheckReference && !ReferenceField)
9735         return true;
9736 
9737       // Convert FieldDecls to their index number.
9738       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9739       for (const FieldDecl *I : llvm::reverse(Fields))
9740         UsedFieldIndex.push_back(I->getFieldIndex());
9741 
9742       // See if a warning is needed by checking the first difference in index
9743       // numbers.  If field being used has index less than the field being
9744       // initialized, then the use is safe.
9745       for (auto UsedIter = UsedFieldIndex.begin(),
9746                 UsedEnd = UsedFieldIndex.end(),
9747                 OrigIter = InitFieldIndex.begin(),
9748                 OrigEnd = InitFieldIndex.end();
9749            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9750         if (*UsedIter < *OrigIter)
9751           return true;
9752         if (*UsedIter > *OrigIter)
9753           break;
9754       }
9755 
9756       // TODO: Add a different warning which will print the field names.
9757       HandleDeclRefExpr(DRE);
9758       return true;
9759     }
9760 
9761     // For most expressions, the cast is directly above the DeclRefExpr.
9762     // For conditional operators, the cast can be outside the conditional
9763     // operator if both expressions are DeclRefExpr's.
9764     void HandleValue(Expr *E) {
9765       E = E->IgnoreParens();
9766       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9767         HandleDeclRefExpr(DRE);
9768         return;
9769       }
9770 
9771       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9772         Visit(CO->getCond());
9773         HandleValue(CO->getTrueExpr());
9774         HandleValue(CO->getFalseExpr());
9775         return;
9776       }
9777 
9778       if (BinaryConditionalOperator *BCO =
9779               dyn_cast<BinaryConditionalOperator>(E)) {
9780         Visit(BCO->getCond());
9781         HandleValue(BCO->getFalseExpr());
9782         return;
9783       }
9784 
9785       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9786         HandleValue(OVE->getSourceExpr());
9787         return;
9788       }
9789 
9790       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9791         if (BO->getOpcode() == BO_Comma) {
9792           Visit(BO->getLHS());
9793           HandleValue(BO->getRHS());
9794           return;
9795         }
9796       }
9797 
9798       if (isa<MemberExpr>(E)) {
9799         if (isInitList) {
9800           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9801                                       false /*CheckReference*/))
9802             return;
9803         }
9804 
9805         Expr *Base = E->IgnoreParenImpCasts();
9806         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9807           // Check for static member variables and don't warn on them.
9808           if (!isa<FieldDecl>(ME->getMemberDecl()))
9809             return;
9810           Base = ME->getBase()->IgnoreParenImpCasts();
9811         }
9812         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9813           HandleDeclRefExpr(DRE);
9814         return;
9815       }
9816 
9817       Visit(E);
9818     }
9819 
9820     // Reference types not handled in HandleValue are handled here since all
9821     // uses of references are bad, not just r-value uses.
9822     void VisitDeclRefExpr(DeclRefExpr *E) {
9823       if (isReferenceType)
9824         HandleDeclRefExpr(E);
9825     }
9826 
9827     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9828       if (E->getCastKind() == CK_LValueToRValue) {
9829         HandleValue(E->getSubExpr());
9830         return;
9831       }
9832 
9833       Inherited::VisitImplicitCastExpr(E);
9834     }
9835 
9836     void VisitMemberExpr(MemberExpr *E) {
9837       if (isInitList) {
9838         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9839           return;
9840       }
9841 
9842       // Don't warn on arrays since they can be treated as pointers.
9843       if (E->getType()->canDecayToPointerType()) return;
9844 
9845       // Warn when a non-static method call is followed by non-static member
9846       // field accesses, which is followed by a DeclRefExpr.
9847       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9848       bool Warn = (MD && !MD->isStatic());
9849       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9850       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9851         if (!isa<FieldDecl>(ME->getMemberDecl()))
9852           Warn = false;
9853         Base = ME->getBase()->IgnoreParenImpCasts();
9854       }
9855 
9856       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9857         if (Warn)
9858           HandleDeclRefExpr(DRE);
9859         return;
9860       }
9861 
9862       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9863       // Visit that expression.
9864       Visit(Base);
9865     }
9866 
9867     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9868       Expr *Callee = E->getCallee();
9869 
9870       if (isa<UnresolvedLookupExpr>(Callee))
9871         return Inherited::VisitCXXOperatorCallExpr(E);
9872 
9873       Visit(Callee);
9874       for (auto Arg: E->arguments())
9875         HandleValue(Arg->IgnoreParenImpCasts());
9876     }
9877 
9878     void VisitUnaryOperator(UnaryOperator *E) {
9879       // For POD record types, addresses of its own members are well-defined.
9880       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9881           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9882         if (!isPODType)
9883           HandleValue(E->getSubExpr());
9884         return;
9885       }
9886 
9887       if (E->isIncrementDecrementOp()) {
9888         HandleValue(E->getSubExpr());
9889         return;
9890       }
9891 
9892       Inherited::VisitUnaryOperator(E);
9893     }
9894 
9895     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9896 
9897     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9898       if (E->getConstructor()->isCopyConstructor()) {
9899         Expr *ArgExpr = E->getArg(0);
9900         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9901           if (ILE->getNumInits() == 1)
9902             ArgExpr = ILE->getInit(0);
9903         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9904           if (ICE->getCastKind() == CK_NoOp)
9905             ArgExpr = ICE->getSubExpr();
9906         HandleValue(ArgExpr);
9907         return;
9908       }
9909       Inherited::VisitCXXConstructExpr(E);
9910     }
9911 
9912     void VisitCallExpr(CallExpr *E) {
9913       // Treat std::move as a use.
9914       if (E->getNumArgs() == 1) {
9915         if (FunctionDecl *FD = E->getDirectCallee()) {
9916           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9917               FD->getIdentifier()->isStr("move")) {
9918             HandleValue(E->getArg(0));
9919             return;
9920           }
9921         }
9922       }
9923 
9924       Inherited::VisitCallExpr(E);
9925     }
9926 
9927     void VisitBinaryOperator(BinaryOperator *E) {
9928       if (E->isCompoundAssignmentOp()) {
9929         HandleValue(E->getLHS());
9930         Visit(E->getRHS());
9931         return;
9932       }
9933 
9934       Inherited::VisitBinaryOperator(E);
9935     }
9936 
9937     // A custom visitor for BinaryConditionalOperator is needed because the
9938     // regular visitor would check the condition and true expression separately
9939     // but both point to the same place giving duplicate diagnostics.
9940     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9941       Visit(E->getCond());
9942       Visit(E->getFalseExpr());
9943     }
9944 
9945     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9946       Decl* ReferenceDecl = DRE->getDecl();
9947       if (OrigDecl != ReferenceDecl) return;
9948       unsigned diag;
9949       if (isReferenceType) {
9950         diag = diag::warn_uninit_self_reference_in_reference_init;
9951       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9952         diag = diag::warn_static_self_reference_in_init;
9953       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9954                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9955                  DRE->getDecl()->getType()->isRecordType()) {
9956         diag = diag::warn_uninit_self_reference_in_init;
9957       } else {
9958         // Local variables will be handled by the CFG analysis.
9959         return;
9960       }
9961 
9962       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9963                             S.PDiag(diag)
9964                               << DRE->getNameInfo().getName()
9965                               << OrigDecl->getLocation()
9966                               << DRE->getSourceRange());
9967     }
9968   };
9969 
9970   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9971   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9972                                  bool DirectInit) {
9973     // Parameters arguments are occassionially constructed with itself,
9974     // for instance, in recursive functions.  Skip them.
9975     if (isa<ParmVarDecl>(OrigDecl))
9976       return;
9977 
9978     E = E->IgnoreParens();
9979 
9980     // Skip checking T a = a where T is not a record or reference type.
9981     // Doing so is a way to silence uninitialized warnings.
9982     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9983       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9984         if (ICE->getCastKind() == CK_LValueToRValue)
9985           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9986             if (DRE->getDecl() == OrigDecl)
9987               return;
9988 
9989     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9990   }
9991 } // end anonymous namespace
9992 
9993 namespace {
9994   // Simple wrapper to add the name of a variable or (if no variable is
9995   // available) a DeclarationName into a diagnostic.
9996   struct VarDeclOrName {
9997     VarDecl *VDecl;
9998     DeclarationName Name;
9999 
10000     friend const Sema::SemaDiagnosticBuilder &
10001     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10002       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10003     }
10004   };
10005 } // end anonymous namespace
10006 
10007 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10008                                             DeclarationName Name, QualType Type,
10009                                             TypeSourceInfo *TSI,
10010                                             SourceRange Range, bool DirectInit,
10011                                             Expr *Init) {
10012   bool IsInitCapture = !VDecl;
10013   assert((!VDecl || !VDecl->isInitCapture()) &&
10014          "init captures are expected to be deduced prior to initialization");
10015 
10016   VarDeclOrName VN{VDecl, Name};
10017 
10018   DeducedType *Deduced = Type->getContainedDeducedType();
10019   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10020 
10021   // C++11 [dcl.spec.auto]p3
10022   if (!Init) {
10023     assert(VDecl && "no init for init capture deduction?");
10024     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10025       << VDecl->getDeclName() << Type;
10026     return QualType();
10027   }
10028 
10029   ArrayRef<Expr*> DeduceInits = Init;
10030   if (DirectInit) {
10031     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10032       DeduceInits = PL->exprs();
10033   }
10034 
10035   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10036     assert(VDecl && "non-auto type for init capture deduction?");
10037     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10038     InitializationKind Kind = InitializationKind::CreateForInit(
10039         VDecl->getLocation(), DirectInit, Init);
10040     // FIXME: Initialization should not be taking a mutable list of inits.
10041     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10042     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10043                                                        InitsCopy);
10044   }
10045 
10046   if (DirectInit) {
10047     if (auto *IL = dyn_cast<InitListExpr>(Init))
10048       DeduceInits = IL->inits();
10049   }
10050 
10051   // Deduction only works if we have exactly one source expression.
10052   if (DeduceInits.empty()) {
10053     // It isn't possible to write this directly, but it is possible to
10054     // end up in this situation with "auto x(some_pack...);"
10055     Diag(Init->getLocStart(), IsInitCapture
10056                                   ? diag::err_init_capture_no_expression
10057                                   : diag::err_auto_var_init_no_expression)
10058         << VN << Type << Range;
10059     return QualType();
10060   }
10061 
10062   if (DeduceInits.size() > 1) {
10063     Diag(DeduceInits[1]->getLocStart(),
10064          IsInitCapture ? diag::err_init_capture_multiple_expressions
10065                        : diag::err_auto_var_init_multiple_expressions)
10066         << VN << Type << Range;
10067     return QualType();
10068   }
10069 
10070   Expr *DeduceInit = DeduceInits[0];
10071   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10072     Diag(Init->getLocStart(), IsInitCapture
10073                                   ? diag::err_init_capture_paren_braces
10074                                   : diag::err_auto_var_init_paren_braces)
10075         << isa<InitListExpr>(Init) << VN << Type << Range;
10076     return QualType();
10077   }
10078 
10079   // Expressions default to 'id' when we're in a debugger.
10080   bool DefaultedAnyToId = false;
10081   if (getLangOpts().DebuggerCastResultToId &&
10082       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10083     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10084     if (Result.isInvalid()) {
10085       return QualType();
10086     }
10087     Init = Result.get();
10088     DefaultedAnyToId = true;
10089   }
10090 
10091   // C++ [dcl.decomp]p1:
10092   //   If the assignment-expression [...] has array type A and no ref-qualifier
10093   //   is present, e has type cv A
10094   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10095       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10096       DeduceInit->getType()->isConstantArrayType())
10097     return Context.getQualifiedType(DeduceInit->getType(),
10098                                     Type.getQualifiers());
10099 
10100   QualType DeducedType;
10101   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10102     if (!IsInitCapture)
10103       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10104     else if (isa<InitListExpr>(Init))
10105       Diag(Range.getBegin(),
10106            diag::err_init_capture_deduction_failure_from_init_list)
10107           << VN
10108           << (DeduceInit->getType().isNull() ? TSI->getType()
10109                                              : DeduceInit->getType())
10110           << DeduceInit->getSourceRange();
10111     else
10112       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10113           << VN << TSI->getType()
10114           << (DeduceInit->getType().isNull() ? TSI->getType()
10115                                              : DeduceInit->getType())
10116           << DeduceInit->getSourceRange();
10117   }
10118 
10119   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10120   // 'id' instead of a specific object type prevents most of our usual
10121   // checks.
10122   // We only want to warn outside of template instantiations, though:
10123   // inside a template, the 'id' could have come from a parameter.
10124   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10125       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10126     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10127     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10128   }
10129 
10130   return DeducedType;
10131 }
10132 
10133 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10134                                          Expr *Init) {
10135   QualType DeducedType = deduceVarTypeFromInitializer(
10136       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10137       VDecl->getSourceRange(), DirectInit, Init);
10138   if (DeducedType.isNull()) {
10139     VDecl->setInvalidDecl();
10140     return true;
10141   }
10142 
10143   VDecl->setType(DeducedType);
10144   assert(VDecl->isLinkageValid());
10145 
10146   // In ARC, infer lifetime.
10147   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10148     VDecl->setInvalidDecl();
10149 
10150   // If this is a redeclaration, check that the type we just deduced matches
10151   // the previously declared type.
10152   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10153     // We never need to merge the type, because we cannot form an incomplete
10154     // array of auto, nor deduce such a type.
10155     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10156   }
10157 
10158   // Check the deduced type is valid for a variable declaration.
10159   CheckVariableDeclarationType(VDecl);
10160   return VDecl->isInvalidDecl();
10161 }
10162 
10163 /// AddInitializerToDecl - Adds the initializer Init to the
10164 /// declaration dcl. If DirectInit is true, this is C++ direct
10165 /// initialization rather than copy initialization.
10166 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10167   // If there is no declaration, there was an error parsing it.  Just ignore
10168   // the initializer.
10169   if (!RealDecl || RealDecl->isInvalidDecl()) {
10170     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10171     return;
10172   }
10173 
10174   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10175     // Pure-specifiers are handled in ActOnPureSpecifier.
10176     Diag(Method->getLocation(), diag::err_member_function_initialization)
10177       << Method->getDeclName() << Init->getSourceRange();
10178     Method->setInvalidDecl();
10179     return;
10180   }
10181 
10182   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10183   if (!VDecl) {
10184     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10185     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10186     RealDecl->setInvalidDecl();
10187     return;
10188   }
10189 
10190   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10191   if (VDecl->getType()->isUndeducedType()) {
10192     // Attempt typo correction early so that the type of the init expression can
10193     // be deduced based on the chosen correction if the original init contains a
10194     // TypoExpr.
10195     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10196     if (!Res.isUsable()) {
10197       RealDecl->setInvalidDecl();
10198       return;
10199     }
10200     Init = Res.get();
10201 
10202     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10203       return;
10204   }
10205 
10206   // dllimport cannot be used on variable definitions.
10207   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10208     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10209     VDecl->setInvalidDecl();
10210     return;
10211   }
10212 
10213   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10214     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10215     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10216     VDecl->setInvalidDecl();
10217     return;
10218   }
10219 
10220   if (!VDecl->getType()->isDependentType()) {
10221     // A definition must end up with a complete type, which means it must be
10222     // complete with the restriction that an array type might be completed by
10223     // the initializer; note that later code assumes this restriction.
10224     QualType BaseDeclType = VDecl->getType();
10225     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10226       BaseDeclType = Array->getElementType();
10227     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10228                             diag::err_typecheck_decl_incomplete_type)) {
10229       RealDecl->setInvalidDecl();
10230       return;
10231     }
10232 
10233     // The variable can not have an abstract class type.
10234     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10235                                diag::err_abstract_type_in_decl,
10236                                AbstractVariableType))
10237       VDecl->setInvalidDecl();
10238   }
10239 
10240   // If adding the initializer will turn this declaration into a definition,
10241   // and we already have a definition for this variable, diagnose or otherwise
10242   // handle the situation.
10243   VarDecl *Def;
10244   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10245       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10246       !VDecl->isThisDeclarationADemotedDefinition() &&
10247       checkVarDeclRedefinition(Def, VDecl))
10248     return;
10249 
10250   if (getLangOpts().CPlusPlus) {
10251     // C++ [class.static.data]p4
10252     //   If a static data member is of const integral or const
10253     //   enumeration type, its declaration in the class definition can
10254     //   specify a constant-initializer which shall be an integral
10255     //   constant expression (5.19). In that case, the member can appear
10256     //   in integral constant expressions. The member shall still be
10257     //   defined in a namespace scope if it is used in the program and the
10258     //   namespace scope definition shall not contain an initializer.
10259     //
10260     // We already performed a redefinition check above, but for static
10261     // data members we also need to check whether there was an in-class
10262     // declaration with an initializer.
10263     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10264       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10265           << VDecl->getDeclName();
10266       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10267            diag::note_previous_initializer)
10268           << 0;
10269       return;
10270     }
10271 
10272     if (VDecl->hasLocalStorage())
10273       getCurFunction()->setHasBranchProtectedScope();
10274 
10275     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10276       VDecl->setInvalidDecl();
10277       return;
10278     }
10279   }
10280 
10281   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10282   // a kernel function cannot be initialized."
10283   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10284     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10285     VDecl->setInvalidDecl();
10286     return;
10287   }
10288 
10289   // Get the decls type and save a reference for later, since
10290   // CheckInitializerTypes may change it.
10291   QualType DclT = VDecl->getType(), SavT = DclT;
10292 
10293   // Expressions default to 'id' when we're in a debugger
10294   // and we are assigning it to a variable of Objective-C pointer type.
10295   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10296       Init->getType() == Context.UnknownAnyTy) {
10297     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10298     if (Result.isInvalid()) {
10299       VDecl->setInvalidDecl();
10300       return;
10301     }
10302     Init = Result.get();
10303   }
10304 
10305   // Perform the initialization.
10306   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10307   if (!VDecl->isInvalidDecl()) {
10308     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10309     InitializationKind Kind = InitializationKind::CreateForInit(
10310         VDecl->getLocation(), DirectInit, Init);
10311 
10312     MultiExprArg Args = Init;
10313     if (CXXDirectInit)
10314       Args = MultiExprArg(CXXDirectInit->getExprs(),
10315                           CXXDirectInit->getNumExprs());
10316 
10317     // Try to correct any TypoExprs in the initialization arguments.
10318     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10319       ExprResult Res = CorrectDelayedTyposInExpr(
10320           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10321             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10322             return Init.Failed() ? ExprError() : E;
10323           });
10324       if (Res.isInvalid()) {
10325         VDecl->setInvalidDecl();
10326       } else if (Res.get() != Args[Idx]) {
10327         Args[Idx] = Res.get();
10328       }
10329     }
10330     if (VDecl->isInvalidDecl())
10331       return;
10332 
10333     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10334                                    /*TopLevelOfInitList=*/false,
10335                                    /*TreatUnavailableAsInvalid=*/false);
10336     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10337     if (Result.isInvalid()) {
10338       VDecl->setInvalidDecl();
10339       return;
10340     }
10341 
10342     Init = Result.getAs<Expr>();
10343   }
10344 
10345   // Check for self-references within variable initializers.
10346   // Variables declared within a function/method body (except for references)
10347   // are handled by a dataflow analysis.
10348   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10349       VDecl->getType()->isReferenceType()) {
10350     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10351   }
10352 
10353   // If the type changed, it means we had an incomplete type that was
10354   // completed by the initializer. For example:
10355   //   int ary[] = { 1, 3, 5 };
10356   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10357   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10358     VDecl->setType(DclT);
10359 
10360   if (!VDecl->isInvalidDecl()) {
10361     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10362 
10363     if (VDecl->hasAttr<BlocksAttr>())
10364       checkRetainCycles(VDecl, Init);
10365 
10366     // It is safe to assign a weak reference into a strong variable.
10367     // Although this code can still have problems:
10368     //   id x = self.weakProp;
10369     //   id y = self.weakProp;
10370     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10371     // paths through the function. This should be revisited if
10372     // -Wrepeated-use-of-weak is made flow-sensitive.
10373     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10374          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10375         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10376                          Init->getLocStart()))
10377       getCurFunction()->markSafeWeakUse(Init);
10378   }
10379 
10380   // The initialization is usually a full-expression.
10381   //
10382   // FIXME: If this is a braced initialization of an aggregate, it is not
10383   // an expression, and each individual field initializer is a separate
10384   // full-expression. For instance, in:
10385   //
10386   //   struct Temp { ~Temp(); };
10387   //   struct S { S(Temp); };
10388   //   struct T { S a, b; } t = { Temp(), Temp() }
10389   //
10390   // we should destroy the first Temp before constructing the second.
10391   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10392                                           false,
10393                                           VDecl->isConstexpr());
10394   if (Result.isInvalid()) {
10395     VDecl->setInvalidDecl();
10396     return;
10397   }
10398   Init = Result.get();
10399 
10400   // Attach the initializer to the decl.
10401   VDecl->setInit(Init);
10402 
10403   if (VDecl->isLocalVarDecl()) {
10404     // Don't check the initializer if the declaration is malformed.
10405     if (VDecl->isInvalidDecl()) {
10406       // do nothing
10407 
10408     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10409     // This is true even in OpenCL C++.
10410     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10411       CheckForConstantInitializer(Init, DclT);
10412 
10413     // Otherwise, C++ does not restrict the initializer.
10414     } else if (getLangOpts().CPlusPlus) {
10415       // do nothing
10416 
10417     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10418     // static storage duration shall be constant expressions or string literals.
10419     } else if (VDecl->getStorageClass() == SC_Static) {
10420       CheckForConstantInitializer(Init, DclT);
10421 
10422     // C89 is stricter than C99 for aggregate initializers.
10423     // C89 6.5.7p3: All the expressions [...] in an initializer list
10424     // for an object that has aggregate or union type shall be
10425     // constant expressions.
10426     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10427                isa<InitListExpr>(Init)) {
10428       const Expr *Culprit;
10429       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10430         Diag(Culprit->getExprLoc(),
10431              diag::ext_aggregate_init_not_constant)
10432           << Culprit->getSourceRange();
10433       }
10434     }
10435   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10436              VDecl->getLexicalDeclContext()->isRecord()) {
10437     // This is an in-class initialization for a static data member, e.g.,
10438     //
10439     // struct S {
10440     //   static const int value = 17;
10441     // };
10442 
10443     // C++ [class.mem]p4:
10444     //   A member-declarator can contain a constant-initializer only
10445     //   if it declares a static member (9.4) of const integral or
10446     //   const enumeration type, see 9.4.2.
10447     //
10448     // C++11 [class.static.data]p3:
10449     //   If a non-volatile non-inline const static data member is of integral
10450     //   or enumeration type, its declaration in the class definition can
10451     //   specify a brace-or-equal-initializer in which every initializer-clause
10452     //   that is an assignment-expression is a constant expression. A static
10453     //   data member of literal type can be declared in the class definition
10454     //   with the constexpr specifier; if so, its declaration shall specify a
10455     //   brace-or-equal-initializer in which every initializer-clause that is
10456     //   an assignment-expression is a constant expression.
10457 
10458     // Do nothing on dependent types.
10459     if (DclT->isDependentType()) {
10460 
10461     // Allow any 'static constexpr' members, whether or not they are of literal
10462     // type. We separately check that every constexpr variable is of literal
10463     // type.
10464     } else if (VDecl->isConstexpr()) {
10465 
10466     // Require constness.
10467     } else if (!DclT.isConstQualified()) {
10468       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10469         << Init->getSourceRange();
10470       VDecl->setInvalidDecl();
10471 
10472     // We allow integer constant expressions in all cases.
10473     } else if (DclT->isIntegralOrEnumerationType()) {
10474       // Check whether the expression is a constant expression.
10475       SourceLocation Loc;
10476       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10477         // In C++11, a non-constexpr const static data member with an
10478         // in-class initializer cannot be volatile.
10479         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10480       else if (Init->isValueDependent())
10481         ; // Nothing to check.
10482       else if (Init->isIntegerConstantExpr(Context, &Loc))
10483         ; // Ok, it's an ICE!
10484       else if (Init->isEvaluatable(Context)) {
10485         // If we can constant fold the initializer through heroics, accept it,
10486         // but report this as a use of an extension for -pedantic.
10487         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10488           << Init->getSourceRange();
10489       } else {
10490         // Otherwise, this is some crazy unknown case.  Report the issue at the
10491         // location provided by the isIntegerConstantExpr failed check.
10492         Diag(Loc, diag::err_in_class_initializer_non_constant)
10493           << Init->getSourceRange();
10494         VDecl->setInvalidDecl();
10495       }
10496 
10497     // We allow foldable floating-point constants as an extension.
10498     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10499       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10500       // it anyway and provide a fixit to add the 'constexpr'.
10501       if (getLangOpts().CPlusPlus11) {
10502         Diag(VDecl->getLocation(),
10503              diag::ext_in_class_initializer_float_type_cxx11)
10504             << DclT << Init->getSourceRange();
10505         Diag(VDecl->getLocStart(),
10506              diag::note_in_class_initializer_float_type_cxx11)
10507             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10508       } else {
10509         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10510           << DclT << Init->getSourceRange();
10511 
10512         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10513           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10514             << Init->getSourceRange();
10515           VDecl->setInvalidDecl();
10516         }
10517       }
10518 
10519     // Suggest adding 'constexpr' in C++11 for literal types.
10520     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10521       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10522         << DclT << Init->getSourceRange()
10523         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10524       VDecl->setConstexpr(true);
10525 
10526     } else {
10527       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10528         << DclT << Init->getSourceRange();
10529       VDecl->setInvalidDecl();
10530     }
10531   } else if (VDecl->isFileVarDecl()) {
10532     // In C, extern is typically used to avoid tentative definitions when
10533     // declaring variables in headers, but adding an intializer makes it a
10534     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10535     // In C++, extern is often used to give implictly static const variables
10536     // external linkage, so don't warn in that case. If selectany is present,
10537     // this might be header code intended for C and C++ inclusion, so apply the
10538     // C++ rules.
10539     if (VDecl->getStorageClass() == SC_Extern &&
10540         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10541          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10542         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10543         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10544       Diag(VDecl->getLocation(), diag::warn_extern_init);
10545 
10546     // C99 6.7.8p4. All file scoped initializers need to be constant.
10547     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10548       CheckForConstantInitializer(Init, DclT);
10549   }
10550 
10551   // We will represent direct-initialization similarly to copy-initialization:
10552   //    int x(1);  -as-> int x = 1;
10553   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10554   //
10555   // Clients that want to distinguish between the two forms, can check for
10556   // direct initializer using VarDecl::getInitStyle().
10557   // A major benefit is that clients that don't particularly care about which
10558   // exactly form was it (like the CodeGen) can handle both cases without
10559   // special case code.
10560 
10561   // C++ 8.5p11:
10562   // The form of initialization (using parentheses or '=') is generally
10563   // insignificant, but does matter when the entity being initialized has a
10564   // class type.
10565   if (CXXDirectInit) {
10566     assert(DirectInit && "Call-style initializer must be direct init.");
10567     VDecl->setInitStyle(VarDecl::CallInit);
10568   } else if (DirectInit) {
10569     // This must be list-initialization. No other way is direct-initialization.
10570     VDecl->setInitStyle(VarDecl::ListInit);
10571   }
10572 
10573   CheckCompleteVariableDeclaration(VDecl);
10574 }
10575 
10576 /// ActOnInitializerError - Given that there was an error parsing an
10577 /// initializer for the given declaration, try to return to some form
10578 /// of sanity.
10579 void Sema::ActOnInitializerError(Decl *D) {
10580   // Our main concern here is re-establishing invariants like "a
10581   // variable's type is either dependent or complete".
10582   if (!D || D->isInvalidDecl()) return;
10583 
10584   VarDecl *VD = dyn_cast<VarDecl>(D);
10585   if (!VD) return;
10586 
10587   // Bindings are not usable if we can't make sense of the initializer.
10588   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10589     for (auto *BD : DD->bindings())
10590       BD->setInvalidDecl();
10591 
10592   // Auto types are meaningless if we can't make sense of the initializer.
10593   if (ParsingInitForAutoVars.count(D)) {
10594     D->setInvalidDecl();
10595     return;
10596   }
10597 
10598   QualType Ty = VD->getType();
10599   if (Ty->isDependentType()) return;
10600 
10601   // Require a complete type.
10602   if (RequireCompleteType(VD->getLocation(),
10603                           Context.getBaseElementType(Ty),
10604                           diag::err_typecheck_decl_incomplete_type)) {
10605     VD->setInvalidDecl();
10606     return;
10607   }
10608 
10609   // Require a non-abstract type.
10610   if (RequireNonAbstractType(VD->getLocation(), Ty,
10611                              diag::err_abstract_type_in_decl,
10612                              AbstractVariableType)) {
10613     VD->setInvalidDecl();
10614     return;
10615   }
10616 
10617   // Don't bother complaining about constructors or destructors,
10618   // though.
10619 }
10620 
10621 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10622   // If there is no declaration, there was an error parsing it. Just ignore it.
10623   if (!RealDecl)
10624     return;
10625 
10626   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10627     QualType Type = Var->getType();
10628 
10629     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10630     if (isa<DecompositionDecl>(RealDecl)) {
10631       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10632       Var->setInvalidDecl();
10633       return;
10634     }
10635 
10636     if (Type->isUndeducedType() &&
10637         DeduceVariableDeclarationType(Var, false, nullptr))
10638       return;
10639 
10640     // C++11 [class.static.data]p3: A static data member can be declared with
10641     // the constexpr specifier; if so, its declaration shall specify
10642     // a brace-or-equal-initializer.
10643     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10644     // the definition of a variable [...] or the declaration of a static data
10645     // member.
10646     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10647         !Var->isThisDeclarationADemotedDefinition()) {
10648       if (Var->isStaticDataMember()) {
10649         // C++1z removes the relevant rule; the in-class declaration is always
10650         // a definition there.
10651         if (!getLangOpts().CPlusPlus1z) {
10652           Diag(Var->getLocation(),
10653                diag::err_constexpr_static_mem_var_requires_init)
10654             << Var->getDeclName();
10655           Var->setInvalidDecl();
10656           return;
10657         }
10658       } else {
10659         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10660         Var->setInvalidDecl();
10661         return;
10662       }
10663     }
10664 
10665     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10666     // definition having the concept specifier is called a variable concept. A
10667     // concept definition refers to [...] a variable concept and its initializer.
10668     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10669       if (VTD->isConcept()) {
10670         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10671         Var->setInvalidDecl();
10672         return;
10673       }
10674     }
10675 
10676     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10677     // be initialized.
10678     if (!Var->isInvalidDecl() &&
10679         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10680         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10681       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10682       Var->setInvalidDecl();
10683       return;
10684     }
10685 
10686     switch (Var->isThisDeclarationADefinition()) {
10687     case VarDecl::Definition:
10688       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10689         break;
10690 
10691       // We have an out-of-line definition of a static data member
10692       // that has an in-class initializer, so we type-check this like
10693       // a declaration.
10694       //
10695       // Fall through
10696 
10697     case VarDecl::DeclarationOnly:
10698       // It's only a declaration.
10699 
10700       // Block scope. C99 6.7p7: If an identifier for an object is
10701       // declared with no linkage (C99 6.2.2p6), the type for the
10702       // object shall be complete.
10703       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10704           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10705           RequireCompleteType(Var->getLocation(), Type,
10706                               diag::err_typecheck_decl_incomplete_type))
10707         Var->setInvalidDecl();
10708 
10709       // Make sure that the type is not abstract.
10710       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10711           RequireNonAbstractType(Var->getLocation(), Type,
10712                                  diag::err_abstract_type_in_decl,
10713                                  AbstractVariableType))
10714         Var->setInvalidDecl();
10715       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10716           Var->getStorageClass() == SC_PrivateExtern) {
10717         Diag(Var->getLocation(), diag::warn_private_extern);
10718         Diag(Var->getLocation(), diag::note_private_extern);
10719       }
10720 
10721       return;
10722 
10723     case VarDecl::TentativeDefinition:
10724       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10725       // object that has file scope without an initializer, and without a
10726       // storage-class specifier or with the storage-class specifier "static",
10727       // constitutes a tentative definition. Note: A tentative definition with
10728       // external linkage is valid (C99 6.2.2p5).
10729       if (!Var->isInvalidDecl()) {
10730         if (const IncompleteArrayType *ArrayT
10731                                     = Context.getAsIncompleteArrayType(Type)) {
10732           if (RequireCompleteType(Var->getLocation(),
10733                                   ArrayT->getElementType(),
10734                                   diag::err_illegal_decl_array_incomplete_type))
10735             Var->setInvalidDecl();
10736         } else if (Var->getStorageClass() == SC_Static) {
10737           // C99 6.9.2p3: If the declaration of an identifier for an object is
10738           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10739           // declared type shall not be an incomplete type.
10740           // NOTE: code such as the following
10741           //     static struct s;
10742           //     struct s { int a; };
10743           // is accepted by gcc. Hence here we issue a warning instead of
10744           // an error and we do not invalidate the static declaration.
10745           // NOTE: to avoid multiple warnings, only check the first declaration.
10746           if (Var->isFirstDecl())
10747             RequireCompleteType(Var->getLocation(), Type,
10748                                 diag::ext_typecheck_decl_incomplete_type);
10749         }
10750       }
10751 
10752       // Record the tentative definition; we're done.
10753       if (!Var->isInvalidDecl())
10754         TentativeDefinitions.push_back(Var);
10755       return;
10756     }
10757 
10758     // Provide a specific diagnostic for uninitialized variable
10759     // definitions with incomplete array type.
10760     if (Type->isIncompleteArrayType()) {
10761       Diag(Var->getLocation(),
10762            diag::err_typecheck_incomplete_array_needs_initializer);
10763       Var->setInvalidDecl();
10764       return;
10765     }
10766 
10767     // Provide a specific diagnostic for uninitialized variable
10768     // definitions with reference type.
10769     if (Type->isReferenceType()) {
10770       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10771         << Var->getDeclName()
10772         << SourceRange(Var->getLocation(), Var->getLocation());
10773       Var->setInvalidDecl();
10774       return;
10775     }
10776 
10777     // Do not attempt to type-check the default initializer for a
10778     // variable with dependent type.
10779     if (Type->isDependentType())
10780       return;
10781 
10782     if (Var->isInvalidDecl())
10783       return;
10784 
10785     if (!Var->hasAttr<AliasAttr>()) {
10786       if (RequireCompleteType(Var->getLocation(),
10787                               Context.getBaseElementType(Type),
10788                               diag::err_typecheck_decl_incomplete_type)) {
10789         Var->setInvalidDecl();
10790         return;
10791       }
10792     } else {
10793       return;
10794     }
10795 
10796     // The variable can not have an abstract class type.
10797     if (RequireNonAbstractType(Var->getLocation(), Type,
10798                                diag::err_abstract_type_in_decl,
10799                                AbstractVariableType)) {
10800       Var->setInvalidDecl();
10801       return;
10802     }
10803 
10804     // Check for jumps past the implicit initializer.  C++0x
10805     // clarifies that this applies to a "variable with automatic
10806     // storage duration", not a "local variable".
10807     // C++11 [stmt.dcl]p3
10808     //   A program that jumps from a point where a variable with automatic
10809     //   storage duration is not in scope to a point where it is in scope is
10810     //   ill-formed unless the variable has scalar type, class type with a
10811     //   trivial default constructor and a trivial destructor, a cv-qualified
10812     //   version of one of these types, or an array of one of the preceding
10813     //   types and is declared without an initializer.
10814     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10815       if (const RecordType *Record
10816             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10817         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10818         // Mark the function for further checking even if the looser rules of
10819         // C++11 do not require such checks, so that we can diagnose
10820         // incompatibilities with C++98.
10821         if (!CXXRecord->isPOD())
10822           getCurFunction()->setHasBranchProtectedScope();
10823       }
10824     }
10825 
10826     // C++03 [dcl.init]p9:
10827     //   If no initializer is specified for an object, and the
10828     //   object is of (possibly cv-qualified) non-POD class type (or
10829     //   array thereof), the object shall be default-initialized; if
10830     //   the object is of const-qualified type, the underlying class
10831     //   type shall have a user-declared default
10832     //   constructor. Otherwise, if no initializer is specified for
10833     //   a non- static object, the object and its subobjects, if
10834     //   any, have an indeterminate initial value); if the object
10835     //   or any of its subobjects are of const-qualified type, the
10836     //   program is ill-formed.
10837     // C++0x [dcl.init]p11:
10838     //   If no initializer is specified for an object, the object is
10839     //   default-initialized; [...].
10840     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10841     InitializationKind Kind
10842       = InitializationKind::CreateDefault(Var->getLocation());
10843 
10844     InitializationSequence InitSeq(*this, Entity, Kind, None);
10845     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10846     if (Init.isInvalid())
10847       Var->setInvalidDecl();
10848     else if (Init.get()) {
10849       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10850       // This is important for template substitution.
10851       Var->setInitStyle(VarDecl::CallInit);
10852     }
10853 
10854     CheckCompleteVariableDeclaration(Var);
10855   }
10856 }
10857 
10858 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10859   // If there is no declaration, there was an error parsing it. Ignore it.
10860   if (!D)
10861     return;
10862 
10863   VarDecl *VD = dyn_cast<VarDecl>(D);
10864   if (!VD) {
10865     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10866     D->setInvalidDecl();
10867     return;
10868   }
10869 
10870   VD->setCXXForRangeDecl(true);
10871 
10872   // for-range-declaration cannot be given a storage class specifier.
10873   int Error = -1;
10874   switch (VD->getStorageClass()) {
10875   case SC_None:
10876     break;
10877   case SC_Extern:
10878     Error = 0;
10879     break;
10880   case SC_Static:
10881     Error = 1;
10882     break;
10883   case SC_PrivateExtern:
10884     Error = 2;
10885     break;
10886   case SC_Auto:
10887     Error = 3;
10888     break;
10889   case SC_Register:
10890     Error = 4;
10891     break;
10892   }
10893   if (Error != -1) {
10894     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10895       << VD->getDeclName() << Error;
10896     D->setInvalidDecl();
10897   }
10898 }
10899 
10900 StmtResult
10901 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10902                                  IdentifierInfo *Ident,
10903                                  ParsedAttributes &Attrs,
10904                                  SourceLocation AttrEnd) {
10905   // C++1y [stmt.iter]p1:
10906   //   A range-based for statement of the form
10907   //      for ( for-range-identifier : for-range-initializer ) statement
10908   //   is equivalent to
10909   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10910   DeclSpec DS(Attrs.getPool().getFactory());
10911 
10912   const char *PrevSpec;
10913   unsigned DiagID;
10914   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10915                      getPrintingPolicy());
10916 
10917   Declarator D(DS, Declarator::ForContext);
10918   D.SetIdentifier(Ident, IdentLoc);
10919   D.takeAttributes(Attrs, AttrEnd);
10920 
10921   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10922   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10923                 EmptyAttrs, IdentLoc);
10924   Decl *Var = ActOnDeclarator(S, D);
10925   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10926   FinalizeDeclaration(Var);
10927   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10928                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10929 }
10930 
10931 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10932   if (var->isInvalidDecl()) return;
10933 
10934   if (getLangOpts().OpenCL) {
10935     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10936     // initialiser
10937     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10938         !var->hasInit()) {
10939       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10940           << 1 /*Init*/;
10941       var->setInvalidDecl();
10942       return;
10943     }
10944   }
10945 
10946   // In Objective-C, don't allow jumps past the implicit initialization of a
10947   // local retaining variable.
10948   if (getLangOpts().ObjC1 &&
10949       var->hasLocalStorage()) {
10950     switch (var->getType().getObjCLifetime()) {
10951     case Qualifiers::OCL_None:
10952     case Qualifiers::OCL_ExplicitNone:
10953     case Qualifiers::OCL_Autoreleasing:
10954       break;
10955 
10956     case Qualifiers::OCL_Weak:
10957     case Qualifiers::OCL_Strong:
10958       getCurFunction()->setHasBranchProtectedScope();
10959       break;
10960     }
10961   }
10962 
10963   // Warn about externally-visible variables being defined without a
10964   // prior declaration.  We only want to do this for global
10965   // declarations, but we also specifically need to avoid doing it for
10966   // class members because the linkage of an anonymous class can
10967   // change if it's later given a typedef name.
10968   if (var->isThisDeclarationADefinition() &&
10969       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10970       var->isExternallyVisible() && var->hasLinkage() &&
10971       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10972                                   var->getLocation())) {
10973     // Find a previous declaration that's not a definition.
10974     VarDecl *prev = var->getPreviousDecl();
10975     while (prev && prev->isThisDeclarationADefinition())
10976       prev = prev->getPreviousDecl();
10977 
10978     if (!prev)
10979       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10980   }
10981 
10982   // Cache the result of checking for constant initialization.
10983   Optional<bool> CacheHasConstInit;
10984   const Expr *CacheCulprit;
10985   auto checkConstInit = [&]() mutable {
10986     if (!CacheHasConstInit)
10987       CacheHasConstInit = var->getInit()->isConstantInitializer(
10988             Context, var->getType()->isReferenceType(), &CacheCulprit);
10989     return *CacheHasConstInit;
10990   };
10991 
10992   if (var->getTLSKind() == VarDecl::TLS_Static) {
10993     if (var->getType().isDestructedType()) {
10994       // GNU C++98 edits for __thread, [basic.start.term]p3:
10995       //   The type of an object with thread storage duration shall not
10996       //   have a non-trivial destructor.
10997       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10998       if (getLangOpts().CPlusPlus11)
10999         Diag(var->getLocation(), diag::note_use_thread_local);
11000     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11001       if (!checkConstInit()) {
11002         // GNU C++98 edits for __thread, [basic.start.init]p4:
11003         //   An object of thread storage duration shall not require dynamic
11004         //   initialization.
11005         // FIXME: Need strict checking here.
11006         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11007           << CacheCulprit->getSourceRange();
11008         if (getLangOpts().CPlusPlus11)
11009           Diag(var->getLocation(), diag::note_use_thread_local);
11010       }
11011     }
11012   }
11013 
11014   // Apply section attributes and pragmas to global variables.
11015   bool GlobalStorage = var->hasGlobalStorage();
11016   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11017       !inTemplateInstantiation()) {
11018     PragmaStack<StringLiteral *> *Stack = nullptr;
11019     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11020     if (var->getType().isConstQualified())
11021       Stack = &ConstSegStack;
11022     else if (!var->getInit()) {
11023       Stack = &BSSSegStack;
11024       SectionFlags |= ASTContext::PSF_Write;
11025     } else {
11026       Stack = &DataSegStack;
11027       SectionFlags |= ASTContext::PSF_Write;
11028     }
11029     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11030       var->addAttr(SectionAttr::CreateImplicit(
11031           Context, SectionAttr::Declspec_allocate,
11032           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11033     }
11034     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11035       if (UnifySection(SA->getName(), SectionFlags, var))
11036         var->dropAttr<SectionAttr>();
11037 
11038     // Apply the init_seg attribute if this has an initializer.  If the
11039     // initializer turns out to not be dynamic, we'll end up ignoring this
11040     // attribute.
11041     if (CurInitSeg && var->getInit())
11042       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11043                                                CurInitSegLoc));
11044   }
11045 
11046   // All the following checks are C++ only.
11047   if (!getLangOpts().CPlusPlus) {
11048       // If this variable must be emitted, add it as an initializer for the
11049       // current module.
11050      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11051        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11052      return;
11053   }
11054 
11055   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11056     CheckCompleteDecompositionDeclaration(DD);
11057 
11058   QualType type = var->getType();
11059   if (type->isDependentType()) return;
11060 
11061   // __block variables might require us to capture a copy-initializer.
11062   if (var->hasAttr<BlocksAttr>()) {
11063     // It's currently invalid to ever have a __block variable with an
11064     // array type; should we diagnose that here?
11065 
11066     // Regardless, we don't want to ignore array nesting when
11067     // constructing this copy.
11068     if (type->isStructureOrClassType()) {
11069       EnterExpressionEvaluationContext scope(
11070           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11071       SourceLocation poi = var->getLocation();
11072       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11073       ExprResult result
11074         = PerformMoveOrCopyInitialization(
11075             InitializedEntity::InitializeBlock(poi, type, false),
11076             var, var->getType(), varRef, /*AllowNRVO=*/true);
11077       if (!result.isInvalid()) {
11078         result = MaybeCreateExprWithCleanups(result);
11079         Expr *init = result.getAs<Expr>();
11080         Context.setBlockVarCopyInits(var, init);
11081       }
11082     }
11083   }
11084 
11085   Expr *Init = var->getInit();
11086   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11087   QualType baseType = Context.getBaseElementType(type);
11088 
11089   if (!var->getDeclContext()->isDependentContext() &&
11090       Init && !Init->isValueDependent()) {
11091 
11092     if (var->isConstexpr()) {
11093       SmallVector<PartialDiagnosticAt, 8> Notes;
11094       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11095         SourceLocation DiagLoc = var->getLocation();
11096         // If the note doesn't add any useful information other than a source
11097         // location, fold it into the primary diagnostic.
11098         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11099               diag::note_invalid_subexpr_in_const_expr) {
11100           DiagLoc = Notes[0].first;
11101           Notes.clear();
11102         }
11103         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11104           << var << Init->getSourceRange();
11105         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11106           Diag(Notes[I].first, Notes[I].second);
11107       }
11108     } else if (var->isUsableInConstantExpressions(Context)) {
11109       // Check whether the initializer of a const variable of integral or
11110       // enumeration type is an ICE now, since we can't tell whether it was
11111       // initialized by a constant expression if we check later.
11112       var->checkInitIsICE();
11113     }
11114 
11115     // Don't emit further diagnostics about constexpr globals since they
11116     // were just diagnosed.
11117     if (!var->isConstexpr() && GlobalStorage &&
11118             var->hasAttr<RequireConstantInitAttr>()) {
11119       // FIXME: Need strict checking in C++03 here.
11120       bool DiagErr = getLangOpts().CPlusPlus11
11121           ? !var->checkInitIsICE() : !checkConstInit();
11122       if (DiagErr) {
11123         auto attr = var->getAttr<RequireConstantInitAttr>();
11124         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11125           << Init->getSourceRange();
11126         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11127           << attr->getRange();
11128         if (getLangOpts().CPlusPlus11) {
11129           APValue Value;
11130           SmallVector<PartialDiagnosticAt, 8> Notes;
11131           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11132           for (auto &it : Notes)
11133             Diag(it.first, it.second);
11134         } else {
11135           Diag(CacheCulprit->getExprLoc(),
11136                diag::note_invalid_subexpr_in_const_expr)
11137               << CacheCulprit->getSourceRange();
11138         }
11139       }
11140     }
11141     else if (!var->isConstexpr() && IsGlobal &&
11142              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11143                                     var->getLocation())) {
11144       // Warn about globals which don't have a constant initializer.  Don't
11145       // warn about globals with a non-trivial destructor because we already
11146       // warned about them.
11147       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11148       if (!(RD && !RD->hasTrivialDestructor())) {
11149         if (!checkConstInit())
11150           Diag(var->getLocation(), diag::warn_global_constructor)
11151             << Init->getSourceRange();
11152       }
11153     }
11154   }
11155 
11156   // Require the destructor.
11157   if (const RecordType *recordType = baseType->getAs<RecordType>())
11158     FinalizeVarWithDestructor(var, recordType);
11159 
11160   // If this variable must be emitted, add it as an initializer for the current
11161   // module.
11162   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11163     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11164 }
11165 
11166 /// \brief Determines if a variable's alignment is dependent.
11167 static bool hasDependentAlignment(VarDecl *VD) {
11168   if (VD->getType()->isDependentType())
11169     return true;
11170   for (auto *I : VD->specific_attrs<AlignedAttr>())
11171     if (I->isAlignmentDependent())
11172       return true;
11173   return false;
11174 }
11175 
11176 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11177 /// any semantic actions necessary after any initializer has been attached.
11178 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11179   // Note that we are no longer parsing the initializer for this declaration.
11180   ParsingInitForAutoVars.erase(ThisDecl);
11181 
11182   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11183   if (!VD)
11184     return;
11185 
11186   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11187   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11188       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11189     if (PragmaClangBSSSection.Valid)
11190       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11191                                                             PragmaClangBSSSection.SectionName,
11192                                                             PragmaClangBSSSection.PragmaLocation));
11193     if (PragmaClangDataSection.Valid)
11194       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11195                                                              PragmaClangDataSection.SectionName,
11196                                                              PragmaClangDataSection.PragmaLocation));
11197     if (PragmaClangRodataSection.Valid)
11198       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11199                                                                PragmaClangRodataSection.SectionName,
11200                                                                PragmaClangRodataSection.PragmaLocation));
11201   }
11202 
11203   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11204     for (auto *BD : DD->bindings()) {
11205       FinalizeDeclaration(BD);
11206     }
11207   }
11208 
11209   checkAttributesAfterMerging(*this, *VD);
11210 
11211   // Perform TLS alignment check here after attributes attached to the variable
11212   // which may affect the alignment have been processed. Only perform the check
11213   // if the target has a maximum TLS alignment (zero means no constraints).
11214   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11215     // Protect the check so that it's not performed on dependent types and
11216     // dependent alignments (we can't determine the alignment in that case).
11217     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11218         !VD->isInvalidDecl()) {
11219       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11220       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11221         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11222           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11223           << (unsigned)MaxAlignChars.getQuantity();
11224       }
11225     }
11226   }
11227 
11228   if (VD->isStaticLocal()) {
11229     if (FunctionDecl *FD =
11230             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11231       // Static locals inherit dll attributes from their function.
11232       if (Attr *A = getDLLAttr(FD)) {
11233         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11234         NewAttr->setInherited(true);
11235         VD->addAttr(NewAttr);
11236       }
11237       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11238       // function, only __shared__ variables may be declared with
11239       // static storage class.
11240       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11241           CUDADiagIfDeviceCode(VD->getLocation(),
11242                                diag::err_device_static_local_var)
11243               << CurrentCUDATarget())
11244         VD->setInvalidDecl();
11245     }
11246   }
11247 
11248   // Perform check for initializers of device-side global variables.
11249   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11250   // 7.5). We must also apply the same checks to all __shared__
11251   // variables whether they are local or not. CUDA also allows
11252   // constant initializers for __constant__ and __device__ variables.
11253   if (getLangOpts().CUDA) {
11254     const Expr *Init = VD->getInit();
11255     if (Init && VD->hasGlobalStorage()) {
11256       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11257           VD->hasAttr<CUDASharedAttr>()) {
11258         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11259         bool AllowedInit = false;
11260         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11261           AllowedInit =
11262               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11263         // We'll allow constant initializers even if it's a non-empty
11264         // constructor according to CUDA rules. This deviates from NVCC,
11265         // but allows us to handle things like constexpr constructors.
11266         if (!AllowedInit &&
11267             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11268           AllowedInit = VD->getInit()->isConstantInitializer(
11269               Context, VD->getType()->isReferenceType());
11270 
11271         // Also make sure that destructor, if there is one, is empty.
11272         if (AllowedInit)
11273           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11274             AllowedInit =
11275                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11276 
11277         if (!AllowedInit) {
11278           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11279                                       ? diag::err_shared_var_init
11280                                       : diag::err_dynamic_var_init)
11281               << Init->getSourceRange();
11282           VD->setInvalidDecl();
11283         }
11284       } else {
11285         // This is a host-side global variable.  Check that the initializer is
11286         // callable from the host side.
11287         const FunctionDecl *InitFn = nullptr;
11288         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11289           InitFn = CE->getConstructor();
11290         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11291           InitFn = CE->getDirectCallee();
11292         }
11293         if (InitFn) {
11294           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11295           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11296             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11297                 << InitFnTarget << InitFn;
11298             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11299             VD->setInvalidDecl();
11300           }
11301         }
11302       }
11303     }
11304   }
11305 
11306   // Grab the dllimport or dllexport attribute off of the VarDecl.
11307   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11308 
11309   // Imported static data members cannot be defined out-of-line.
11310   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11311     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11312         VD->isThisDeclarationADefinition()) {
11313       // We allow definitions of dllimport class template static data members
11314       // with a warning.
11315       CXXRecordDecl *Context =
11316         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11317       bool IsClassTemplateMember =
11318           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11319           Context->getDescribedClassTemplate();
11320 
11321       Diag(VD->getLocation(),
11322            IsClassTemplateMember
11323                ? diag::warn_attribute_dllimport_static_field_definition
11324                : diag::err_attribute_dllimport_static_field_definition);
11325       Diag(IA->getLocation(), diag::note_attribute);
11326       if (!IsClassTemplateMember)
11327         VD->setInvalidDecl();
11328     }
11329   }
11330 
11331   // dllimport/dllexport variables cannot be thread local, their TLS index
11332   // isn't exported with the variable.
11333   if (DLLAttr && VD->getTLSKind()) {
11334     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11335     if (F && getDLLAttr(F)) {
11336       assert(VD->isStaticLocal());
11337       // But if this is a static local in a dlimport/dllexport function, the
11338       // function will never be inlined, which means the var would never be
11339       // imported, so having it marked import/export is safe.
11340     } else {
11341       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11342                                                                     << DLLAttr;
11343       VD->setInvalidDecl();
11344     }
11345   }
11346 
11347   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11348     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11349       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11350       VD->dropAttr<UsedAttr>();
11351     }
11352   }
11353 
11354   const DeclContext *DC = VD->getDeclContext();
11355   // If there's a #pragma GCC visibility in scope, and this isn't a class
11356   // member, set the visibility of this variable.
11357   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11358     AddPushedVisibilityAttribute(VD);
11359 
11360   // FIXME: Warn on unused var template partial specializations.
11361   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11362     MarkUnusedFileScopedDecl(VD);
11363 
11364   // Now we have parsed the initializer and can update the table of magic
11365   // tag values.
11366   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11367       !VD->getType()->isIntegralOrEnumerationType())
11368     return;
11369 
11370   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11371     const Expr *MagicValueExpr = VD->getInit();
11372     if (!MagicValueExpr) {
11373       continue;
11374     }
11375     llvm::APSInt MagicValueInt;
11376     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11377       Diag(I->getRange().getBegin(),
11378            diag::err_type_tag_for_datatype_not_ice)
11379         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11380       continue;
11381     }
11382     if (MagicValueInt.getActiveBits() > 64) {
11383       Diag(I->getRange().getBegin(),
11384            diag::err_type_tag_for_datatype_too_large)
11385         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11386       continue;
11387     }
11388     uint64_t MagicValue = MagicValueInt.getZExtValue();
11389     RegisterTypeTagForDatatype(I->getArgumentKind(),
11390                                MagicValue,
11391                                I->getMatchingCType(),
11392                                I->getLayoutCompatible(),
11393                                I->getMustBeNull());
11394   }
11395 }
11396 
11397 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11398   auto *VD = dyn_cast<VarDecl>(DD);
11399   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11400 }
11401 
11402 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11403                                                    ArrayRef<Decl *> Group) {
11404   SmallVector<Decl*, 8> Decls;
11405 
11406   if (DS.isTypeSpecOwned())
11407     Decls.push_back(DS.getRepAsDecl());
11408 
11409   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11410   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11411   bool DiagnosedMultipleDecomps = false;
11412   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11413   bool DiagnosedNonDeducedAuto = false;
11414 
11415   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11416     if (Decl *D = Group[i]) {
11417       // For declarators, there are some additional syntactic-ish checks we need
11418       // to perform.
11419       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11420         if (!FirstDeclaratorInGroup)
11421           FirstDeclaratorInGroup = DD;
11422         if (!FirstDecompDeclaratorInGroup)
11423           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11424         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11425             !hasDeducedAuto(DD))
11426           FirstNonDeducedAutoInGroup = DD;
11427 
11428         if (FirstDeclaratorInGroup != DD) {
11429           // A decomposition declaration cannot be combined with any other
11430           // declaration in the same group.
11431           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11432             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11433                  diag::err_decomp_decl_not_alone)
11434                 << FirstDeclaratorInGroup->getSourceRange()
11435                 << DD->getSourceRange();
11436             DiagnosedMultipleDecomps = true;
11437           }
11438 
11439           // A declarator that uses 'auto' in any way other than to declare a
11440           // variable with a deduced type cannot be combined with any other
11441           // declarator in the same group.
11442           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11443             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11444                  diag::err_auto_non_deduced_not_alone)
11445                 << FirstNonDeducedAutoInGroup->getType()
11446                        ->hasAutoForTrailingReturnType()
11447                 << FirstDeclaratorInGroup->getSourceRange()
11448                 << DD->getSourceRange();
11449             DiagnosedNonDeducedAuto = true;
11450           }
11451         }
11452       }
11453 
11454       Decls.push_back(D);
11455     }
11456   }
11457 
11458   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11459     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11460       handleTagNumbering(Tag, S);
11461       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11462           getLangOpts().CPlusPlus)
11463         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11464     }
11465   }
11466 
11467   return BuildDeclaratorGroup(Decls);
11468 }
11469 
11470 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11471 /// group, performing any necessary semantic checking.
11472 Sema::DeclGroupPtrTy
11473 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11474   // C++14 [dcl.spec.auto]p7: (DR1347)
11475   //   If the type that replaces the placeholder type is not the same in each
11476   //   deduction, the program is ill-formed.
11477   if (Group.size() > 1) {
11478     QualType Deduced;
11479     VarDecl *DeducedDecl = nullptr;
11480     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11481       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11482       if (!D || D->isInvalidDecl())
11483         break;
11484       DeducedType *DT = D->getType()->getContainedDeducedType();
11485       if (!DT || DT->getDeducedType().isNull())
11486         continue;
11487       if (Deduced.isNull()) {
11488         Deduced = DT->getDeducedType();
11489         DeducedDecl = D;
11490       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11491         auto *AT = dyn_cast<AutoType>(DT);
11492         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11493              diag::err_auto_different_deductions)
11494           << (AT ? (unsigned)AT->getKeyword() : 3)
11495           << Deduced << DeducedDecl->getDeclName()
11496           << DT->getDeducedType() << D->getDeclName()
11497           << DeducedDecl->getInit()->getSourceRange()
11498           << D->getInit()->getSourceRange();
11499         D->setInvalidDecl();
11500         break;
11501       }
11502     }
11503   }
11504 
11505   ActOnDocumentableDecls(Group);
11506 
11507   return DeclGroupPtrTy::make(
11508       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11509 }
11510 
11511 void Sema::ActOnDocumentableDecl(Decl *D) {
11512   ActOnDocumentableDecls(D);
11513 }
11514 
11515 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11516   // Don't parse the comment if Doxygen diagnostics are ignored.
11517   if (Group.empty() || !Group[0])
11518     return;
11519 
11520   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11521                       Group[0]->getLocation()) &&
11522       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11523                       Group[0]->getLocation()))
11524     return;
11525 
11526   if (Group.size() >= 2) {
11527     // This is a decl group.  Normally it will contain only declarations
11528     // produced from declarator list.  But in case we have any definitions or
11529     // additional declaration references:
11530     //   'typedef struct S {} S;'
11531     //   'typedef struct S *S;'
11532     //   'struct S *pS;'
11533     // FinalizeDeclaratorGroup adds these as separate declarations.
11534     Decl *MaybeTagDecl = Group[0];
11535     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11536       Group = Group.slice(1);
11537     }
11538   }
11539 
11540   // See if there are any new comments that are not attached to a decl.
11541   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11542   if (!Comments.empty() &&
11543       !Comments.back()->isAttached()) {
11544     // There is at least one comment that not attached to a decl.
11545     // Maybe it should be attached to one of these decls?
11546     //
11547     // Note that this way we pick up not only comments that precede the
11548     // declaration, but also comments that *follow* the declaration -- thanks to
11549     // the lookahead in the lexer: we've consumed the semicolon and looked
11550     // ahead through comments.
11551     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11552       Context.getCommentForDecl(Group[i], &PP);
11553   }
11554 }
11555 
11556 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11557 /// to introduce parameters into function prototype scope.
11558 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11559   const DeclSpec &DS = D.getDeclSpec();
11560 
11561   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11562 
11563   // C++03 [dcl.stc]p2 also permits 'auto'.
11564   StorageClass SC = SC_None;
11565   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11566     SC = SC_Register;
11567   } else if (getLangOpts().CPlusPlus &&
11568              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11569     SC = SC_Auto;
11570   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11571     Diag(DS.getStorageClassSpecLoc(),
11572          diag::err_invalid_storage_class_in_func_decl);
11573     D.getMutableDeclSpec().ClearStorageClassSpecs();
11574   }
11575 
11576   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11577     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11578       << DeclSpec::getSpecifierName(TSCS);
11579   if (DS.isInlineSpecified())
11580     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11581         << getLangOpts().CPlusPlus1z;
11582   if (DS.isConstexprSpecified())
11583     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11584       << 0;
11585   if (DS.isConceptSpecified())
11586     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11587 
11588   DiagnoseFunctionSpecifiers(DS);
11589 
11590   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11591   QualType parmDeclType = TInfo->getType();
11592 
11593   if (getLangOpts().CPlusPlus) {
11594     // Check that there are no default arguments inside the type of this
11595     // parameter.
11596     CheckExtraCXXDefaultArguments(D);
11597 
11598     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11599     if (D.getCXXScopeSpec().isSet()) {
11600       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11601         << D.getCXXScopeSpec().getRange();
11602       D.getCXXScopeSpec().clear();
11603     }
11604   }
11605 
11606   // Ensure we have a valid name
11607   IdentifierInfo *II = nullptr;
11608   if (D.hasName()) {
11609     II = D.getIdentifier();
11610     if (!II) {
11611       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11612         << GetNameForDeclarator(D).getName();
11613       D.setInvalidType(true);
11614     }
11615   }
11616 
11617   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11618   if (II) {
11619     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11620                    ForRedeclaration);
11621     LookupName(R, S);
11622     if (R.isSingleResult()) {
11623       NamedDecl *PrevDecl = R.getFoundDecl();
11624       if (PrevDecl->isTemplateParameter()) {
11625         // Maybe we will complain about the shadowed template parameter.
11626         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11627         // Just pretend that we didn't see the previous declaration.
11628         PrevDecl = nullptr;
11629       } else if (S->isDeclScope(PrevDecl)) {
11630         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11631         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11632 
11633         // Recover by removing the name
11634         II = nullptr;
11635         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11636         D.setInvalidType(true);
11637       }
11638     }
11639   }
11640 
11641   // Temporarily put parameter variables in the translation unit, not
11642   // the enclosing context.  This prevents them from accidentally
11643   // looking like class members in C++.
11644   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11645                                     D.getLocStart(),
11646                                     D.getIdentifierLoc(), II,
11647                                     parmDeclType, TInfo,
11648                                     SC);
11649 
11650   if (D.isInvalidType())
11651     New->setInvalidDecl();
11652 
11653   assert(S->isFunctionPrototypeScope());
11654   assert(S->getFunctionPrototypeDepth() >= 1);
11655   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11656                     S->getNextFunctionPrototypeIndex());
11657 
11658   // Add the parameter declaration into this scope.
11659   S->AddDecl(New);
11660   if (II)
11661     IdResolver.AddDecl(New);
11662 
11663   ProcessDeclAttributes(S, New, D);
11664 
11665   if (D.getDeclSpec().isModulePrivateSpecified())
11666     Diag(New->getLocation(), diag::err_module_private_local)
11667       << 1 << New->getDeclName()
11668       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11669       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11670 
11671   if (New->hasAttr<BlocksAttr>()) {
11672     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11673   }
11674   return New;
11675 }
11676 
11677 /// \brief Synthesizes a variable for a parameter arising from a
11678 /// typedef.
11679 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11680                                               SourceLocation Loc,
11681                                               QualType T) {
11682   /* FIXME: setting StartLoc == Loc.
11683      Would it be worth to modify callers so as to provide proper source
11684      location for the unnamed parameters, embedding the parameter's type? */
11685   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11686                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11687                                            SC_None, nullptr);
11688   Param->setImplicit();
11689   return Param;
11690 }
11691 
11692 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11693   // Don't diagnose unused-parameter errors in template instantiations; we
11694   // will already have done so in the template itself.
11695   if (inTemplateInstantiation())
11696     return;
11697 
11698   for (const ParmVarDecl *Parameter : Parameters) {
11699     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11700         !Parameter->hasAttr<UnusedAttr>()) {
11701       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11702         << Parameter->getDeclName();
11703     }
11704   }
11705 }
11706 
11707 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11708     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11709   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11710     return;
11711 
11712   // Warn if the return value is pass-by-value and larger than the specified
11713   // threshold.
11714   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11715     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11716     if (Size > LangOpts.NumLargeByValueCopy)
11717       Diag(D->getLocation(), diag::warn_return_value_size)
11718           << D->getDeclName() << Size;
11719   }
11720 
11721   // Warn if any parameter is pass-by-value and larger than the specified
11722   // threshold.
11723   for (const ParmVarDecl *Parameter : Parameters) {
11724     QualType T = Parameter->getType();
11725     if (T->isDependentType() || !T.isPODType(Context))
11726       continue;
11727     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11728     if (Size > LangOpts.NumLargeByValueCopy)
11729       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11730           << Parameter->getDeclName() << Size;
11731   }
11732 }
11733 
11734 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11735                                   SourceLocation NameLoc, IdentifierInfo *Name,
11736                                   QualType T, TypeSourceInfo *TSInfo,
11737                                   StorageClass SC) {
11738   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11739   if (getLangOpts().ObjCAutoRefCount &&
11740       T.getObjCLifetime() == Qualifiers::OCL_None &&
11741       T->isObjCLifetimeType()) {
11742 
11743     Qualifiers::ObjCLifetime lifetime;
11744 
11745     // Special cases for arrays:
11746     //   - if it's const, use __unsafe_unretained
11747     //   - otherwise, it's an error
11748     if (T->isArrayType()) {
11749       if (!T.isConstQualified()) {
11750         DelayedDiagnostics.add(
11751             sema::DelayedDiagnostic::makeForbiddenType(
11752             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11753       }
11754       lifetime = Qualifiers::OCL_ExplicitNone;
11755     } else {
11756       lifetime = T->getObjCARCImplicitLifetime();
11757     }
11758     T = Context.getLifetimeQualifiedType(T, lifetime);
11759   }
11760 
11761   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11762                                          Context.getAdjustedParameterType(T),
11763                                          TSInfo, SC, nullptr);
11764 
11765   // Parameters can not be abstract class types.
11766   // For record types, this is done by the AbstractClassUsageDiagnoser once
11767   // the class has been completely parsed.
11768   if (!CurContext->isRecord() &&
11769       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11770                              AbstractParamType))
11771     New->setInvalidDecl();
11772 
11773   // Parameter declarators cannot be interface types. All ObjC objects are
11774   // passed by reference.
11775   if (T->isObjCObjectType()) {
11776     SourceLocation TypeEndLoc =
11777         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11778     Diag(NameLoc,
11779          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11780       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11781     T = Context.getObjCObjectPointerType(T);
11782     New->setType(T);
11783   }
11784 
11785   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11786   // duration shall not be qualified by an address-space qualifier."
11787   // Since all parameters have automatic store duration, they can not have
11788   // an address space.
11789   if (T.getAddressSpace() != 0) {
11790     // OpenCL allows function arguments declared to be an array of a type
11791     // to be qualified with an address space.
11792     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11793       Diag(NameLoc, diag::err_arg_with_address_space);
11794       New->setInvalidDecl();
11795     }
11796   }
11797 
11798   return New;
11799 }
11800 
11801 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11802                                            SourceLocation LocAfterDecls) {
11803   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11804 
11805   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11806   // for a K&R function.
11807   if (!FTI.hasPrototype) {
11808     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11809       --i;
11810       if (FTI.Params[i].Param == nullptr) {
11811         SmallString<256> Code;
11812         llvm::raw_svector_ostream(Code)
11813             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11814         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11815             << FTI.Params[i].Ident
11816             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11817 
11818         // Implicitly declare the argument as type 'int' for lack of a better
11819         // type.
11820         AttributeFactory attrs;
11821         DeclSpec DS(attrs);
11822         const char* PrevSpec; // unused
11823         unsigned DiagID; // unused
11824         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11825                            DiagID, Context.getPrintingPolicy());
11826         // Use the identifier location for the type source range.
11827         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11828         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11829         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11830         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11831         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11832       }
11833     }
11834   }
11835 }
11836 
11837 Decl *
11838 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11839                               MultiTemplateParamsArg TemplateParameterLists,
11840                               SkipBodyInfo *SkipBody) {
11841   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11842   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11843   Scope *ParentScope = FnBodyScope->getParent();
11844 
11845   D.setFunctionDefinitionKind(FDK_Definition);
11846   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11847   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11848 }
11849 
11850 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11851   Consumer.HandleInlineFunctionDefinition(D);
11852 }
11853 
11854 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11855                              const FunctionDecl*& PossibleZeroParamPrototype) {
11856   // Don't warn about invalid declarations.
11857   if (FD->isInvalidDecl())
11858     return false;
11859 
11860   // Or declarations that aren't global.
11861   if (!FD->isGlobal())
11862     return false;
11863 
11864   // Don't warn about C++ member functions.
11865   if (isa<CXXMethodDecl>(FD))
11866     return false;
11867 
11868   // Don't warn about 'main'.
11869   if (FD->isMain())
11870     return false;
11871 
11872   // Don't warn about inline functions.
11873   if (FD->isInlined())
11874     return false;
11875 
11876   // Don't warn about function templates.
11877   if (FD->getDescribedFunctionTemplate())
11878     return false;
11879 
11880   // Don't warn about function template specializations.
11881   if (FD->isFunctionTemplateSpecialization())
11882     return false;
11883 
11884   // Don't warn for OpenCL kernels.
11885   if (FD->hasAttr<OpenCLKernelAttr>())
11886     return false;
11887 
11888   // Don't warn on explicitly deleted functions.
11889   if (FD->isDeleted())
11890     return false;
11891 
11892   bool MissingPrototype = true;
11893   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11894        Prev; Prev = Prev->getPreviousDecl()) {
11895     // Ignore any declarations that occur in function or method
11896     // scope, because they aren't visible from the header.
11897     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11898       continue;
11899 
11900     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11901     if (FD->getNumParams() == 0)
11902       PossibleZeroParamPrototype = Prev;
11903     break;
11904   }
11905 
11906   return MissingPrototype;
11907 }
11908 
11909 void
11910 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11911                                    const FunctionDecl *EffectiveDefinition,
11912                                    SkipBodyInfo *SkipBody) {
11913   const FunctionDecl *Definition = EffectiveDefinition;
11914   if (!Definition)
11915     if (!FD->isDefined(Definition))
11916       return;
11917 
11918   if (canRedefineFunction(Definition, getLangOpts()))
11919     return;
11920 
11921   // Don't emit an error when this is redifinition of a typo-corrected
11922   // definition.
11923   if (TypoCorrectedFunctionDefinitions.count(Definition))
11924     return;
11925 
11926   // If we don't have a visible definition of the function, and it's inline or
11927   // a template, skip the new definition.
11928   if (SkipBody && !hasVisibleDefinition(Definition) &&
11929       (Definition->getFormalLinkage() == InternalLinkage ||
11930        Definition->isInlined() ||
11931        Definition->getDescribedFunctionTemplate() ||
11932        Definition->getNumTemplateParameterLists())) {
11933     SkipBody->ShouldSkip = true;
11934     if (auto *TD = Definition->getDescribedFunctionTemplate())
11935       makeMergedDefinitionVisible(TD);
11936     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
11937     return;
11938   }
11939 
11940   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11941       Definition->getStorageClass() == SC_Extern)
11942     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11943         << FD->getDeclName() << getLangOpts().CPlusPlus;
11944   else
11945     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11946 
11947   Diag(Definition->getLocation(), diag::note_previous_definition);
11948   FD->setInvalidDecl();
11949 }
11950 
11951 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11952                                    Sema &S) {
11953   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11954 
11955   LambdaScopeInfo *LSI = S.PushLambdaScope();
11956   LSI->CallOperator = CallOperator;
11957   LSI->Lambda = LambdaClass;
11958   LSI->ReturnType = CallOperator->getReturnType();
11959   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11960 
11961   if (LCD == LCD_None)
11962     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11963   else if (LCD == LCD_ByCopy)
11964     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11965   else if (LCD == LCD_ByRef)
11966     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11967   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11968 
11969   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11970   LSI->Mutable = !CallOperator->isConst();
11971 
11972   // Add the captures to the LSI so they can be noted as already
11973   // captured within tryCaptureVar.
11974   auto I = LambdaClass->field_begin();
11975   for (const auto &C : LambdaClass->captures()) {
11976     if (C.capturesVariable()) {
11977       VarDecl *VD = C.getCapturedVar();
11978       if (VD->isInitCapture())
11979         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11980       QualType CaptureType = VD->getType();
11981       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11982       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11983           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11984           /*EllipsisLoc*/C.isPackExpansion()
11985                          ? C.getEllipsisLoc() : SourceLocation(),
11986           CaptureType, /*Expr*/ nullptr);
11987 
11988     } else if (C.capturesThis()) {
11989       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11990                               /*Expr*/ nullptr,
11991                               C.getCaptureKind() == LCK_StarThis);
11992     } else {
11993       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11994     }
11995     ++I;
11996   }
11997 }
11998 
11999 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12000                                     SkipBodyInfo *SkipBody) {
12001   if (!D)
12002     return D;
12003   FunctionDecl *FD = nullptr;
12004 
12005   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12006     FD = FunTmpl->getTemplatedDecl();
12007   else
12008     FD = cast<FunctionDecl>(D);
12009 
12010   // Check for defining attributes before the check for redefinition.
12011   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12012     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12013     FD->dropAttr<AliasAttr>();
12014     FD->setInvalidDecl();
12015   }
12016   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12017     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12018     FD->dropAttr<IFuncAttr>();
12019     FD->setInvalidDecl();
12020   }
12021 
12022   // See if this is a redefinition.
12023   if (!FD->isLateTemplateParsed()) {
12024     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12025 
12026     // If we're skipping the body, we're done. Don't enter the scope.
12027     if (SkipBody && SkipBody->ShouldSkip)
12028       return D;
12029   }
12030 
12031   // Mark this function as "will have a body eventually".  This lets users to
12032   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12033   // this function.
12034   FD->setWillHaveBody();
12035 
12036   // If we are instantiating a generic lambda call operator, push
12037   // a LambdaScopeInfo onto the function stack.  But use the information
12038   // that's already been calculated (ActOnLambdaExpr) to prime the current
12039   // LambdaScopeInfo.
12040   // When the template operator is being specialized, the LambdaScopeInfo,
12041   // has to be properly restored so that tryCaptureVariable doesn't try
12042   // and capture any new variables. In addition when calculating potential
12043   // captures during transformation of nested lambdas, it is necessary to
12044   // have the LSI properly restored.
12045   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12046     assert(inTemplateInstantiation() &&
12047            "There should be an active template instantiation on the stack "
12048            "when instantiating a generic lambda!");
12049     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12050   } else {
12051     // Enter a new function scope
12052     PushFunctionScope();
12053   }
12054 
12055   // Builtin functions cannot be defined.
12056   if (unsigned BuiltinID = FD->getBuiltinID()) {
12057     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12058         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12059       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12060       FD->setInvalidDecl();
12061     }
12062   }
12063 
12064   // The return type of a function definition must be complete
12065   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12066   QualType ResultType = FD->getReturnType();
12067   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12068       !FD->isInvalidDecl() &&
12069       RequireCompleteType(FD->getLocation(), ResultType,
12070                           diag::err_func_def_incomplete_result))
12071     FD->setInvalidDecl();
12072 
12073   if (FnBodyScope)
12074     PushDeclContext(FnBodyScope, FD);
12075 
12076   // Check the validity of our function parameters
12077   CheckParmsForFunctionDef(FD->parameters(),
12078                            /*CheckParameterNames=*/true);
12079 
12080   // Add non-parameter declarations already in the function to the current
12081   // scope.
12082   if (FnBodyScope) {
12083     for (Decl *NPD : FD->decls()) {
12084       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12085       if (!NonParmDecl)
12086         continue;
12087       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12088              "parameters should not be in newly created FD yet");
12089 
12090       // If the decl has a name, make it accessible in the current scope.
12091       if (NonParmDecl->getDeclName())
12092         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12093 
12094       // Similarly, dive into enums and fish their constants out, making them
12095       // accessible in this scope.
12096       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12097         for (auto *EI : ED->enumerators())
12098           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12099       }
12100     }
12101   }
12102 
12103   // Introduce our parameters into the function scope
12104   for (auto Param : FD->parameters()) {
12105     Param->setOwningFunction(FD);
12106 
12107     // If this has an identifier, add it to the scope stack.
12108     if (Param->getIdentifier() && FnBodyScope) {
12109       CheckShadow(FnBodyScope, Param);
12110 
12111       PushOnScopeChains(Param, FnBodyScope);
12112     }
12113   }
12114 
12115   // Ensure that the function's exception specification is instantiated.
12116   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12117     ResolveExceptionSpec(D->getLocation(), FPT);
12118 
12119   // dllimport cannot be applied to non-inline function definitions.
12120   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12121       !FD->isTemplateInstantiation()) {
12122     assert(!FD->hasAttr<DLLExportAttr>());
12123     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12124     FD->setInvalidDecl();
12125     return D;
12126   }
12127   // We want to attach documentation to original Decl (which might be
12128   // a function template).
12129   ActOnDocumentableDecl(D);
12130   if (getCurLexicalContext()->isObjCContainer() &&
12131       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12132       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12133     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12134 
12135   return D;
12136 }
12137 
12138 /// \brief Given the set of return statements within a function body,
12139 /// compute the variables that are subject to the named return value
12140 /// optimization.
12141 ///
12142 /// Each of the variables that is subject to the named return value
12143 /// optimization will be marked as NRVO variables in the AST, and any
12144 /// return statement that has a marked NRVO variable as its NRVO candidate can
12145 /// use the named return value optimization.
12146 ///
12147 /// This function applies a very simplistic algorithm for NRVO: if every return
12148 /// statement in the scope of a variable has the same NRVO candidate, that
12149 /// candidate is an NRVO variable.
12150 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12151   ReturnStmt **Returns = Scope->Returns.data();
12152 
12153   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12154     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12155       if (!NRVOCandidate->isNRVOVariable())
12156         Returns[I]->setNRVOCandidate(nullptr);
12157     }
12158   }
12159 }
12160 
12161 bool Sema::canDelayFunctionBody(const Declarator &D) {
12162   // We can't delay parsing the body of a constexpr function template (yet).
12163   if (D.getDeclSpec().isConstexprSpecified())
12164     return false;
12165 
12166   // We can't delay parsing the body of a function template with a deduced
12167   // return type (yet).
12168   if (D.getDeclSpec().hasAutoTypeSpec()) {
12169     // If the placeholder introduces a non-deduced trailing return type,
12170     // we can still delay parsing it.
12171     if (D.getNumTypeObjects()) {
12172       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12173       if (Outer.Kind == DeclaratorChunk::Function &&
12174           Outer.Fun.hasTrailingReturnType()) {
12175         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12176         return Ty.isNull() || !Ty->isUndeducedType();
12177       }
12178     }
12179     return false;
12180   }
12181 
12182   return true;
12183 }
12184 
12185 bool Sema::canSkipFunctionBody(Decl *D) {
12186   // We cannot skip the body of a function (or function template) which is
12187   // constexpr, since we may need to evaluate its body in order to parse the
12188   // rest of the file.
12189   // We cannot skip the body of a function with an undeduced return type,
12190   // because any callers of that function need to know the type.
12191   if (const FunctionDecl *FD = D->getAsFunction())
12192     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12193       return false;
12194   return Consumer.shouldSkipFunctionBody(D);
12195 }
12196 
12197 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12198   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12199     FD->setHasSkippedBody();
12200   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12201     MD->setHasSkippedBody();
12202   return Decl;
12203 }
12204 
12205 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12206   return ActOnFinishFunctionBody(D, BodyArg, false);
12207 }
12208 
12209 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12210                                     bool IsInstantiation) {
12211   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12212 
12213   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12214   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12215 
12216   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12217     CheckCompletedCoroutineBody(FD, Body);
12218 
12219   if (FD) {
12220     FD->setBody(Body);
12221 
12222     if (getLangOpts().CPlusPlus14) {
12223       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12224           FD->getReturnType()->isUndeducedType()) {
12225         // If the function has a deduced result type but contains no 'return'
12226         // statements, the result type as written must be exactly 'auto', and
12227         // the deduced result type is 'void'.
12228         if (!FD->getReturnType()->getAs<AutoType>()) {
12229           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12230               << FD->getReturnType();
12231           FD->setInvalidDecl();
12232         } else {
12233           // Substitute 'void' for the 'auto' in the type.
12234           TypeLoc ResultType = getReturnTypeLoc(FD);
12235           Context.adjustDeducedFunctionResultType(
12236               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12237         }
12238       }
12239     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12240       // In C++11, we don't use 'auto' deduction rules for lambda call
12241       // operators because we don't support return type deduction.
12242       auto *LSI = getCurLambda();
12243       if (LSI->HasImplicitReturnType) {
12244         deduceClosureReturnType(*LSI);
12245 
12246         // C++11 [expr.prim.lambda]p4:
12247         //   [...] if there are no return statements in the compound-statement
12248         //   [the deduced type is] the type void
12249         QualType RetType =
12250             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12251 
12252         // Update the return type to the deduced type.
12253         const FunctionProtoType *Proto =
12254             FD->getType()->getAs<FunctionProtoType>();
12255         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12256                                             Proto->getExtProtoInfo()));
12257       }
12258     }
12259 
12260     // The only way to be included in UndefinedButUsed is if there is an
12261     // ODR use before the definition. Avoid the expensive map lookup if this
12262     // is the first declaration.
12263     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12264       if (!FD->isExternallyVisible())
12265         UndefinedButUsed.erase(FD);
12266       else if (FD->isInlined() &&
12267                !LangOpts.GNUInline &&
12268                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12269         UndefinedButUsed.erase(FD);
12270     }
12271 
12272     // If the function implicitly returns zero (like 'main') or is naked,
12273     // don't complain about missing return statements.
12274     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12275       WP.disableCheckFallThrough();
12276 
12277     // MSVC permits the use of pure specifier (=0) on function definition,
12278     // defined at class scope, warn about this non-standard construct.
12279     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12280       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12281 
12282     if (!FD->isInvalidDecl()) {
12283       // Don't diagnose unused parameters of defaulted or deleted functions.
12284       if (!FD->isDeleted() && !FD->isDefaulted())
12285         DiagnoseUnusedParameters(FD->parameters());
12286       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12287                                              FD->getReturnType(), FD);
12288 
12289       // If this is a structor, we need a vtable.
12290       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12291         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12292       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12293         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12294 
12295       // Try to apply the named return value optimization. We have to check
12296       // if we can do this here because lambdas keep return statements around
12297       // to deduce an implicit return type.
12298       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12299           !FD->isDependentContext())
12300         computeNRVO(Body, getCurFunction());
12301     }
12302 
12303     // GNU warning -Wmissing-prototypes:
12304     //   Warn if a global function is defined without a previous
12305     //   prototype declaration. This warning is issued even if the
12306     //   definition itself provides a prototype. The aim is to detect
12307     //   global functions that fail to be declared in header files.
12308     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12309     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12310       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12311 
12312       if (PossibleZeroParamPrototype) {
12313         // We found a declaration that is not a prototype,
12314         // but that could be a zero-parameter prototype
12315         if (TypeSourceInfo *TI =
12316                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12317           TypeLoc TL = TI->getTypeLoc();
12318           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12319             Diag(PossibleZeroParamPrototype->getLocation(),
12320                  diag::note_declaration_not_a_prototype)
12321                 << PossibleZeroParamPrototype
12322                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12323         }
12324       }
12325 
12326       // GNU warning -Wstrict-prototypes
12327       //   Warn if K&R function is defined without a previous declaration.
12328       //   This warning is issued only if the definition itself does not provide
12329       //   a prototype. Only K&R definitions do not provide a prototype.
12330       //   An empty list in a function declarator that is part of a definition
12331       //   of that function specifies that the function has no parameters
12332       //   (C99 6.7.5.3p14)
12333       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12334           !LangOpts.CPlusPlus) {
12335         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12336         TypeLoc TL = TI->getTypeLoc();
12337         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12338         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12339       }
12340     }
12341 
12342     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12343       const CXXMethodDecl *KeyFunction;
12344       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12345           MD->isVirtual() &&
12346           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12347           MD == KeyFunction->getCanonicalDecl()) {
12348         // Update the key-function state if necessary for this ABI.
12349         if (FD->isInlined() &&
12350             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12351           Context.setNonKeyFunction(MD);
12352 
12353           // If the newly-chosen key function is already defined, then we
12354           // need to mark the vtable as used retroactively.
12355           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12356           const FunctionDecl *Definition;
12357           if (KeyFunction && KeyFunction->isDefined(Definition))
12358             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12359         } else {
12360           // We just defined they key function; mark the vtable as used.
12361           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12362         }
12363       }
12364     }
12365 
12366     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12367            "Function parsing confused");
12368   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12369     assert(MD == getCurMethodDecl() && "Method parsing confused");
12370     MD->setBody(Body);
12371     if (!MD->isInvalidDecl()) {
12372       DiagnoseUnusedParameters(MD->parameters());
12373       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12374                                              MD->getReturnType(), MD);
12375 
12376       if (Body)
12377         computeNRVO(Body, getCurFunction());
12378     }
12379     if (getCurFunction()->ObjCShouldCallSuper) {
12380       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12381         << MD->getSelector().getAsString();
12382       getCurFunction()->ObjCShouldCallSuper = false;
12383     }
12384     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12385       const ObjCMethodDecl *InitMethod = nullptr;
12386       bool isDesignated =
12387           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12388       assert(isDesignated && InitMethod);
12389       (void)isDesignated;
12390 
12391       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12392         auto IFace = MD->getClassInterface();
12393         if (!IFace)
12394           return false;
12395         auto SuperD = IFace->getSuperClass();
12396         if (!SuperD)
12397           return false;
12398         return SuperD->getIdentifier() ==
12399             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12400       };
12401       // Don't issue this warning for unavailable inits or direct subclasses
12402       // of NSObject.
12403       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12404         Diag(MD->getLocation(),
12405              diag::warn_objc_designated_init_missing_super_call);
12406         Diag(InitMethod->getLocation(),
12407              diag::note_objc_designated_init_marked_here);
12408       }
12409       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12410     }
12411     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12412       // Don't issue this warning for unavaialable inits.
12413       if (!MD->isUnavailable())
12414         Diag(MD->getLocation(),
12415              diag::warn_objc_secondary_init_missing_init_call);
12416       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12417     }
12418   } else {
12419     return nullptr;
12420   }
12421 
12422   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12423     DiagnoseUnguardedAvailabilityViolations(dcl);
12424 
12425   assert(!getCurFunction()->ObjCShouldCallSuper &&
12426          "This should only be set for ObjC methods, which should have been "
12427          "handled in the block above.");
12428 
12429   // Verify and clean out per-function state.
12430   if (Body && (!FD || !FD->isDefaulted())) {
12431     // C++ constructors that have function-try-blocks can't have return
12432     // statements in the handlers of that block. (C++ [except.handle]p14)
12433     // Verify this.
12434     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12435       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12436 
12437     // Verify that gotos and switch cases don't jump into scopes illegally.
12438     if (getCurFunction()->NeedsScopeChecking() &&
12439         !PP.isCodeCompletionEnabled())
12440       DiagnoseInvalidJumps(Body);
12441 
12442     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12443       if (!Destructor->getParent()->isDependentType())
12444         CheckDestructor(Destructor);
12445 
12446       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12447                                              Destructor->getParent());
12448     }
12449 
12450     // If any errors have occurred, clear out any temporaries that may have
12451     // been leftover. This ensures that these temporaries won't be picked up for
12452     // deletion in some later function.
12453     if (getDiagnostics().hasErrorOccurred() ||
12454         getDiagnostics().getSuppressAllDiagnostics()) {
12455       DiscardCleanupsInEvaluationContext();
12456     }
12457     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12458         !isa<FunctionTemplateDecl>(dcl)) {
12459       // Since the body is valid, issue any analysis-based warnings that are
12460       // enabled.
12461       ActivePolicy = &WP;
12462     }
12463 
12464     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12465         (!CheckConstexprFunctionDecl(FD) ||
12466          !CheckConstexprFunctionBody(FD, Body)))
12467       FD->setInvalidDecl();
12468 
12469     if (FD && FD->hasAttr<NakedAttr>()) {
12470       for (const Stmt *S : Body->children()) {
12471         // Allow local register variables without initializer as they don't
12472         // require prologue.
12473         bool RegisterVariables = false;
12474         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12475           for (const auto *Decl : DS->decls()) {
12476             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12477               RegisterVariables =
12478                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12479               if (!RegisterVariables)
12480                 break;
12481             }
12482           }
12483         }
12484         if (RegisterVariables)
12485           continue;
12486         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12487           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12488           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12489           FD->setInvalidDecl();
12490           break;
12491         }
12492       }
12493     }
12494 
12495     assert(ExprCleanupObjects.size() ==
12496                ExprEvalContexts.back().NumCleanupObjects &&
12497            "Leftover temporaries in function");
12498     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12499     assert(MaybeODRUseExprs.empty() &&
12500            "Leftover expressions for odr-use checking");
12501   }
12502 
12503   if (!IsInstantiation)
12504     PopDeclContext();
12505 
12506   PopFunctionScopeInfo(ActivePolicy, dcl);
12507   // If any errors have occurred, clear out any temporaries that may have
12508   // been leftover. This ensures that these temporaries won't be picked up for
12509   // deletion in some later function.
12510   if (getDiagnostics().hasErrorOccurred()) {
12511     DiscardCleanupsInEvaluationContext();
12512   }
12513 
12514   return dcl;
12515 }
12516 
12517 /// When we finish delayed parsing of an attribute, we must attach it to the
12518 /// relevant Decl.
12519 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12520                                        ParsedAttributes &Attrs) {
12521   // Always attach attributes to the underlying decl.
12522   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12523     D = TD->getTemplatedDecl();
12524   ProcessDeclAttributeList(S, D, Attrs.getList());
12525 
12526   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12527     if (Method->isStatic())
12528       checkThisInStaticMemberFunctionAttributes(Method);
12529 }
12530 
12531 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12532 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12533 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12534                                           IdentifierInfo &II, Scope *S) {
12535   // Before we produce a declaration for an implicitly defined
12536   // function, see whether there was a locally-scoped declaration of
12537   // this name as a function or variable. If so, use that
12538   // (non-visible) declaration, and complain about it.
12539   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12540     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12541     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12542     return ExternCPrev;
12543   }
12544 
12545   // Extension in C99.  Legal in C90, but warn about it.
12546   unsigned diag_id;
12547   if (II.getName().startswith("__builtin_"))
12548     diag_id = diag::warn_builtin_unknown;
12549   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12550   else if (getLangOpts().OpenCL)
12551     diag_id = diag::err_opencl_implicit_function_decl;
12552   else if (getLangOpts().C99)
12553     diag_id = diag::ext_implicit_function_decl;
12554   else
12555     diag_id = diag::warn_implicit_function_decl;
12556   Diag(Loc, diag_id) << &II;
12557 
12558   // Because typo correction is expensive, only do it if the implicit
12559   // function declaration is going to be treated as an error.
12560   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12561     TypoCorrection Corrected;
12562     if (S &&
12563         (Corrected = CorrectTypo(
12564              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12565              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12566       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12567                    /*ErrorRecovery*/false);
12568   }
12569 
12570   // Set a Declarator for the implicit definition: int foo();
12571   const char *Dummy;
12572   AttributeFactory attrFactory;
12573   DeclSpec DS(attrFactory);
12574   unsigned DiagID;
12575   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12576                                   Context.getPrintingPolicy());
12577   (void)Error; // Silence warning.
12578   assert(!Error && "Error setting up implicit decl!");
12579   SourceLocation NoLoc;
12580   Declarator D(DS, Declarator::BlockContext);
12581   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12582                                              /*IsAmbiguous=*/false,
12583                                              /*LParenLoc=*/NoLoc,
12584                                              /*Params=*/nullptr,
12585                                              /*NumParams=*/0,
12586                                              /*EllipsisLoc=*/NoLoc,
12587                                              /*RParenLoc=*/NoLoc,
12588                                              /*TypeQuals=*/0,
12589                                              /*RefQualifierIsLvalueRef=*/true,
12590                                              /*RefQualifierLoc=*/NoLoc,
12591                                              /*ConstQualifierLoc=*/NoLoc,
12592                                              /*VolatileQualifierLoc=*/NoLoc,
12593                                              /*RestrictQualifierLoc=*/NoLoc,
12594                                              /*MutableLoc=*/NoLoc,
12595                                              EST_None,
12596                                              /*ESpecRange=*/SourceRange(),
12597                                              /*Exceptions=*/nullptr,
12598                                              /*ExceptionRanges=*/nullptr,
12599                                              /*NumExceptions=*/0,
12600                                              /*NoexceptExpr=*/nullptr,
12601                                              /*ExceptionSpecTokens=*/nullptr,
12602                                              /*DeclsInPrototype=*/None,
12603                                              Loc, Loc, D),
12604                 DS.getAttributes(),
12605                 SourceLocation());
12606   D.SetIdentifier(&II, Loc);
12607 
12608   // Insert this function into translation-unit scope.
12609 
12610   DeclContext *PrevDC = CurContext;
12611   CurContext = Context.getTranslationUnitDecl();
12612 
12613   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12614   FD->setImplicit();
12615 
12616   CurContext = PrevDC;
12617 
12618   AddKnownFunctionAttributes(FD);
12619 
12620   return FD;
12621 }
12622 
12623 /// \brief Adds any function attributes that we know a priori based on
12624 /// the declaration of this function.
12625 ///
12626 /// These attributes can apply both to implicitly-declared builtins
12627 /// (like __builtin___printf_chk) or to library-declared functions
12628 /// like NSLog or printf.
12629 ///
12630 /// We need to check for duplicate attributes both here and where user-written
12631 /// attributes are applied to declarations.
12632 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12633   if (FD->isInvalidDecl())
12634     return;
12635 
12636   // If this is a built-in function, map its builtin attributes to
12637   // actual attributes.
12638   if (unsigned BuiltinID = FD->getBuiltinID()) {
12639     // Handle printf-formatting attributes.
12640     unsigned FormatIdx;
12641     bool HasVAListArg;
12642     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12643       if (!FD->hasAttr<FormatAttr>()) {
12644         const char *fmt = "printf";
12645         unsigned int NumParams = FD->getNumParams();
12646         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12647             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12648           fmt = "NSString";
12649         FD->addAttr(FormatAttr::CreateImplicit(Context,
12650                                                &Context.Idents.get(fmt),
12651                                                FormatIdx+1,
12652                                                HasVAListArg ? 0 : FormatIdx+2,
12653                                                FD->getLocation()));
12654       }
12655     }
12656     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12657                                              HasVAListArg)) {
12658      if (!FD->hasAttr<FormatAttr>())
12659        FD->addAttr(FormatAttr::CreateImplicit(Context,
12660                                               &Context.Idents.get("scanf"),
12661                                               FormatIdx+1,
12662                                               HasVAListArg ? 0 : FormatIdx+2,
12663                                               FD->getLocation()));
12664     }
12665 
12666     // Mark const if we don't care about errno and that is the only
12667     // thing preventing the function from being const. This allows
12668     // IRgen to use LLVM intrinsics for such functions.
12669     if (!getLangOpts().MathErrno &&
12670         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12671       if (!FD->hasAttr<ConstAttr>())
12672         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12673     }
12674 
12675     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12676         !FD->hasAttr<ReturnsTwiceAttr>())
12677       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12678                                          FD->getLocation()));
12679     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12680       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12681     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12682       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12683     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12684       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12685     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12686         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12687       // Add the appropriate attribute, depending on the CUDA compilation mode
12688       // and which target the builtin belongs to. For example, during host
12689       // compilation, aux builtins are __device__, while the rest are __host__.
12690       if (getLangOpts().CUDAIsDevice !=
12691           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12692         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12693       else
12694         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12695     }
12696   }
12697 
12698   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12699   // throw, add an implicit nothrow attribute to any extern "C" function we come
12700   // across.
12701   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12702       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12703     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12704     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12705       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12706   }
12707 
12708   IdentifierInfo *Name = FD->getIdentifier();
12709   if (!Name)
12710     return;
12711   if ((!getLangOpts().CPlusPlus &&
12712        FD->getDeclContext()->isTranslationUnit()) ||
12713       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12714        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12715        LinkageSpecDecl::lang_c)) {
12716     // Okay: this could be a libc/libm/Objective-C function we know
12717     // about.
12718   } else
12719     return;
12720 
12721   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12722     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12723     // target-specific builtins, perhaps?
12724     if (!FD->hasAttr<FormatAttr>())
12725       FD->addAttr(FormatAttr::CreateImplicit(Context,
12726                                              &Context.Idents.get("printf"), 2,
12727                                              Name->isStr("vasprintf") ? 0 : 3,
12728                                              FD->getLocation()));
12729   }
12730 
12731   if (Name->isStr("__CFStringMakeConstantString")) {
12732     // We already have a __builtin___CFStringMakeConstantString,
12733     // but builds that use -fno-constant-cfstrings don't go through that.
12734     if (!FD->hasAttr<FormatArgAttr>())
12735       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12736                                                 FD->getLocation()));
12737   }
12738 }
12739 
12740 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12741                                     TypeSourceInfo *TInfo) {
12742   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12743   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12744 
12745   if (!TInfo) {
12746     assert(D.isInvalidType() && "no declarator info for valid type");
12747     TInfo = Context.getTrivialTypeSourceInfo(T);
12748   }
12749 
12750   // Scope manipulation handled by caller.
12751   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12752                                            D.getLocStart(),
12753                                            D.getIdentifierLoc(),
12754                                            D.getIdentifier(),
12755                                            TInfo);
12756 
12757   // Bail out immediately if we have an invalid declaration.
12758   if (D.isInvalidType()) {
12759     NewTD->setInvalidDecl();
12760     return NewTD;
12761   }
12762 
12763   if (D.getDeclSpec().isModulePrivateSpecified()) {
12764     if (CurContext->isFunctionOrMethod())
12765       Diag(NewTD->getLocation(), diag::err_module_private_local)
12766         << 2 << NewTD->getDeclName()
12767         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12768         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12769     else
12770       NewTD->setModulePrivate();
12771   }
12772 
12773   // C++ [dcl.typedef]p8:
12774   //   If the typedef declaration defines an unnamed class (or
12775   //   enum), the first typedef-name declared by the declaration
12776   //   to be that class type (or enum type) is used to denote the
12777   //   class type (or enum type) for linkage purposes only.
12778   // We need to check whether the type was declared in the declaration.
12779   switch (D.getDeclSpec().getTypeSpecType()) {
12780   case TST_enum:
12781   case TST_struct:
12782   case TST_interface:
12783   case TST_union:
12784   case TST_class: {
12785     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12786     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12787     break;
12788   }
12789 
12790   default:
12791     break;
12792   }
12793 
12794   return NewTD;
12795 }
12796 
12797 /// \brief Check that this is a valid underlying type for an enum declaration.
12798 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12799   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12800   QualType T = TI->getType();
12801 
12802   if (T->isDependentType())
12803     return false;
12804 
12805   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12806     if (BT->isInteger())
12807       return false;
12808 
12809   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12810   return true;
12811 }
12812 
12813 /// Check whether this is a valid redeclaration of a previous enumeration.
12814 /// \return true if the redeclaration was invalid.
12815 bool Sema::CheckEnumRedeclaration(
12816     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12817     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12818   bool IsFixed = !EnumUnderlyingTy.isNull();
12819 
12820   if (IsScoped != Prev->isScoped()) {
12821     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12822       << Prev->isScoped();
12823     Diag(Prev->getLocation(), diag::note_previous_declaration);
12824     return true;
12825   }
12826 
12827   if (IsFixed && Prev->isFixed()) {
12828     if (!EnumUnderlyingTy->isDependentType() &&
12829         !Prev->getIntegerType()->isDependentType() &&
12830         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12831                                         Prev->getIntegerType())) {
12832       // TODO: Highlight the underlying type of the redeclaration.
12833       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12834         << EnumUnderlyingTy << Prev->getIntegerType();
12835       Diag(Prev->getLocation(), diag::note_previous_declaration)
12836           << Prev->getIntegerTypeRange();
12837       return true;
12838     }
12839   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12840     ;
12841   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12842     ;
12843   } else if (IsFixed != Prev->isFixed()) {
12844     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12845       << Prev->isFixed();
12846     Diag(Prev->getLocation(), diag::note_previous_declaration);
12847     return true;
12848   }
12849 
12850   return false;
12851 }
12852 
12853 /// \brief Get diagnostic %select index for tag kind for
12854 /// redeclaration diagnostic message.
12855 /// WARNING: Indexes apply to particular diagnostics only!
12856 ///
12857 /// \returns diagnostic %select index.
12858 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12859   switch (Tag) {
12860   case TTK_Struct: return 0;
12861   case TTK_Interface: return 1;
12862   case TTK_Class:  return 2;
12863   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12864   }
12865 }
12866 
12867 /// \brief Determine if tag kind is a class-key compatible with
12868 /// class for redeclaration (class, struct, or __interface).
12869 ///
12870 /// \returns true iff the tag kind is compatible.
12871 static bool isClassCompatTagKind(TagTypeKind Tag)
12872 {
12873   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12874 }
12875 
12876 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12877                                              TagTypeKind TTK) {
12878   if (isa<TypedefDecl>(PrevDecl))
12879     return NTK_Typedef;
12880   else if (isa<TypeAliasDecl>(PrevDecl))
12881     return NTK_TypeAlias;
12882   else if (isa<ClassTemplateDecl>(PrevDecl))
12883     return NTK_Template;
12884   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12885     return NTK_TypeAliasTemplate;
12886   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12887     return NTK_TemplateTemplateArgument;
12888   switch (TTK) {
12889   case TTK_Struct:
12890   case TTK_Interface:
12891   case TTK_Class:
12892     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12893   case TTK_Union:
12894     return NTK_NonUnion;
12895   case TTK_Enum:
12896     return NTK_NonEnum;
12897   }
12898   llvm_unreachable("invalid TTK");
12899 }
12900 
12901 /// \brief Determine whether a tag with a given kind is acceptable
12902 /// as a redeclaration of the given tag declaration.
12903 ///
12904 /// \returns true if the new tag kind is acceptable, false otherwise.
12905 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12906                                         TagTypeKind NewTag, bool isDefinition,
12907                                         SourceLocation NewTagLoc,
12908                                         const IdentifierInfo *Name) {
12909   // C++ [dcl.type.elab]p3:
12910   //   The class-key or enum keyword present in the
12911   //   elaborated-type-specifier shall agree in kind with the
12912   //   declaration to which the name in the elaborated-type-specifier
12913   //   refers. This rule also applies to the form of
12914   //   elaborated-type-specifier that declares a class-name or
12915   //   friend class since it can be construed as referring to the
12916   //   definition of the class. Thus, in any
12917   //   elaborated-type-specifier, the enum keyword shall be used to
12918   //   refer to an enumeration (7.2), the union class-key shall be
12919   //   used to refer to a union (clause 9), and either the class or
12920   //   struct class-key shall be used to refer to a class (clause 9)
12921   //   declared using the class or struct class-key.
12922   TagTypeKind OldTag = Previous->getTagKind();
12923   if (!isDefinition || !isClassCompatTagKind(NewTag))
12924     if (OldTag == NewTag)
12925       return true;
12926 
12927   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12928     // Warn about the struct/class tag mismatch.
12929     bool isTemplate = false;
12930     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12931       isTemplate = Record->getDescribedClassTemplate();
12932 
12933     if (inTemplateInstantiation()) {
12934       // In a template instantiation, do not offer fix-its for tag mismatches
12935       // since they usually mess up the template instead of fixing the problem.
12936       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12937         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12938         << getRedeclDiagFromTagKind(OldTag);
12939       return true;
12940     }
12941 
12942     if (isDefinition) {
12943       // On definitions, check previous tags and issue a fix-it for each
12944       // one that doesn't match the current tag.
12945       if (Previous->getDefinition()) {
12946         // Don't suggest fix-its for redefinitions.
12947         return true;
12948       }
12949 
12950       bool previousMismatch = false;
12951       for (auto I : Previous->redecls()) {
12952         if (I->getTagKind() != NewTag) {
12953           if (!previousMismatch) {
12954             previousMismatch = true;
12955             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12956               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12957               << getRedeclDiagFromTagKind(I->getTagKind());
12958           }
12959           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12960             << getRedeclDiagFromTagKind(NewTag)
12961             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12962                  TypeWithKeyword::getTagTypeKindName(NewTag));
12963         }
12964       }
12965       return true;
12966     }
12967 
12968     // Check for a previous definition.  If current tag and definition
12969     // are same type, do nothing.  If no definition, but disagree with
12970     // with previous tag type, give a warning, but no fix-it.
12971     const TagDecl *Redecl = Previous->getDefinition() ?
12972                             Previous->getDefinition() : Previous;
12973     if (Redecl->getTagKind() == NewTag) {
12974       return true;
12975     }
12976 
12977     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12978       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12979       << getRedeclDiagFromTagKind(OldTag);
12980     Diag(Redecl->getLocation(), diag::note_previous_use);
12981 
12982     // If there is a previous definition, suggest a fix-it.
12983     if (Previous->getDefinition()) {
12984         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12985           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12986           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12987                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12988     }
12989 
12990     return true;
12991   }
12992   return false;
12993 }
12994 
12995 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12996 /// from an outer enclosing namespace or file scope inside a friend declaration.
12997 /// This should provide the commented out code in the following snippet:
12998 ///   namespace N {
12999 ///     struct X;
13000 ///     namespace M {
13001 ///       struct Y { friend struct /*N::*/ X; };
13002 ///     }
13003 ///   }
13004 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13005                                          SourceLocation NameLoc) {
13006   // While the decl is in a namespace, do repeated lookup of that name and see
13007   // if we get the same namespace back.  If we do not, continue until
13008   // translation unit scope, at which point we have a fully qualified NNS.
13009   SmallVector<IdentifierInfo *, 4> Namespaces;
13010   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13011   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13012     // This tag should be declared in a namespace, which can only be enclosed by
13013     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13014     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13015     if (!Namespace || Namespace->isAnonymousNamespace())
13016       return FixItHint();
13017     IdentifierInfo *II = Namespace->getIdentifier();
13018     Namespaces.push_back(II);
13019     NamedDecl *Lookup = SemaRef.LookupSingleName(
13020         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13021     if (Lookup == Namespace)
13022       break;
13023   }
13024 
13025   // Once we have all the namespaces, reverse them to go outermost first, and
13026   // build an NNS.
13027   SmallString<64> Insertion;
13028   llvm::raw_svector_ostream OS(Insertion);
13029   if (DC->isTranslationUnit())
13030     OS << "::";
13031   std::reverse(Namespaces.begin(), Namespaces.end());
13032   for (auto *II : Namespaces)
13033     OS << II->getName() << "::";
13034   return FixItHint::CreateInsertion(NameLoc, Insertion);
13035 }
13036 
13037 /// \brief Determine whether a tag originally declared in context \p OldDC can
13038 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13039 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13040 /// using-declaration).
13041 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13042                                          DeclContext *NewDC) {
13043   OldDC = OldDC->getRedeclContext();
13044   NewDC = NewDC->getRedeclContext();
13045 
13046   if (OldDC->Equals(NewDC))
13047     return true;
13048 
13049   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13050   // encloses the other).
13051   if (S.getLangOpts().MSVCCompat &&
13052       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13053     return true;
13054 
13055   return false;
13056 }
13057 
13058 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13059 /// former case, Name will be non-null.  In the later case, Name will be null.
13060 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13061 /// reference/declaration/definition of a tag.
13062 ///
13063 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13064 /// trailing-type-specifier) other than one in an alias-declaration.
13065 ///
13066 /// \param SkipBody If non-null, will be set to indicate if the caller should
13067 /// skip the definition of this tag and treat it as if it were a declaration.
13068 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13069                      SourceLocation KWLoc, CXXScopeSpec &SS,
13070                      IdentifierInfo *Name, SourceLocation NameLoc,
13071                      AttributeList *Attr, AccessSpecifier AS,
13072                      SourceLocation ModulePrivateLoc,
13073                      MultiTemplateParamsArg TemplateParameterLists,
13074                      bool &OwnedDecl, bool &IsDependent,
13075                      SourceLocation ScopedEnumKWLoc,
13076                      bool ScopedEnumUsesClassTag,
13077                      TypeResult UnderlyingType,
13078                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
13079   // If this is not a definition, it must have a name.
13080   IdentifierInfo *OrigName = Name;
13081   assert((Name != nullptr || TUK == TUK_Definition) &&
13082          "Nameless record must be a definition!");
13083   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13084 
13085   OwnedDecl = false;
13086   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13087   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13088 
13089   // FIXME: Check member specializations more carefully.
13090   bool isMemberSpecialization = false;
13091   bool Invalid = false;
13092 
13093   // We only need to do this matching if we have template parameters
13094   // or a scope specifier, which also conveniently avoids this work
13095   // for non-C++ cases.
13096   if (TemplateParameterLists.size() > 0 ||
13097       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13098     if (TemplateParameterList *TemplateParams =
13099             MatchTemplateParametersToScopeSpecifier(
13100                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13101                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13102       if (Kind == TTK_Enum) {
13103         Diag(KWLoc, diag::err_enum_template);
13104         return nullptr;
13105       }
13106 
13107       if (TemplateParams->size() > 0) {
13108         // This is a declaration or definition of a class template (which may
13109         // be a member of another template).
13110 
13111         if (Invalid)
13112           return nullptr;
13113 
13114         OwnedDecl = false;
13115         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13116                                                SS, Name, NameLoc, Attr,
13117                                                TemplateParams, AS,
13118                                                ModulePrivateLoc,
13119                                                /*FriendLoc*/SourceLocation(),
13120                                                TemplateParameterLists.size()-1,
13121                                                TemplateParameterLists.data(),
13122                                                SkipBody);
13123         return Result.get();
13124       } else {
13125         // The "template<>" header is extraneous.
13126         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13127           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13128         isMemberSpecialization = true;
13129       }
13130     }
13131   }
13132 
13133   // Figure out the underlying type if this a enum declaration. We need to do
13134   // this early, because it's needed to detect if this is an incompatible
13135   // redeclaration.
13136   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13137   bool EnumUnderlyingIsImplicit = false;
13138 
13139   if (Kind == TTK_Enum) {
13140     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13141       // No underlying type explicitly specified, or we failed to parse the
13142       // type, default to int.
13143       EnumUnderlying = Context.IntTy.getTypePtr();
13144     else if (UnderlyingType.get()) {
13145       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13146       // integral type; any cv-qualification is ignored.
13147       TypeSourceInfo *TI = nullptr;
13148       GetTypeFromParser(UnderlyingType.get(), &TI);
13149       EnumUnderlying = TI;
13150 
13151       if (CheckEnumUnderlyingType(TI))
13152         // Recover by falling back to int.
13153         EnumUnderlying = Context.IntTy.getTypePtr();
13154 
13155       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13156                                           UPPC_FixedUnderlyingType))
13157         EnumUnderlying = Context.IntTy.getTypePtr();
13158 
13159     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13160       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13161         // Microsoft enums are always of int type.
13162         EnumUnderlying = Context.IntTy.getTypePtr();
13163         EnumUnderlyingIsImplicit = true;
13164       }
13165     }
13166   }
13167 
13168   DeclContext *SearchDC = CurContext;
13169   DeclContext *DC = CurContext;
13170   bool isStdBadAlloc = false;
13171   bool isStdAlignValT = false;
13172 
13173   RedeclarationKind Redecl = ForRedeclaration;
13174   if (TUK == TUK_Friend || TUK == TUK_Reference)
13175     Redecl = NotForRedeclaration;
13176 
13177   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13178   if (Name && SS.isNotEmpty()) {
13179     // We have a nested-name tag ('struct foo::bar').
13180 
13181     // Check for invalid 'foo::'.
13182     if (SS.isInvalid()) {
13183       Name = nullptr;
13184       goto CreateNewDecl;
13185     }
13186 
13187     // If this is a friend or a reference to a class in a dependent
13188     // context, don't try to make a decl for it.
13189     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13190       DC = computeDeclContext(SS, false);
13191       if (!DC) {
13192         IsDependent = true;
13193         return nullptr;
13194       }
13195     } else {
13196       DC = computeDeclContext(SS, true);
13197       if (!DC) {
13198         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13199           << SS.getRange();
13200         return nullptr;
13201       }
13202     }
13203 
13204     if (RequireCompleteDeclContext(SS, DC))
13205       return nullptr;
13206 
13207     SearchDC = DC;
13208     // Look-up name inside 'foo::'.
13209     LookupQualifiedName(Previous, DC);
13210 
13211     if (Previous.isAmbiguous())
13212       return nullptr;
13213 
13214     if (Previous.empty()) {
13215       // Name lookup did not find anything. However, if the
13216       // nested-name-specifier refers to the current instantiation,
13217       // and that current instantiation has any dependent base
13218       // classes, we might find something at instantiation time: treat
13219       // this as a dependent elaborated-type-specifier.
13220       // But this only makes any sense for reference-like lookups.
13221       if (Previous.wasNotFoundInCurrentInstantiation() &&
13222           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13223         IsDependent = true;
13224         return nullptr;
13225       }
13226 
13227       // A tag 'foo::bar' must already exist.
13228       Diag(NameLoc, diag::err_not_tag_in_scope)
13229         << Kind << Name << DC << SS.getRange();
13230       Name = nullptr;
13231       Invalid = true;
13232       goto CreateNewDecl;
13233     }
13234   } else if (Name) {
13235     // C++14 [class.mem]p14:
13236     //   If T is the name of a class, then each of the following shall have a
13237     //   name different from T:
13238     //    -- every member of class T that is itself a type
13239     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13240         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13241       return nullptr;
13242 
13243     // If this is a named struct, check to see if there was a previous forward
13244     // declaration or definition.
13245     // FIXME: We're looking into outer scopes here, even when we
13246     // shouldn't be. Doing so can result in ambiguities that we
13247     // shouldn't be diagnosing.
13248     LookupName(Previous, S);
13249 
13250     // When declaring or defining a tag, ignore ambiguities introduced
13251     // by types using'ed into this scope.
13252     if (Previous.isAmbiguous() &&
13253         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13254       LookupResult::Filter F = Previous.makeFilter();
13255       while (F.hasNext()) {
13256         NamedDecl *ND = F.next();
13257         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13258                 SearchDC->getRedeclContext()))
13259           F.erase();
13260       }
13261       F.done();
13262     }
13263 
13264     // C++11 [namespace.memdef]p3:
13265     //   If the name in a friend declaration is neither qualified nor
13266     //   a template-id and the declaration is a function or an
13267     //   elaborated-type-specifier, the lookup to determine whether
13268     //   the entity has been previously declared shall not consider
13269     //   any scopes outside the innermost enclosing namespace.
13270     //
13271     // MSVC doesn't implement the above rule for types, so a friend tag
13272     // declaration may be a redeclaration of a type declared in an enclosing
13273     // scope.  They do implement this rule for friend functions.
13274     //
13275     // Does it matter that this should be by scope instead of by
13276     // semantic context?
13277     if (!Previous.empty() && TUK == TUK_Friend) {
13278       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13279       LookupResult::Filter F = Previous.makeFilter();
13280       bool FriendSawTagOutsideEnclosingNamespace = false;
13281       while (F.hasNext()) {
13282         NamedDecl *ND = F.next();
13283         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13284         if (DC->isFileContext() &&
13285             !EnclosingNS->Encloses(ND->getDeclContext())) {
13286           if (getLangOpts().MSVCCompat)
13287             FriendSawTagOutsideEnclosingNamespace = true;
13288           else
13289             F.erase();
13290         }
13291       }
13292       F.done();
13293 
13294       // Diagnose this MSVC extension in the easy case where lookup would have
13295       // unambiguously found something outside the enclosing namespace.
13296       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13297         NamedDecl *ND = Previous.getFoundDecl();
13298         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13299             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13300       }
13301     }
13302 
13303     // Note:  there used to be some attempt at recovery here.
13304     if (Previous.isAmbiguous())
13305       return nullptr;
13306 
13307     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13308       // FIXME: This makes sure that we ignore the contexts associated
13309       // with C structs, unions, and enums when looking for a matching
13310       // tag declaration or definition. See the similar lookup tweak
13311       // in Sema::LookupName; is there a better way to deal with this?
13312       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13313         SearchDC = SearchDC->getParent();
13314     }
13315   }
13316 
13317   if (Previous.isSingleResult() &&
13318       Previous.getFoundDecl()->isTemplateParameter()) {
13319     // Maybe we will complain about the shadowed template parameter.
13320     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13321     // Just pretend that we didn't see the previous declaration.
13322     Previous.clear();
13323   }
13324 
13325   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13326       DC->Equals(getStdNamespace())) {
13327     if (Name->isStr("bad_alloc")) {
13328       // This is a declaration of or a reference to "std::bad_alloc".
13329       isStdBadAlloc = true;
13330 
13331       // If std::bad_alloc has been implicitly declared (but made invisible to
13332       // name lookup), fill in this implicit declaration as the previous
13333       // declaration, so that the declarations get chained appropriately.
13334       if (Previous.empty() && StdBadAlloc)
13335         Previous.addDecl(getStdBadAlloc());
13336     } else if (Name->isStr("align_val_t")) {
13337       isStdAlignValT = true;
13338       if (Previous.empty() && StdAlignValT)
13339         Previous.addDecl(getStdAlignValT());
13340     }
13341   }
13342 
13343   // If we didn't find a previous declaration, and this is a reference
13344   // (or friend reference), move to the correct scope.  In C++, we
13345   // also need to do a redeclaration lookup there, just in case
13346   // there's a shadow friend decl.
13347   if (Name && Previous.empty() &&
13348       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13349     if (Invalid) goto CreateNewDecl;
13350     assert(SS.isEmpty());
13351 
13352     if (TUK == TUK_Reference) {
13353       // C++ [basic.scope.pdecl]p5:
13354       //   -- for an elaborated-type-specifier of the form
13355       //
13356       //          class-key identifier
13357       //
13358       //      if the elaborated-type-specifier is used in the
13359       //      decl-specifier-seq or parameter-declaration-clause of a
13360       //      function defined in namespace scope, the identifier is
13361       //      declared as a class-name in the namespace that contains
13362       //      the declaration; otherwise, except as a friend
13363       //      declaration, the identifier is declared in the smallest
13364       //      non-class, non-function-prototype scope that contains the
13365       //      declaration.
13366       //
13367       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13368       // C structs and unions.
13369       //
13370       // It is an error in C++ to declare (rather than define) an enum
13371       // type, including via an elaborated type specifier.  We'll
13372       // diagnose that later; for now, declare the enum in the same
13373       // scope as we would have picked for any other tag type.
13374       //
13375       // GNU C also supports this behavior as part of its incomplete
13376       // enum types extension, while GNU C++ does not.
13377       //
13378       // Find the context where we'll be declaring the tag.
13379       // FIXME: We would like to maintain the current DeclContext as the
13380       // lexical context,
13381       SearchDC = getTagInjectionContext(SearchDC);
13382 
13383       // Find the scope where we'll be declaring the tag.
13384       S = getTagInjectionScope(S, getLangOpts());
13385     } else {
13386       assert(TUK == TUK_Friend);
13387       // C++ [namespace.memdef]p3:
13388       //   If a friend declaration in a non-local class first declares a
13389       //   class or function, the friend class or function is a member of
13390       //   the innermost enclosing namespace.
13391       SearchDC = SearchDC->getEnclosingNamespaceContext();
13392     }
13393 
13394     // In C++, we need to do a redeclaration lookup to properly
13395     // diagnose some problems.
13396     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13397     // hidden declaration so that we don't get ambiguity errors when using a
13398     // type declared by an elaborated-type-specifier.  In C that is not correct
13399     // and we should instead merge compatible types found by lookup.
13400     if (getLangOpts().CPlusPlus) {
13401       Previous.setRedeclarationKind(ForRedeclaration);
13402       LookupQualifiedName(Previous, SearchDC);
13403     } else {
13404       Previous.setRedeclarationKind(ForRedeclaration);
13405       LookupName(Previous, S);
13406     }
13407   }
13408 
13409   // If we have a known previous declaration to use, then use it.
13410   if (Previous.empty() && SkipBody && SkipBody->Previous)
13411     Previous.addDecl(SkipBody->Previous);
13412 
13413   if (!Previous.empty()) {
13414     NamedDecl *PrevDecl = Previous.getFoundDecl();
13415     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13416 
13417     // It's okay to have a tag decl in the same scope as a typedef
13418     // which hides a tag decl in the same scope.  Finding this
13419     // insanity with a redeclaration lookup can only actually happen
13420     // in C++.
13421     //
13422     // This is also okay for elaborated-type-specifiers, which is
13423     // technically forbidden by the current standard but which is
13424     // okay according to the likely resolution of an open issue;
13425     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13426     if (getLangOpts().CPlusPlus) {
13427       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13428         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13429           TagDecl *Tag = TT->getDecl();
13430           if (Tag->getDeclName() == Name &&
13431               Tag->getDeclContext()->getRedeclContext()
13432                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13433             PrevDecl = Tag;
13434             Previous.clear();
13435             Previous.addDecl(Tag);
13436             Previous.resolveKind();
13437           }
13438         }
13439       }
13440     }
13441 
13442     // If this is a redeclaration of a using shadow declaration, it must
13443     // declare a tag in the same context. In MSVC mode, we allow a
13444     // redefinition if either context is within the other.
13445     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13446       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13447       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13448           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13449           !(OldTag && isAcceptableTagRedeclContext(
13450                           *this, OldTag->getDeclContext(), SearchDC))) {
13451         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13452         Diag(Shadow->getTargetDecl()->getLocation(),
13453              diag::note_using_decl_target);
13454         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13455             << 0;
13456         // Recover by ignoring the old declaration.
13457         Previous.clear();
13458         goto CreateNewDecl;
13459       }
13460     }
13461 
13462     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13463       // If this is a use of a previous tag, or if the tag is already declared
13464       // in the same scope (so that the definition/declaration completes or
13465       // rementions the tag), reuse the decl.
13466       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13467           isDeclInScope(DirectPrevDecl, SearchDC, S,
13468                         SS.isNotEmpty() || isMemberSpecialization)) {
13469         // Make sure that this wasn't declared as an enum and now used as a
13470         // struct or something similar.
13471         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13472                                           TUK == TUK_Definition, KWLoc,
13473                                           Name)) {
13474           bool SafeToContinue
13475             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13476                Kind != TTK_Enum);
13477           if (SafeToContinue)
13478             Diag(KWLoc, diag::err_use_with_wrong_tag)
13479               << Name
13480               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13481                                               PrevTagDecl->getKindName());
13482           else
13483             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13484           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13485 
13486           if (SafeToContinue)
13487             Kind = PrevTagDecl->getTagKind();
13488           else {
13489             // Recover by making this an anonymous redefinition.
13490             Name = nullptr;
13491             Previous.clear();
13492             Invalid = true;
13493           }
13494         }
13495 
13496         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13497           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13498 
13499           // If this is an elaborated-type-specifier for a scoped enumeration,
13500           // the 'class' keyword is not necessary and not permitted.
13501           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13502             if (ScopedEnum)
13503               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13504                 << PrevEnum->isScoped()
13505                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13506             return PrevTagDecl;
13507           }
13508 
13509           QualType EnumUnderlyingTy;
13510           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13511             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13512           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13513             EnumUnderlyingTy = QualType(T, 0);
13514 
13515           // All conflicts with previous declarations are recovered by
13516           // returning the previous declaration, unless this is a definition,
13517           // in which case we want the caller to bail out.
13518           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13519                                      ScopedEnum, EnumUnderlyingTy,
13520                                      EnumUnderlyingIsImplicit, PrevEnum))
13521             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13522         }
13523 
13524         // C++11 [class.mem]p1:
13525         //   A member shall not be declared twice in the member-specification,
13526         //   except that a nested class or member class template can be declared
13527         //   and then later defined.
13528         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13529             S->isDeclScope(PrevDecl)) {
13530           Diag(NameLoc, diag::ext_member_redeclared);
13531           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13532         }
13533 
13534         if (!Invalid) {
13535           // If this is a use, just return the declaration we found, unless
13536           // we have attributes.
13537           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13538             if (Attr) {
13539               // FIXME: Diagnose these attributes. For now, we create a new
13540               // declaration to hold them.
13541             } else if (TUK == TUK_Reference &&
13542                        (PrevTagDecl->getFriendObjectKind() ==
13543                             Decl::FOK_Undeclared ||
13544                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13545                        SS.isEmpty()) {
13546               // This declaration is a reference to an existing entity, but
13547               // has different visibility from that entity: it either makes
13548               // a friend visible or it makes a type visible in a new module.
13549               // In either case, create a new declaration. We only do this if
13550               // the declaration would have meant the same thing if no prior
13551               // declaration were found, that is, if it was found in the same
13552               // scope where we would have injected a declaration.
13553               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13554                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13555                 return PrevTagDecl;
13556               // This is in the injected scope, create a new declaration in
13557               // that scope.
13558               S = getTagInjectionScope(S, getLangOpts());
13559             } else {
13560               return PrevTagDecl;
13561             }
13562           }
13563 
13564           // Diagnose attempts to redefine a tag.
13565           if (TUK == TUK_Definition) {
13566             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13567               // If we're defining a specialization and the previous definition
13568               // is from an implicit instantiation, don't emit an error
13569               // here; we'll catch this in the general case below.
13570               bool IsExplicitSpecializationAfterInstantiation = false;
13571               if (isMemberSpecialization) {
13572                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13573                   IsExplicitSpecializationAfterInstantiation =
13574                     RD->getTemplateSpecializationKind() !=
13575                     TSK_ExplicitSpecialization;
13576                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13577                   IsExplicitSpecializationAfterInstantiation =
13578                     ED->getTemplateSpecializationKind() !=
13579                     TSK_ExplicitSpecialization;
13580               }
13581 
13582               NamedDecl *Hidden = nullptr;
13583               if (SkipBody && getLangOpts().CPlusPlus &&
13584                   !hasVisibleDefinition(Def, &Hidden)) {
13585                 // There is a definition of this tag, but it is not visible. We
13586                 // explicitly make use of C++'s one definition rule here, and
13587                 // assume that this definition is identical to the hidden one
13588                 // we already have. Make the existing definition visible and
13589                 // use it in place of this one.
13590                 SkipBody->ShouldSkip = true;
13591                 makeMergedDefinitionVisible(Hidden);
13592                 return Def;
13593               } else if (!IsExplicitSpecializationAfterInstantiation) {
13594                 // A redeclaration in function prototype scope in C isn't
13595                 // visible elsewhere, so merely issue a warning.
13596                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13597                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13598                 else
13599                   Diag(NameLoc, diag::err_redefinition) << Name;
13600                 notePreviousDefinition(Def,
13601                                        NameLoc.isValid() ? NameLoc : KWLoc);
13602                 // If this is a redefinition, recover by making this
13603                 // struct be anonymous, which will make any later
13604                 // references get the previous definition.
13605                 Name = nullptr;
13606                 Previous.clear();
13607                 Invalid = true;
13608               }
13609             } else {
13610               // If the type is currently being defined, complain
13611               // about a nested redefinition.
13612               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13613               if (TD->isBeingDefined()) {
13614                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13615                 Diag(PrevTagDecl->getLocation(),
13616                      diag::note_previous_definition);
13617                 Name = nullptr;
13618                 Previous.clear();
13619                 Invalid = true;
13620               }
13621             }
13622 
13623             // Okay, this is definition of a previously declared or referenced
13624             // tag. We're going to create a new Decl for it.
13625           }
13626 
13627           // Okay, we're going to make a redeclaration.  If this is some kind
13628           // of reference, make sure we build the redeclaration in the same DC
13629           // as the original, and ignore the current access specifier.
13630           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13631             SearchDC = PrevTagDecl->getDeclContext();
13632             AS = AS_none;
13633           }
13634         }
13635         // If we get here we have (another) forward declaration or we
13636         // have a definition.  Just create a new decl.
13637 
13638       } else {
13639         // If we get here, this is a definition of a new tag type in a nested
13640         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13641         // new decl/type.  We set PrevDecl to NULL so that the entities
13642         // have distinct types.
13643         Previous.clear();
13644       }
13645       // If we get here, we're going to create a new Decl. If PrevDecl
13646       // is non-NULL, it's a definition of the tag declared by
13647       // PrevDecl. If it's NULL, we have a new definition.
13648 
13649     // Otherwise, PrevDecl is not a tag, but was found with tag
13650     // lookup.  This is only actually possible in C++, where a few
13651     // things like templates still live in the tag namespace.
13652     } else {
13653       // Use a better diagnostic if an elaborated-type-specifier
13654       // found the wrong kind of type on the first
13655       // (non-redeclaration) lookup.
13656       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13657           !Previous.isForRedeclaration()) {
13658         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13659         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13660                                                        << Kind;
13661         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13662         Invalid = true;
13663 
13664       // Otherwise, only diagnose if the declaration is in scope.
13665       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13666                                 SS.isNotEmpty() || isMemberSpecialization)) {
13667         // do nothing
13668 
13669       // Diagnose implicit declarations introduced by elaborated types.
13670       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13671         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13672         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13673         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13674         Invalid = true;
13675 
13676       // Otherwise it's a declaration.  Call out a particularly common
13677       // case here.
13678       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13679         unsigned Kind = 0;
13680         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13681         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13682           << Name << Kind << TND->getUnderlyingType();
13683         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13684         Invalid = true;
13685 
13686       // Otherwise, diagnose.
13687       } else {
13688         // The tag name clashes with something else in the target scope,
13689         // issue an error and recover by making this tag be anonymous.
13690         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13691         notePreviousDefinition(PrevDecl, NameLoc);
13692         Name = nullptr;
13693         Invalid = true;
13694       }
13695 
13696       // The existing declaration isn't relevant to us; we're in a
13697       // new scope, so clear out the previous declaration.
13698       Previous.clear();
13699     }
13700   }
13701 
13702 CreateNewDecl:
13703 
13704   TagDecl *PrevDecl = nullptr;
13705   if (Previous.isSingleResult())
13706     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13707 
13708   // If there is an identifier, use the location of the identifier as the
13709   // location of the decl, otherwise use the location of the struct/union
13710   // keyword.
13711   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13712 
13713   // Otherwise, create a new declaration. If there is a previous
13714   // declaration of the same entity, the two will be linked via
13715   // PrevDecl.
13716   TagDecl *New;
13717 
13718   bool IsForwardReference = false;
13719   if (Kind == TTK_Enum) {
13720     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13721     // enum X { A, B, C } D;    D should chain to X.
13722     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13723                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13724                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13725 
13726     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13727       StdAlignValT = cast<EnumDecl>(New);
13728 
13729     // If this is an undefined enum, warn.
13730     if (TUK != TUK_Definition && !Invalid) {
13731       TagDecl *Def;
13732       if (!EnumUnderlyingIsImplicit &&
13733           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13734           cast<EnumDecl>(New)->isFixed()) {
13735         // C++0x: 7.2p2: opaque-enum-declaration.
13736         // Conflicts are diagnosed above. Do nothing.
13737       }
13738       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13739         Diag(Loc, diag::ext_forward_ref_enum_def)
13740           << New;
13741         Diag(Def->getLocation(), diag::note_previous_definition);
13742       } else {
13743         unsigned DiagID = diag::ext_forward_ref_enum;
13744         if (getLangOpts().MSVCCompat)
13745           DiagID = diag::ext_ms_forward_ref_enum;
13746         else if (getLangOpts().CPlusPlus)
13747           DiagID = diag::err_forward_ref_enum;
13748         Diag(Loc, DiagID);
13749 
13750         // If this is a forward-declared reference to an enumeration, make a
13751         // note of it; we won't actually be introducing the declaration into
13752         // the declaration context.
13753         if (TUK == TUK_Reference)
13754           IsForwardReference = true;
13755       }
13756     }
13757 
13758     if (EnumUnderlying) {
13759       EnumDecl *ED = cast<EnumDecl>(New);
13760       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13761         ED->setIntegerTypeSourceInfo(TI);
13762       else
13763         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13764       ED->setPromotionType(ED->getIntegerType());
13765     }
13766   } else {
13767     // struct/union/class
13768 
13769     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13770     // struct X { int A; } D;    D should chain to X.
13771     if (getLangOpts().CPlusPlus) {
13772       // FIXME: Look for a way to use RecordDecl for simple structs.
13773       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13774                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13775 
13776       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13777         StdBadAlloc = cast<CXXRecordDecl>(New);
13778     } else
13779       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13780                                cast_or_null<RecordDecl>(PrevDecl));
13781   }
13782 
13783   // C++11 [dcl.type]p3:
13784   //   A type-specifier-seq shall not define a class or enumeration [...].
13785   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13786     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13787       << Context.getTagDeclType(New);
13788     Invalid = true;
13789   }
13790 
13791   // Maybe add qualifier info.
13792   if (SS.isNotEmpty()) {
13793     if (SS.isSet()) {
13794       // If this is either a declaration or a definition, check the
13795       // nested-name-specifier against the current context. We don't do this
13796       // for explicit specializations, because they have similar checking
13797       // (with more specific diagnostics) in the call to
13798       // CheckMemberSpecialization, below.
13799       if (!isMemberSpecialization &&
13800           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13801           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13802         Invalid = true;
13803 
13804       New->setQualifierInfo(SS.getWithLocInContext(Context));
13805       if (TemplateParameterLists.size() > 0) {
13806         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13807       }
13808     }
13809     else
13810       Invalid = true;
13811   }
13812 
13813   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13814     // Add alignment attributes if necessary; these attributes are checked when
13815     // the ASTContext lays out the structure.
13816     //
13817     // It is important for implementing the correct semantics that this
13818     // happen here (in act on tag decl). The #pragma pack stack is
13819     // maintained as a result of parser callbacks which can occur at
13820     // many points during the parsing of a struct declaration (because
13821     // the #pragma tokens are effectively skipped over during the
13822     // parsing of the struct).
13823     if (TUK == TUK_Definition) {
13824       AddAlignmentAttributesForRecord(RD);
13825       AddMsStructLayoutForRecord(RD);
13826     }
13827   }
13828 
13829   if (ModulePrivateLoc.isValid()) {
13830     if (isMemberSpecialization)
13831       Diag(New->getLocation(), diag::err_module_private_specialization)
13832         << 2
13833         << FixItHint::CreateRemoval(ModulePrivateLoc);
13834     // __module_private__ does not apply to local classes. However, we only
13835     // diagnose this as an error when the declaration specifiers are
13836     // freestanding. Here, we just ignore the __module_private__.
13837     else if (!SearchDC->isFunctionOrMethod())
13838       New->setModulePrivate();
13839   }
13840 
13841   // If this is a specialization of a member class (of a class template),
13842   // check the specialization.
13843   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13844     Invalid = true;
13845 
13846   // If we're declaring or defining a tag in function prototype scope in C,
13847   // note that this type can only be used within the function and add it to
13848   // the list of decls to inject into the function definition scope.
13849   if ((Name || Kind == TTK_Enum) &&
13850       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13851     if (getLangOpts().CPlusPlus) {
13852       // C++ [dcl.fct]p6:
13853       //   Types shall not be defined in return or parameter types.
13854       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13855         Diag(Loc, diag::err_type_defined_in_param_type)
13856             << Name;
13857         Invalid = true;
13858       }
13859     } else if (!PrevDecl) {
13860       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13861     }
13862   }
13863 
13864   if (Invalid)
13865     New->setInvalidDecl();
13866 
13867   // Set the lexical context. If the tag has a C++ scope specifier, the
13868   // lexical context will be different from the semantic context.
13869   New->setLexicalDeclContext(CurContext);
13870 
13871   // Mark this as a friend decl if applicable.
13872   // In Microsoft mode, a friend declaration also acts as a forward
13873   // declaration so we always pass true to setObjectOfFriendDecl to make
13874   // the tag name visible.
13875   if (TUK == TUK_Friend)
13876     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13877 
13878   // Set the access specifier.
13879   if (!Invalid && SearchDC->isRecord())
13880     SetMemberAccessSpecifier(New, PrevDecl, AS);
13881 
13882   if (TUK == TUK_Definition)
13883     New->startDefinition();
13884 
13885   if (Attr)
13886     ProcessDeclAttributeList(S, New, Attr);
13887   AddPragmaAttributes(S, New);
13888 
13889   // If this has an identifier, add it to the scope stack.
13890   if (TUK == TUK_Friend) {
13891     // We might be replacing an existing declaration in the lookup tables;
13892     // if so, borrow its access specifier.
13893     if (PrevDecl)
13894       New->setAccess(PrevDecl->getAccess());
13895 
13896     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13897     DC->makeDeclVisibleInContext(New);
13898     if (Name) // can be null along some error paths
13899       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13900         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13901   } else if (Name) {
13902     S = getNonFieldDeclScope(S);
13903     PushOnScopeChains(New, S, !IsForwardReference);
13904     if (IsForwardReference)
13905       SearchDC->makeDeclVisibleInContext(New);
13906   } else {
13907     CurContext->addDecl(New);
13908   }
13909 
13910   // If this is the C FILE type, notify the AST context.
13911   if (IdentifierInfo *II = New->getIdentifier())
13912     if (!New->isInvalidDecl() &&
13913         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13914         II->isStr("FILE"))
13915       Context.setFILEDecl(New);
13916 
13917   if (PrevDecl)
13918     mergeDeclAttributes(New, PrevDecl);
13919 
13920   // If there's a #pragma GCC visibility in scope, set the visibility of this
13921   // record.
13922   AddPushedVisibilityAttribute(New);
13923 
13924   if (isMemberSpecialization && !New->isInvalidDecl())
13925     CompleteMemberSpecialization(New, Previous);
13926 
13927   OwnedDecl = true;
13928   // In C++, don't return an invalid declaration. We can't recover well from
13929   // the cases where we make the type anonymous.
13930   if (Invalid && getLangOpts().CPlusPlus) {
13931     if (New->isBeingDefined())
13932       if (auto RD = dyn_cast<RecordDecl>(New))
13933         RD->completeDefinition();
13934     return nullptr;
13935   } else {
13936     return New;
13937   }
13938 }
13939 
13940 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13941   AdjustDeclIfTemplate(TagD);
13942   TagDecl *Tag = cast<TagDecl>(TagD);
13943 
13944   // Enter the tag context.
13945   PushDeclContext(S, Tag);
13946 
13947   ActOnDocumentableDecl(TagD);
13948 
13949   // If there's a #pragma GCC visibility in scope, set the visibility of this
13950   // record.
13951   AddPushedVisibilityAttribute(Tag);
13952 }
13953 
13954 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13955   assert(isa<ObjCContainerDecl>(IDecl) &&
13956          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13957   DeclContext *OCD = cast<DeclContext>(IDecl);
13958   assert(getContainingDC(OCD) == CurContext &&
13959       "The next DeclContext should be lexically contained in the current one.");
13960   CurContext = OCD;
13961   return IDecl;
13962 }
13963 
13964 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13965                                            SourceLocation FinalLoc,
13966                                            bool IsFinalSpelledSealed,
13967                                            SourceLocation LBraceLoc) {
13968   AdjustDeclIfTemplate(TagD);
13969   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13970 
13971   FieldCollector->StartClass();
13972 
13973   if (!Record->getIdentifier())
13974     return;
13975 
13976   if (FinalLoc.isValid())
13977     Record->addAttr(new (Context)
13978                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13979 
13980   // C++ [class]p2:
13981   //   [...] The class-name is also inserted into the scope of the
13982   //   class itself; this is known as the injected-class-name. For
13983   //   purposes of access checking, the injected-class-name is treated
13984   //   as if it were a public member name.
13985   CXXRecordDecl *InjectedClassName
13986     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13987                             Record->getLocStart(), Record->getLocation(),
13988                             Record->getIdentifier(),
13989                             /*PrevDecl=*/nullptr,
13990                             /*DelayTypeCreation=*/true);
13991   Context.getTypeDeclType(InjectedClassName, Record);
13992   InjectedClassName->setImplicit();
13993   InjectedClassName->setAccess(AS_public);
13994   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13995       InjectedClassName->setDescribedClassTemplate(Template);
13996   PushOnScopeChains(InjectedClassName, S);
13997   assert(InjectedClassName->isInjectedClassName() &&
13998          "Broken injected-class-name");
13999 }
14000 
14001 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14002                                     SourceRange BraceRange) {
14003   AdjustDeclIfTemplate(TagD);
14004   TagDecl *Tag = cast<TagDecl>(TagD);
14005   Tag->setBraceRange(BraceRange);
14006 
14007   // Make sure we "complete" the definition even it is invalid.
14008   if (Tag->isBeingDefined()) {
14009     assert(Tag->isInvalidDecl() && "We should already have completed it");
14010     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14011       RD->completeDefinition();
14012   }
14013 
14014   if (isa<CXXRecordDecl>(Tag)) {
14015     FieldCollector->FinishClass();
14016   }
14017 
14018   // Exit this scope of this tag's definition.
14019   PopDeclContext();
14020 
14021   if (getCurLexicalContext()->isObjCContainer() &&
14022       Tag->getDeclContext()->isFileContext())
14023     Tag->setTopLevelDeclInObjCContainer();
14024 
14025   // Notify the consumer that we've defined a tag.
14026   if (!Tag->isInvalidDecl())
14027     Consumer.HandleTagDeclDefinition(Tag);
14028 }
14029 
14030 void Sema::ActOnObjCContainerFinishDefinition() {
14031   // Exit this scope of this interface definition.
14032   PopDeclContext();
14033 }
14034 
14035 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14036   assert(DC == CurContext && "Mismatch of container contexts");
14037   OriginalLexicalContext = DC;
14038   ActOnObjCContainerFinishDefinition();
14039 }
14040 
14041 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14042   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14043   OriginalLexicalContext = nullptr;
14044 }
14045 
14046 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14047   AdjustDeclIfTemplate(TagD);
14048   TagDecl *Tag = cast<TagDecl>(TagD);
14049   Tag->setInvalidDecl();
14050 
14051   // Make sure we "complete" the definition even it is invalid.
14052   if (Tag->isBeingDefined()) {
14053     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14054       RD->completeDefinition();
14055   }
14056 
14057   // We're undoing ActOnTagStartDefinition here, not
14058   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14059   // the FieldCollector.
14060 
14061   PopDeclContext();
14062 }
14063 
14064 // Note that FieldName may be null for anonymous bitfields.
14065 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14066                                 IdentifierInfo *FieldName,
14067                                 QualType FieldTy, bool IsMsStruct,
14068                                 Expr *BitWidth, bool *ZeroWidth) {
14069   // Default to true; that shouldn't confuse checks for emptiness
14070   if (ZeroWidth)
14071     *ZeroWidth = true;
14072 
14073   // C99 6.7.2.1p4 - verify the field type.
14074   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14075   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14076     // Handle incomplete types with specific error.
14077     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14078       return ExprError();
14079     if (FieldName)
14080       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14081         << FieldName << FieldTy << BitWidth->getSourceRange();
14082     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14083       << FieldTy << BitWidth->getSourceRange();
14084   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14085                                              UPPC_BitFieldWidth))
14086     return ExprError();
14087 
14088   // If the bit-width is type- or value-dependent, don't try to check
14089   // it now.
14090   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14091     return BitWidth;
14092 
14093   llvm::APSInt Value;
14094   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14095   if (ICE.isInvalid())
14096     return ICE;
14097   BitWidth = ICE.get();
14098 
14099   if (Value != 0 && ZeroWidth)
14100     *ZeroWidth = false;
14101 
14102   // Zero-width bitfield is ok for anonymous field.
14103   if (Value == 0 && FieldName)
14104     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14105 
14106   if (Value.isSigned() && Value.isNegative()) {
14107     if (FieldName)
14108       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14109                << FieldName << Value.toString(10);
14110     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14111       << Value.toString(10);
14112   }
14113 
14114   if (!FieldTy->isDependentType()) {
14115     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14116     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14117     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14118 
14119     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14120     // ABI.
14121     bool CStdConstraintViolation =
14122         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14123     bool MSBitfieldViolation =
14124         Value.ugt(TypeStorageSize) &&
14125         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14126     if (CStdConstraintViolation || MSBitfieldViolation) {
14127       unsigned DiagWidth =
14128           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14129       if (FieldName)
14130         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14131                << FieldName << (unsigned)Value.getZExtValue()
14132                << !CStdConstraintViolation << DiagWidth;
14133 
14134       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14135              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14136              << DiagWidth;
14137     }
14138 
14139     // Warn on types where the user might conceivably expect to get all
14140     // specified bits as value bits: that's all integral types other than
14141     // 'bool'.
14142     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14143       if (FieldName)
14144         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14145             << FieldName << (unsigned)Value.getZExtValue()
14146             << (unsigned)TypeWidth;
14147       else
14148         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14149             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14150     }
14151   }
14152 
14153   return BitWidth;
14154 }
14155 
14156 /// ActOnField - Each field of a C struct/union is passed into this in order
14157 /// to create a FieldDecl object for it.
14158 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14159                        Declarator &D, Expr *BitfieldWidth) {
14160   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14161                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14162                                /*InitStyle=*/ICIS_NoInit, AS_public);
14163   return Res;
14164 }
14165 
14166 /// HandleField - Analyze a field of a C struct or a C++ data member.
14167 ///
14168 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14169                              SourceLocation DeclStart,
14170                              Declarator &D, Expr *BitWidth,
14171                              InClassInitStyle InitStyle,
14172                              AccessSpecifier AS) {
14173   if (D.isDecompositionDeclarator()) {
14174     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14175     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14176       << Decomp.getSourceRange();
14177     return nullptr;
14178   }
14179 
14180   IdentifierInfo *II = D.getIdentifier();
14181   SourceLocation Loc = DeclStart;
14182   if (II) Loc = D.getIdentifierLoc();
14183 
14184   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14185   QualType T = TInfo->getType();
14186   if (getLangOpts().CPlusPlus) {
14187     CheckExtraCXXDefaultArguments(D);
14188 
14189     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14190                                         UPPC_DataMemberType)) {
14191       D.setInvalidType();
14192       T = Context.IntTy;
14193       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14194     }
14195   }
14196 
14197   // TR 18037 does not allow fields to be declared with address spaces.
14198   if (T.getQualifiers().hasAddressSpace()) {
14199     Diag(Loc, diag::err_field_with_address_space);
14200     D.setInvalidType();
14201   }
14202 
14203   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14204   // used as structure or union field: image, sampler, event or block types.
14205   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14206                           T->isSamplerT() || T->isBlockPointerType())) {
14207     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14208     D.setInvalidType();
14209   }
14210 
14211   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14212 
14213   if (D.getDeclSpec().isInlineSpecified())
14214     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14215         << getLangOpts().CPlusPlus1z;
14216   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14217     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14218          diag::err_invalid_thread)
14219       << DeclSpec::getSpecifierName(TSCS);
14220 
14221   // Check to see if this name was declared as a member previously
14222   NamedDecl *PrevDecl = nullptr;
14223   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14224   LookupName(Previous, S);
14225   switch (Previous.getResultKind()) {
14226     case LookupResult::Found:
14227     case LookupResult::FoundUnresolvedValue:
14228       PrevDecl = Previous.getAsSingle<NamedDecl>();
14229       break;
14230 
14231     case LookupResult::FoundOverloaded:
14232       PrevDecl = Previous.getRepresentativeDecl();
14233       break;
14234 
14235     case LookupResult::NotFound:
14236     case LookupResult::NotFoundInCurrentInstantiation:
14237     case LookupResult::Ambiguous:
14238       break;
14239   }
14240   Previous.suppressDiagnostics();
14241 
14242   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14243     // Maybe we will complain about the shadowed template parameter.
14244     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14245     // Just pretend that we didn't see the previous declaration.
14246     PrevDecl = nullptr;
14247   }
14248 
14249   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14250     PrevDecl = nullptr;
14251 
14252   bool Mutable
14253     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14254   SourceLocation TSSL = D.getLocStart();
14255   FieldDecl *NewFD
14256     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14257                      TSSL, AS, PrevDecl, &D);
14258 
14259   if (NewFD->isInvalidDecl())
14260     Record->setInvalidDecl();
14261 
14262   if (D.getDeclSpec().isModulePrivateSpecified())
14263     NewFD->setModulePrivate();
14264 
14265   if (NewFD->isInvalidDecl() && PrevDecl) {
14266     // Don't introduce NewFD into scope; there's already something
14267     // with the same name in the same scope.
14268   } else if (II) {
14269     PushOnScopeChains(NewFD, S);
14270   } else
14271     Record->addDecl(NewFD);
14272 
14273   return NewFD;
14274 }
14275 
14276 /// \brief Build a new FieldDecl and check its well-formedness.
14277 ///
14278 /// This routine builds a new FieldDecl given the fields name, type,
14279 /// record, etc. \p PrevDecl should refer to any previous declaration
14280 /// with the same name and in the same scope as the field to be
14281 /// created.
14282 ///
14283 /// \returns a new FieldDecl.
14284 ///
14285 /// \todo The Declarator argument is a hack. It will be removed once
14286 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14287                                 TypeSourceInfo *TInfo,
14288                                 RecordDecl *Record, SourceLocation Loc,
14289                                 bool Mutable, Expr *BitWidth,
14290                                 InClassInitStyle InitStyle,
14291                                 SourceLocation TSSL,
14292                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14293                                 Declarator *D) {
14294   IdentifierInfo *II = Name.getAsIdentifierInfo();
14295   bool InvalidDecl = false;
14296   if (D) InvalidDecl = D->isInvalidType();
14297 
14298   // If we receive a broken type, recover by assuming 'int' and
14299   // marking this declaration as invalid.
14300   if (T.isNull()) {
14301     InvalidDecl = true;
14302     T = Context.IntTy;
14303   }
14304 
14305   QualType EltTy = Context.getBaseElementType(T);
14306   if (!EltTy->isDependentType()) {
14307     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14308       // Fields of incomplete type force their record to be invalid.
14309       Record->setInvalidDecl();
14310       InvalidDecl = true;
14311     } else {
14312       NamedDecl *Def;
14313       EltTy->isIncompleteType(&Def);
14314       if (Def && Def->isInvalidDecl()) {
14315         Record->setInvalidDecl();
14316         InvalidDecl = true;
14317       }
14318     }
14319   }
14320 
14321   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14322   if (BitWidth && getLangOpts().OpenCL) {
14323     Diag(Loc, diag::err_opencl_bitfields);
14324     InvalidDecl = true;
14325   }
14326 
14327   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14328   // than a variably modified type.
14329   if (!InvalidDecl && T->isVariablyModifiedType()) {
14330     bool SizeIsNegative;
14331     llvm::APSInt Oversized;
14332 
14333     TypeSourceInfo *FixedTInfo =
14334       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14335                                                     SizeIsNegative,
14336                                                     Oversized);
14337     if (FixedTInfo) {
14338       Diag(Loc, diag::warn_illegal_constant_array_size);
14339       TInfo = FixedTInfo;
14340       T = FixedTInfo->getType();
14341     } else {
14342       if (SizeIsNegative)
14343         Diag(Loc, diag::err_typecheck_negative_array_size);
14344       else if (Oversized.getBoolValue())
14345         Diag(Loc, diag::err_array_too_large)
14346           << Oversized.toString(10);
14347       else
14348         Diag(Loc, diag::err_typecheck_field_variable_size);
14349       InvalidDecl = true;
14350     }
14351   }
14352 
14353   // Fields can not have abstract class types
14354   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14355                                              diag::err_abstract_type_in_decl,
14356                                              AbstractFieldType))
14357     InvalidDecl = true;
14358 
14359   bool ZeroWidth = false;
14360   if (InvalidDecl)
14361     BitWidth = nullptr;
14362   // If this is declared as a bit-field, check the bit-field.
14363   if (BitWidth) {
14364     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14365                               &ZeroWidth).get();
14366     if (!BitWidth) {
14367       InvalidDecl = true;
14368       BitWidth = nullptr;
14369       ZeroWidth = false;
14370     }
14371   }
14372 
14373   // Check that 'mutable' is consistent with the type of the declaration.
14374   if (!InvalidDecl && Mutable) {
14375     unsigned DiagID = 0;
14376     if (T->isReferenceType())
14377       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14378                                         : diag::err_mutable_reference;
14379     else if (T.isConstQualified())
14380       DiagID = diag::err_mutable_const;
14381 
14382     if (DiagID) {
14383       SourceLocation ErrLoc = Loc;
14384       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14385         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14386       Diag(ErrLoc, DiagID);
14387       if (DiagID != diag::ext_mutable_reference) {
14388         Mutable = false;
14389         InvalidDecl = true;
14390       }
14391     }
14392   }
14393 
14394   // C++11 [class.union]p8 (DR1460):
14395   //   At most one variant member of a union may have a
14396   //   brace-or-equal-initializer.
14397   if (InitStyle != ICIS_NoInit)
14398     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14399 
14400   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14401                                        BitWidth, Mutable, InitStyle);
14402   if (InvalidDecl)
14403     NewFD->setInvalidDecl();
14404 
14405   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14406     Diag(Loc, diag::err_duplicate_member) << II;
14407     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14408     NewFD->setInvalidDecl();
14409   }
14410 
14411   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14412     if (Record->isUnion()) {
14413       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14414         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14415         if (RDecl->getDefinition()) {
14416           // C++ [class.union]p1: An object of a class with a non-trivial
14417           // constructor, a non-trivial copy constructor, a non-trivial
14418           // destructor, or a non-trivial copy assignment operator
14419           // cannot be a member of a union, nor can an array of such
14420           // objects.
14421           if (CheckNontrivialField(NewFD))
14422             NewFD->setInvalidDecl();
14423         }
14424       }
14425 
14426       // C++ [class.union]p1: If a union contains a member of reference type,
14427       // the program is ill-formed, except when compiling with MSVC extensions
14428       // enabled.
14429       if (EltTy->isReferenceType()) {
14430         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14431                                     diag::ext_union_member_of_reference_type :
14432                                     diag::err_union_member_of_reference_type)
14433           << NewFD->getDeclName() << EltTy;
14434         if (!getLangOpts().MicrosoftExt)
14435           NewFD->setInvalidDecl();
14436       }
14437     }
14438   }
14439 
14440   // FIXME: We need to pass in the attributes given an AST
14441   // representation, not a parser representation.
14442   if (D) {
14443     // FIXME: The current scope is almost... but not entirely... correct here.
14444     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14445 
14446     if (NewFD->hasAttrs())
14447       CheckAlignasUnderalignment(NewFD);
14448   }
14449 
14450   // In auto-retain/release, infer strong retension for fields of
14451   // retainable type.
14452   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14453     NewFD->setInvalidDecl();
14454 
14455   if (T.isObjCGCWeak())
14456     Diag(Loc, diag::warn_attribute_weak_on_field);
14457 
14458   NewFD->setAccess(AS);
14459   return NewFD;
14460 }
14461 
14462 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14463   assert(FD);
14464   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14465 
14466   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14467     return false;
14468 
14469   QualType EltTy = Context.getBaseElementType(FD->getType());
14470   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14471     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14472     if (RDecl->getDefinition()) {
14473       // We check for copy constructors before constructors
14474       // because otherwise we'll never get complaints about
14475       // copy constructors.
14476 
14477       CXXSpecialMember member = CXXInvalid;
14478       // We're required to check for any non-trivial constructors. Since the
14479       // implicit default constructor is suppressed if there are any
14480       // user-declared constructors, we just need to check that there is a
14481       // trivial default constructor and a trivial copy constructor. (We don't
14482       // worry about move constructors here, since this is a C++98 check.)
14483       if (RDecl->hasNonTrivialCopyConstructor())
14484         member = CXXCopyConstructor;
14485       else if (!RDecl->hasTrivialDefaultConstructor())
14486         member = CXXDefaultConstructor;
14487       else if (RDecl->hasNonTrivialCopyAssignment())
14488         member = CXXCopyAssignment;
14489       else if (RDecl->hasNonTrivialDestructor())
14490         member = CXXDestructor;
14491 
14492       if (member != CXXInvalid) {
14493         if (!getLangOpts().CPlusPlus11 &&
14494             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14495           // Objective-C++ ARC: it is an error to have a non-trivial field of
14496           // a union. However, system headers in Objective-C programs
14497           // occasionally have Objective-C lifetime objects within unions,
14498           // and rather than cause the program to fail, we make those
14499           // members unavailable.
14500           SourceLocation Loc = FD->getLocation();
14501           if (getSourceManager().isInSystemHeader(Loc)) {
14502             if (!FD->hasAttr<UnavailableAttr>())
14503               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14504                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14505             return false;
14506           }
14507         }
14508 
14509         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14510                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14511                diag::err_illegal_union_or_anon_struct_member)
14512           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14513         DiagnoseNontrivial(RDecl, member);
14514         return !getLangOpts().CPlusPlus11;
14515       }
14516     }
14517   }
14518 
14519   return false;
14520 }
14521 
14522 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14523 ///  AST enum value.
14524 static ObjCIvarDecl::AccessControl
14525 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14526   switch (ivarVisibility) {
14527   default: llvm_unreachable("Unknown visitibility kind");
14528   case tok::objc_private: return ObjCIvarDecl::Private;
14529   case tok::objc_public: return ObjCIvarDecl::Public;
14530   case tok::objc_protected: return ObjCIvarDecl::Protected;
14531   case tok::objc_package: return ObjCIvarDecl::Package;
14532   }
14533 }
14534 
14535 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14536 /// in order to create an IvarDecl object for it.
14537 Decl *Sema::ActOnIvar(Scope *S,
14538                                 SourceLocation DeclStart,
14539                                 Declarator &D, Expr *BitfieldWidth,
14540                                 tok::ObjCKeywordKind Visibility) {
14541 
14542   IdentifierInfo *II = D.getIdentifier();
14543   Expr *BitWidth = (Expr*)BitfieldWidth;
14544   SourceLocation Loc = DeclStart;
14545   if (II) Loc = D.getIdentifierLoc();
14546 
14547   // FIXME: Unnamed fields can be handled in various different ways, for
14548   // example, unnamed unions inject all members into the struct namespace!
14549 
14550   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14551   QualType T = TInfo->getType();
14552 
14553   if (BitWidth) {
14554     // 6.7.2.1p3, 6.7.2.1p4
14555     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14556     if (!BitWidth)
14557       D.setInvalidType();
14558   } else {
14559     // Not a bitfield.
14560 
14561     // validate II.
14562 
14563   }
14564   if (T->isReferenceType()) {
14565     Diag(Loc, diag::err_ivar_reference_type);
14566     D.setInvalidType();
14567   }
14568   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14569   // than a variably modified type.
14570   else if (T->isVariablyModifiedType()) {
14571     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14572     D.setInvalidType();
14573   }
14574 
14575   // Get the visibility (access control) for this ivar.
14576   ObjCIvarDecl::AccessControl ac =
14577     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14578                                         : ObjCIvarDecl::None;
14579   // Must set ivar's DeclContext to its enclosing interface.
14580   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14581   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14582     return nullptr;
14583   ObjCContainerDecl *EnclosingContext;
14584   if (ObjCImplementationDecl *IMPDecl =
14585       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14586     if (LangOpts.ObjCRuntime.isFragile()) {
14587     // Case of ivar declared in an implementation. Context is that of its class.
14588       EnclosingContext = IMPDecl->getClassInterface();
14589       assert(EnclosingContext && "Implementation has no class interface!");
14590     }
14591     else
14592       EnclosingContext = EnclosingDecl;
14593   } else {
14594     if (ObjCCategoryDecl *CDecl =
14595         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14596       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14597         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14598         return nullptr;
14599       }
14600     }
14601     EnclosingContext = EnclosingDecl;
14602   }
14603 
14604   // Construct the decl.
14605   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14606                                              DeclStart, Loc, II, T,
14607                                              TInfo, ac, (Expr *)BitfieldWidth);
14608 
14609   if (II) {
14610     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14611                                            ForRedeclaration);
14612     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14613         && !isa<TagDecl>(PrevDecl)) {
14614       Diag(Loc, diag::err_duplicate_member) << II;
14615       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14616       NewID->setInvalidDecl();
14617     }
14618   }
14619 
14620   // Process attributes attached to the ivar.
14621   ProcessDeclAttributes(S, NewID, D);
14622 
14623   if (D.isInvalidType())
14624     NewID->setInvalidDecl();
14625 
14626   // In ARC, infer 'retaining' for ivars of retainable type.
14627   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14628     NewID->setInvalidDecl();
14629 
14630   if (D.getDeclSpec().isModulePrivateSpecified())
14631     NewID->setModulePrivate();
14632 
14633   if (II) {
14634     // FIXME: When interfaces are DeclContexts, we'll need to add
14635     // these to the interface.
14636     S->AddDecl(NewID);
14637     IdResolver.AddDecl(NewID);
14638   }
14639 
14640   if (LangOpts.ObjCRuntime.isNonFragile() &&
14641       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14642     Diag(Loc, diag::warn_ivars_in_interface);
14643 
14644   return NewID;
14645 }
14646 
14647 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14648 /// class and class extensions. For every class \@interface and class
14649 /// extension \@interface, if the last ivar is a bitfield of any type,
14650 /// then add an implicit `char :0` ivar to the end of that interface.
14651 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14652                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14653   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14654     return;
14655 
14656   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14657   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14658 
14659   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14660     return;
14661   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14662   if (!ID) {
14663     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14664       if (!CD->IsClassExtension())
14665         return;
14666     }
14667     // No need to add this to end of @implementation.
14668     else
14669       return;
14670   }
14671   // All conditions are met. Add a new bitfield to the tail end of ivars.
14672   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14673   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14674 
14675   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14676                               DeclLoc, DeclLoc, nullptr,
14677                               Context.CharTy,
14678                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14679                                                                DeclLoc),
14680                               ObjCIvarDecl::Private, BW,
14681                               true);
14682   AllIvarDecls.push_back(Ivar);
14683 }
14684 
14685 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14686                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14687                        SourceLocation RBrac, AttributeList *Attr) {
14688   assert(EnclosingDecl && "missing record or interface decl");
14689 
14690   // If this is an Objective-C @implementation or category and we have
14691   // new fields here we should reset the layout of the interface since
14692   // it will now change.
14693   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14694     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14695     switch (DC->getKind()) {
14696     default: break;
14697     case Decl::ObjCCategory:
14698       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14699       break;
14700     case Decl::ObjCImplementation:
14701       Context.
14702         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14703       break;
14704     }
14705   }
14706 
14707   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14708 
14709   // Start counting up the number of named members; make sure to include
14710   // members of anonymous structs and unions in the total.
14711   unsigned NumNamedMembers = 0;
14712   if (Record) {
14713     for (const auto *I : Record->decls()) {
14714       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14715         if (IFD->getDeclName())
14716           ++NumNamedMembers;
14717     }
14718   }
14719 
14720   // Verify that all the fields are okay.
14721   SmallVector<FieldDecl*, 32> RecFields;
14722 
14723   bool ObjCFieldLifetimeErrReported = false;
14724   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14725        i != end; ++i) {
14726     FieldDecl *FD = cast<FieldDecl>(*i);
14727 
14728     // Get the type for the field.
14729     const Type *FDTy = FD->getType().getTypePtr();
14730 
14731     if (!FD->isAnonymousStructOrUnion()) {
14732       // Remember all fields written by the user.
14733       RecFields.push_back(FD);
14734     }
14735 
14736     // If the field is already invalid for some reason, don't emit more
14737     // diagnostics about it.
14738     if (FD->isInvalidDecl()) {
14739       EnclosingDecl->setInvalidDecl();
14740       continue;
14741     }
14742 
14743     // C99 6.7.2.1p2:
14744     //   A structure or union shall not contain a member with
14745     //   incomplete or function type (hence, a structure shall not
14746     //   contain an instance of itself, but may contain a pointer to
14747     //   an instance of itself), except that the last member of a
14748     //   structure with more than one named member may have incomplete
14749     //   array type; such a structure (and any union containing,
14750     //   possibly recursively, a member that is such a structure)
14751     //   shall not be a member of a structure or an element of an
14752     //   array.
14753     if (FDTy->isFunctionType()) {
14754       // Field declared as a function.
14755       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14756         << FD->getDeclName();
14757       FD->setInvalidDecl();
14758       EnclosingDecl->setInvalidDecl();
14759       continue;
14760     } else if (FDTy->isIncompleteArrayType() && Record &&
14761                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14762                 ((getLangOpts().MicrosoftExt ||
14763                   getLangOpts().CPlusPlus) &&
14764                  (i + 1 == Fields.end() || Record->isUnion())))) {
14765       // Flexible array member.
14766       // Microsoft and g++ is more permissive regarding flexible array.
14767       // It will accept flexible array in union and also
14768       // as the sole element of a struct/class.
14769       unsigned DiagID = 0;
14770       if (Record->isUnion())
14771         DiagID = getLangOpts().MicrosoftExt
14772                      ? diag::ext_flexible_array_union_ms
14773                      : getLangOpts().CPlusPlus
14774                            ? diag::ext_flexible_array_union_gnu
14775                            : diag::err_flexible_array_union;
14776       else if (NumNamedMembers < 1)
14777         DiagID = getLangOpts().MicrosoftExt
14778                      ? diag::ext_flexible_array_empty_aggregate_ms
14779                      : getLangOpts().CPlusPlus
14780                            ? diag::ext_flexible_array_empty_aggregate_gnu
14781                            : diag::err_flexible_array_empty_aggregate;
14782 
14783       if (DiagID)
14784         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14785                                         << Record->getTagKind();
14786       // While the layout of types that contain virtual bases is not specified
14787       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14788       // virtual bases after the derived members.  This would make a flexible
14789       // array member declared at the end of an object not adjacent to the end
14790       // of the type.
14791       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14792         if (RD->getNumVBases() != 0)
14793           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14794             << FD->getDeclName() << Record->getTagKind();
14795       if (!getLangOpts().C99)
14796         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14797           << FD->getDeclName() << Record->getTagKind();
14798 
14799       // If the element type has a non-trivial destructor, we would not
14800       // implicitly destroy the elements, so disallow it for now.
14801       //
14802       // FIXME: GCC allows this. We should probably either implicitly delete
14803       // the destructor of the containing class, or just allow this.
14804       QualType BaseElem = Context.getBaseElementType(FD->getType());
14805       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14806         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14807           << FD->getDeclName() << FD->getType();
14808         FD->setInvalidDecl();
14809         EnclosingDecl->setInvalidDecl();
14810         continue;
14811       }
14812       // Okay, we have a legal flexible array member at the end of the struct.
14813       Record->setHasFlexibleArrayMember(true);
14814     } else if (!FDTy->isDependentType() &&
14815                RequireCompleteType(FD->getLocation(), FD->getType(),
14816                                    diag::err_field_incomplete)) {
14817       // Incomplete type
14818       FD->setInvalidDecl();
14819       EnclosingDecl->setInvalidDecl();
14820       continue;
14821     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14822       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14823         // A type which contains a flexible array member is considered to be a
14824         // flexible array member.
14825         Record->setHasFlexibleArrayMember(true);
14826         if (!Record->isUnion()) {
14827           // If this is a struct/class and this is not the last element, reject
14828           // it.  Note that GCC supports variable sized arrays in the middle of
14829           // structures.
14830           if (i + 1 != Fields.end())
14831             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14832               << FD->getDeclName() << FD->getType();
14833           else {
14834             // We support flexible arrays at the end of structs in
14835             // other structs as an extension.
14836             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14837               << FD->getDeclName();
14838           }
14839         }
14840       }
14841       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14842           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14843                                  diag::err_abstract_type_in_decl,
14844                                  AbstractIvarType)) {
14845         // Ivars can not have abstract class types
14846         FD->setInvalidDecl();
14847       }
14848       if (Record && FDTTy->getDecl()->hasObjectMember())
14849         Record->setHasObjectMember(true);
14850       if (Record && FDTTy->getDecl()->hasVolatileMember())
14851         Record->setHasVolatileMember(true);
14852     } else if (FDTy->isObjCObjectType()) {
14853       /// A field cannot be an Objective-c object
14854       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14855         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14856       QualType T = Context.getObjCObjectPointerType(FD->getType());
14857       FD->setType(T);
14858     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14859                Record && !ObjCFieldLifetimeErrReported &&
14860                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14861       // It's an error in ARC or Weak if a field has lifetime.
14862       // We don't want to report this in a system header, though,
14863       // so we just make the field unavailable.
14864       // FIXME: that's really not sufficient; we need to make the type
14865       // itself invalid to, say, initialize or copy.
14866       QualType T = FD->getType();
14867       if (T.hasNonTrivialObjCLifetime()) {
14868         SourceLocation loc = FD->getLocation();
14869         if (getSourceManager().isInSystemHeader(loc)) {
14870           if (!FD->hasAttr<UnavailableAttr>()) {
14871             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14872                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14873           }
14874         } else {
14875           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14876             << T->isBlockPointerType() << Record->getTagKind();
14877         }
14878         ObjCFieldLifetimeErrReported = true;
14879       }
14880     } else if (getLangOpts().ObjC1 &&
14881                getLangOpts().getGC() != LangOptions::NonGC &&
14882                Record && !Record->hasObjectMember()) {
14883       if (FD->getType()->isObjCObjectPointerType() ||
14884           FD->getType().isObjCGCStrong())
14885         Record->setHasObjectMember(true);
14886       else if (Context.getAsArrayType(FD->getType())) {
14887         QualType BaseType = Context.getBaseElementType(FD->getType());
14888         if (BaseType->isRecordType() &&
14889             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14890           Record->setHasObjectMember(true);
14891         else if (BaseType->isObjCObjectPointerType() ||
14892                  BaseType.isObjCGCStrong())
14893                Record->setHasObjectMember(true);
14894       }
14895     }
14896     if (Record && FD->getType().isVolatileQualified())
14897       Record->setHasVolatileMember(true);
14898     // Keep track of the number of named members.
14899     if (FD->getIdentifier())
14900       ++NumNamedMembers;
14901   }
14902 
14903   // Okay, we successfully defined 'Record'.
14904   if (Record) {
14905     bool Completed = false;
14906     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14907       if (!CXXRecord->isInvalidDecl()) {
14908         // Set access bits correctly on the directly-declared conversions.
14909         for (CXXRecordDecl::conversion_iterator
14910                I = CXXRecord->conversion_begin(),
14911                E = CXXRecord->conversion_end(); I != E; ++I)
14912           I.setAccess((*I)->getAccess());
14913       }
14914 
14915       if (!CXXRecord->isDependentType()) {
14916         if (CXXRecord->hasUserDeclaredDestructor()) {
14917           // Adjust user-defined destructor exception spec.
14918           if (getLangOpts().CPlusPlus11)
14919             AdjustDestructorExceptionSpec(CXXRecord,
14920                                           CXXRecord->getDestructor());
14921         }
14922 
14923         if (!CXXRecord->isInvalidDecl()) {
14924           // Add any implicitly-declared members to this class.
14925           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14926 
14927           // If we have virtual base classes, we may end up finding multiple
14928           // final overriders for a given virtual function. Check for this
14929           // problem now.
14930           if (CXXRecord->getNumVBases()) {
14931             CXXFinalOverriderMap FinalOverriders;
14932             CXXRecord->getFinalOverriders(FinalOverriders);
14933 
14934             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14935                                              MEnd = FinalOverriders.end();
14936                  M != MEnd; ++M) {
14937               for (OverridingMethods::iterator SO = M->second.begin(),
14938                                             SOEnd = M->second.end();
14939                    SO != SOEnd; ++SO) {
14940                 assert(SO->second.size() > 0 &&
14941                        "Virtual function without overridding functions?");
14942                 if (SO->second.size() == 1)
14943                   continue;
14944 
14945                 // C++ [class.virtual]p2:
14946                 //   In a derived class, if a virtual member function of a base
14947                 //   class subobject has more than one final overrider the
14948                 //   program is ill-formed.
14949                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14950                   << (const NamedDecl *)M->first << Record;
14951                 Diag(M->first->getLocation(),
14952                      diag::note_overridden_virtual_function);
14953                 for (OverridingMethods::overriding_iterator
14954                           OM = SO->second.begin(),
14955                        OMEnd = SO->second.end();
14956                      OM != OMEnd; ++OM)
14957                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14958                     << (const NamedDecl *)M->first << OM->Method->getParent();
14959 
14960                 Record->setInvalidDecl();
14961               }
14962             }
14963             CXXRecord->completeDefinition(&FinalOverriders);
14964             Completed = true;
14965           }
14966         }
14967       }
14968     }
14969 
14970     if (!Completed)
14971       Record->completeDefinition();
14972 
14973     // We may have deferred checking for a deleted destructor. Check now.
14974     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14975       auto *Dtor = CXXRecord->getDestructor();
14976       if (Dtor && Dtor->isImplicit() &&
14977           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14978         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14979     }
14980 
14981     if (Record->hasAttrs()) {
14982       CheckAlignasUnderalignment(Record);
14983 
14984       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14985         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14986                                            IA->getRange(), IA->getBestCase(),
14987                                            IA->getSemanticSpelling());
14988     }
14989 
14990     // Check if the structure/union declaration is a type that can have zero
14991     // size in C. For C this is a language extension, for C++ it may cause
14992     // compatibility problems.
14993     bool CheckForZeroSize;
14994     if (!getLangOpts().CPlusPlus) {
14995       CheckForZeroSize = true;
14996     } else {
14997       // For C++ filter out types that cannot be referenced in C code.
14998       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14999       CheckForZeroSize =
15000           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15001           !CXXRecord->isDependentType() &&
15002           CXXRecord->isCLike();
15003     }
15004     if (CheckForZeroSize) {
15005       bool ZeroSize = true;
15006       bool IsEmpty = true;
15007       unsigned NonBitFields = 0;
15008       for (RecordDecl::field_iterator I = Record->field_begin(),
15009                                       E = Record->field_end();
15010            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15011         IsEmpty = false;
15012         if (I->isUnnamedBitfield()) {
15013           if (I->getBitWidthValue(Context) > 0)
15014             ZeroSize = false;
15015         } else {
15016           ++NonBitFields;
15017           QualType FieldType = I->getType();
15018           if (FieldType->isIncompleteType() ||
15019               !Context.getTypeSizeInChars(FieldType).isZero())
15020             ZeroSize = false;
15021         }
15022       }
15023 
15024       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15025       // allowed in C++, but warn if its declaration is inside
15026       // extern "C" block.
15027       if (ZeroSize) {
15028         Diag(RecLoc, getLangOpts().CPlusPlus ?
15029                          diag::warn_zero_size_struct_union_in_extern_c :
15030                          diag::warn_zero_size_struct_union_compat)
15031           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15032       }
15033 
15034       // Structs without named members are extension in C (C99 6.7.2.1p7),
15035       // but are accepted by GCC.
15036       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15037         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15038                                diag::ext_no_named_members_in_struct_union)
15039           << Record->isUnion();
15040       }
15041     }
15042   } else {
15043     ObjCIvarDecl **ClsFields =
15044       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15045     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15046       ID->setEndOfDefinitionLoc(RBrac);
15047       // Add ivar's to class's DeclContext.
15048       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15049         ClsFields[i]->setLexicalDeclContext(ID);
15050         ID->addDecl(ClsFields[i]);
15051       }
15052       // Must enforce the rule that ivars in the base classes may not be
15053       // duplicates.
15054       if (ID->getSuperClass())
15055         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15056     } else if (ObjCImplementationDecl *IMPDecl =
15057                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15058       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15059       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15060         // Ivar declared in @implementation never belongs to the implementation.
15061         // Only it is in implementation's lexical context.
15062         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15063       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15064       IMPDecl->setIvarLBraceLoc(LBrac);
15065       IMPDecl->setIvarRBraceLoc(RBrac);
15066     } else if (ObjCCategoryDecl *CDecl =
15067                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15068       // case of ivars in class extension; all other cases have been
15069       // reported as errors elsewhere.
15070       // FIXME. Class extension does not have a LocEnd field.
15071       // CDecl->setLocEnd(RBrac);
15072       // Add ivar's to class extension's DeclContext.
15073       // Diagnose redeclaration of private ivars.
15074       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15075       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15076         if (IDecl) {
15077           if (const ObjCIvarDecl *ClsIvar =
15078               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15079             Diag(ClsFields[i]->getLocation(),
15080                  diag::err_duplicate_ivar_declaration);
15081             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15082             continue;
15083           }
15084           for (const auto *Ext : IDecl->known_extensions()) {
15085             if (const ObjCIvarDecl *ClsExtIvar
15086                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15087               Diag(ClsFields[i]->getLocation(),
15088                    diag::err_duplicate_ivar_declaration);
15089               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15090               continue;
15091             }
15092           }
15093         }
15094         ClsFields[i]->setLexicalDeclContext(CDecl);
15095         CDecl->addDecl(ClsFields[i]);
15096       }
15097       CDecl->setIvarLBraceLoc(LBrac);
15098       CDecl->setIvarRBraceLoc(RBrac);
15099     }
15100   }
15101 
15102   if (Attr)
15103     ProcessDeclAttributeList(S, Record, Attr);
15104 }
15105 
15106 /// \brief Determine whether the given integral value is representable within
15107 /// the given type T.
15108 static bool isRepresentableIntegerValue(ASTContext &Context,
15109                                         llvm::APSInt &Value,
15110                                         QualType T) {
15111   assert(T->isIntegralType(Context) && "Integral type required!");
15112   unsigned BitWidth = Context.getIntWidth(T);
15113 
15114   if (Value.isUnsigned() || Value.isNonNegative()) {
15115     if (T->isSignedIntegerOrEnumerationType())
15116       --BitWidth;
15117     return Value.getActiveBits() <= BitWidth;
15118   }
15119   return Value.getMinSignedBits() <= BitWidth;
15120 }
15121 
15122 // \brief Given an integral type, return the next larger integral type
15123 // (or a NULL type of no such type exists).
15124 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15125   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15126   // enum checking below.
15127   assert(T->isIntegralType(Context) && "Integral type required!");
15128   const unsigned NumTypes = 4;
15129   QualType SignedIntegralTypes[NumTypes] = {
15130     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15131   };
15132   QualType UnsignedIntegralTypes[NumTypes] = {
15133     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15134     Context.UnsignedLongLongTy
15135   };
15136 
15137   unsigned BitWidth = Context.getTypeSize(T);
15138   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15139                                                         : UnsignedIntegralTypes;
15140   for (unsigned I = 0; I != NumTypes; ++I)
15141     if (Context.getTypeSize(Types[I]) > BitWidth)
15142       return Types[I];
15143 
15144   return QualType();
15145 }
15146 
15147 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15148                                           EnumConstantDecl *LastEnumConst,
15149                                           SourceLocation IdLoc,
15150                                           IdentifierInfo *Id,
15151                                           Expr *Val) {
15152   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15153   llvm::APSInt EnumVal(IntWidth);
15154   QualType EltTy;
15155 
15156   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15157     Val = nullptr;
15158 
15159   if (Val)
15160     Val = DefaultLvalueConversion(Val).get();
15161 
15162   if (Val) {
15163     if (Enum->isDependentType() || Val->isTypeDependent())
15164       EltTy = Context.DependentTy;
15165     else {
15166       SourceLocation ExpLoc;
15167       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15168           !getLangOpts().MSVCCompat) {
15169         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15170         // constant-expression in the enumerator-definition shall be a converted
15171         // constant expression of the underlying type.
15172         EltTy = Enum->getIntegerType();
15173         ExprResult Converted =
15174           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15175                                            CCEK_Enumerator);
15176         if (Converted.isInvalid())
15177           Val = nullptr;
15178         else
15179           Val = Converted.get();
15180       } else if (!Val->isValueDependent() &&
15181                  !(Val = VerifyIntegerConstantExpression(Val,
15182                                                          &EnumVal).get())) {
15183         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15184       } else {
15185         if (Enum->isFixed()) {
15186           EltTy = Enum->getIntegerType();
15187 
15188           // In Obj-C and Microsoft mode, require the enumeration value to be
15189           // representable in the underlying type of the enumeration. In C++11,
15190           // we perform a non-narrowing conversion as part of converted constant
15191           // expression checking.
15192           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15193             if (getLangOpts().MSVCCompat) {
15194               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15195               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15196             } else
15197               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15198           } else
15199             Val = ImpCastExprToType(Val, EltTy,
15200                                     EltTy->isBooleanType() ?
15201                                     CK_IntegralToBoolean : CK_IntegralCast)
15202                     .get();
15203         } else if (getLangOpts().CPlusPlus) {
15204           // C++11 [dcl.enum]p5:
15205           //   If the underlying type is not fixed, the type of each enumerator
15206           //   is the type of its initializing value:
15207           //     - If an initializer is specified for an enumerator, the
15208           //       initializing value has the same type as the expression.
15209           EltTy = Val->getType();
15210         } else {
15211           // C99 6.7.2.2p2:
15212           //   The expression that defines the value of an enumeration constant
15213           //   shall be an integer constant expression that has a value
15214           //   representable as an int.
15215 
15216           // Complain if the value is not representable in an int.
15217           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15218             Diag(IdLoc, diag::ext_enum_value_not_int)
15219               << EnumVal.toString(10) << Val->getSourceRange()
15220               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15221           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15222             // Force the type of the expression to 'int'.
15223             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15224           }
15225           EltTy = Val->getType();
15226         }
15227       }
15228     }
15229   }
15230 
15231   if (!Val) {
15232     if (Enum->isDependentType())
15233       EltTy = Context.DependentTy;
15234     else if (!LastEnumConst) {
15235       // C++0x [dcl.enum]p5:
15236       //   If the underlying type is not fixed, the type of each enumerator
15237       //   is the type of its initializing value:
15238       //     - If no initializer is specified for the first enumerator, the
15239       //       initializing value has an unspecified integral type.
15240       //
15241       // GCC uses 'int' for its unspecified integral type, as does
15242       // C99 6.7.2.2p3.
15243       if (Enum->isFixed()) {
15244         EltTy = Enum->getIntegerType();
15245       }
15246       else {
15247         EltTy = Context.IntTy;
15248       }
15249     } else {
15250       // Assign the last value + 1.
15251       EnumVal = LastEnumConst->getInitVal();
15252       ++EnumVal;
15253       EltTy = LastEnumConst->getType();
15254 
15255       // Check for overflow on increment.
15256       if (EnumVal < LastEnumConst->getInitVal()) {
15257         // C++0x [dcl.enum]p5:
15258         //   If the underlying type is not fixed, the type of each enumerator
15259         //   is the type of its initializing value:
15260         //
15261         //     - Otherwise the type of the initializing value is the same as
15262         //       the type of the initializing value of the preceding enumerator
15263         //       unless the incremented value is not representable in that type,
15264         //       in which case the type is an unspecified integral type
15265         //       sufficient to contain the incremented value. If no such type
15266         //       exists, the program is ill-formed.
15267         QualType T = getNextLargerIntegralType(Context, EltTy);
15268         if (T.isNull() || Enum->isFixed()) {
15269           // There is no integral type larger enough to represent this
15270           // value. Complain, then allow the value to wrap around.
15271           EnumVal = LastEnumConst->getInitVal();
15272           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15273           ++EnumVal;
15274           if (Enum->isFixed())
15275             // When the underlying type is fixed, this is ill-formed.
15276             Diag(IdLoc, diag::err_enumerator_wrapped)
15277               << EnumVal.toString(10)
15278               << EltTy;
15279           else
15280             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15281               << EnumVal.toString(10);
15282         } else {
15283           EltTy = T;
15284         }
15285 
15286         // Retrieve the last enumerator's value, extent that type to the
15287         // type that is supposed to be large enough to represent the incremented
15288         // value, then increment.
15289         EnumVal = LastEnumConst->getInitVal();
15290         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15291         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15292         ++EnumVal;
15293 
15294         // If we're not in C++, diagnose the overflow of enumerator values,
15295         // which in C99 means that the enumerator value is not representable in
15296         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15297         // permits enumerator values that are representable in some larger
15298         // integral type.
15299         if (!getLangOpts().CPlusPlus && !T.isNull())
15300           Diag(IdLoc, diag::warn_enum_value_overflow);
15301       } else if (!getLangOpts().CPlusPlus &&
15302                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15303         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15304         Diag(IdLoc, diag::ext_enum_value_not_int)
15305           << EnumVal.toString(10) << 1;
15306       }
15307     }
15308   }
15309 
15310   if (!EltTy->isDependentType()) {
15311     // Make the enumerator value match the signedness and size of the
15312     // enumerator's type.
15313     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15314     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15315   }
15316 
15317   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15318                                   Val, EnumVal);
15319 }
15320 
15321 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15322                                                 SourceLocation IILoc) {
15323   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15324       !getLangOpts().CPlusPlus)
15325     return SkipBodyInfo();
15326 
15327   // We have an anonymous enum definition. Look up the first enumerator to
15328   // determine if we should merge the definition with an existing one and
15329   // skip the body.
15330   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15331                                          ForRedeclaration);
15332   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15333   if (!PrevECD)
15334     return SkipBodyInfo();
15335 
15336   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15337   NamedDecl *Hidden;
15338   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15339     SkipBodyInfo Skip;
15340     Skip.Previous = Hidden;
15341     return Skip;
15342   }
15343 
15344   return SkipBodyInfo();
15345 }
15346 
15347 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15348                               SourceLocation IdLoc, IdentifierInfo *Id,
15349                               AttributeList *Attr,
15350                               SourceLocation EqualLoc, Expr *Val) {
15351   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15352   EnumConstantDecl *LastEnumConst =
15353     cast_or_null<EnumConstantDecl>(lastEnumConst);
15354 
15355   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15356   // we find one that is.
15357   S = getNonFieldDeclScope(S);
15358 
15359   // Verify that there isn't already something declared with this name in this
15360   // scope.
15361   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15362                                          ForRedeclaration);
15363   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15364     // Maybe we will complain about the shadowed template parameter.
15365     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15366     // Just pretend that we didn't see the previous declaration.
15367     PrevDecl = nullptr;
15368   }
15369 
15370   // C++ [class.mem]p15:
15371   // If T is the name of a class, then each of the following shall have a name
15372   // different from T:
15373   // - every enumerator of every member of class T that is an unscoped
15374   // enumerated type
15375   if (!TheEnumDecl->isScoped())
15376     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15377                             DeclarationNameInfo(Id, IdLoc));
15378 
15379   EnumConstantDecl *New =
15380     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15381   if (!New)
15382     return nullptr;
15383 
15384   if (PrevDecl) {
15385     // When in C++, we may get a TagDecl with the same name; in this case the
15386     // enum constant will 'hide' the tag.
15387     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15388            "Received TagDecl when not in C++!");
15389     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15390         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15391       if (isa<EnumConstantDecl>(PrevDecl))
15392         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15393       else
15394         Diag(IdLoc, diag::err_redefinition) << Id;
15395       notePreviousDefinition(PrevDecl, IdLoc);
15396       return nullptr;
15397     }
15398   }
15399 
15400   // Process attributes.
15401   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15402   AddPragmaAttributes(S, New);
15403 
15404   // Register this decl in the current scope stack.
15405   New->setAccess(TheEnumDecl->getAccess());
15406   PushOnScopeChains(New, S);
15407 
15408   ActOnDocumentableDecl(New);
15409 
15410   return New;
15411 }
15412 
15413 // Returns true when the enum initial expression does not trigger the
15414 // duplicate enum warning.  A few common cases are exempted as follows:
15415 // Element2 = Element1
15416 // Element2 = Element1 + 1
15417 // Element2 = Element1 - 1
15418 // Where Element2 and Element1 are from the same enum.
15419 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15420   Expr *InitExpr = ECD->getInitExpr();
15421   if (!InitExpr)
15422     return true;
15423   InitExpr = InitExpr->IgnoreImpCasts();
15424 
15425   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15426     if (!BO->isAdditiveOp())
15427       return true;
15428     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15429     if (!IL)
15430       return true;
15431     if (IL->getValue() != 1)
15432       return true;
15433 
15434     InitExpr = BO->getLHS();
15435   }
15436 
15437   // This checks if the elements are from the same enum.
15438   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15439   if (!DRE)
15440     return true;
15441 
15442   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15443   if (!EnumConstant)
15444     return true;
15445 
15446   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15447       Enum)
15448     return true;
15449 
15450   return false;
15451 }
15452 
15453 namespace {
15454 struct DupKey {
15455   int64_t val;
15456   bool isTombstoneOrEmptyKey;
15457   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15458     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15459 };
15460 
15461 static DupKey GetDupKey(const llvm::APSInt& Val) {
15462   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15463                 false);
15464 }
15465 
15466 struct DenseMapInfoDupKey {
15467   static DupKey getEmptyKey() { return DupKey(0, true); }
15468   static DupKey getTombstoneKey() { return DupKey(1, true); }
15469   static unsigned getHashValue(const DupKey Key) {
15470     return (unsigned)(Key.val * 37);
15471   }
15472   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15473     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15474            LHS.val == RHS.val;
15475   }
15476 };
15477 } // end anonymous namespace
15478 
15479 // Emits a warning when an element is implicitly set a value that
15480 // a previous element has already been set to.
15481 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15482                                         EnumDecl *Enum,
15483                                         QualType EnumType) {
15484   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15485     return;
15486   // Avoid anonymous enums
15487   if (!Enum->getIdentifier())
15488     return;
15489 
15490   // Only check for small enums.
15491   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15492     return;
15493 
15494   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15495   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15496 
15497   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15498   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15499           ValueToVectorMap;
15500 
15501   DuplicatesVector DupVector;
15502   ValueToVectorMap EnumMap;
15503 
15504   // Populate the EnumMap with all values represented by enum constants without
15505   // an initialier.
15506   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15507     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15508 
15509     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15510     // this constant.  Skip this enum since it may be ill-formed.
15511     if (!ECD) {
15512       return;
15513     }
15514 
15515     if (ECD->getInitExpr())
15516       continue;
15517 
15518     DupKey Key = GetDupKey(ECD->getInitVal());
15519     DeclOrVector &Entry = EnumMap[Key];
15520 
15521     // First time encountering this value.
15522     if (Entry.isNull())
15523       Entry = ECD;
15524   }
15525 
15526   // Create vectors for any values that has duplicates.
15527   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15528     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15529     if (!ValidDuplicateEnum(ECD, Enum))
15530       continue;
15531 
15532     DupKey Key = GetDupKey(ECD->getInitVal());
15533 
15534     DeclOrVector& Entry = EnumMap[Key];
15535     if (Entry.isNull())
15536       continue;
15537 
15538     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15539       // Ensure constants are different.
15540       if (D == ECD)
15541         continue;
15542 
15543       // Create new vector and push values onto it.
15544       ECDVector *Vec = new ECDVector();
15545       Vec->push_back(D);
15546       Vec->push_back(ECD);
15547 
15548       // Update entry to point to the duplicates vector.
15549       Entry = Vec;
15550 
15551       // Store the vector somewhere we can consult later for quick emission of
15552       // diagnostics.
15553       DupVector.push_back(Vec);
15554       continue;
15555     }
15556 
15557     ECDVector *Vec = Entry.get<ECDVector*>();
15558     // Make sure constants are not added more than once.
15559     if (*Vec->begin() == ECD)
15560       continue;
15561 
15562     Vec->push_back(ECD);
15563   }
15564 
15565   // Emit diagnostics.
15566   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15567                                   DupVectorEnd = DupVector.end();
15568        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15569     ECDVector *Vec = *DupVectorIter;
15570     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15571 
15572     // Emit warning for one enum constant.
15573     ECDVector::iterator I = Vec->begin();
15574     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15575       << (*I)->getName() << (*I)->getInitVal().toString(10)
15576       << (*I)->getSourceRange();
15577     ++I;
15578 
15579     // Emit one note for each of the remaining enum constants with
15580     // the same value.
15581     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15582       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15583         << (*I)->getName() << (*I)->getInitVal().toString(10)
15584         << (*I)->getSourceRange();
15585     delete Vec;
15586   }
15587 }
15588 
15589 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15590                              bool AllowMask) const {
15591   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15592   assert(ED->isCompleteDefinition() && "expected enum definition");
15593 
15594   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15595   llvm::APInt &FlagBits = R.first->second;
15596 
15597   if (R.second) {
15598     for (auto *E : ED->enumerators()) {
15599       const auto &EVal = E->getInitVal();
15600       // Only single-bit enumerators introduce new flag values.
15601       if (EVal.isPowerOf2())
15602         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15603     }
15604   }
15605 
15606   // A value is in a flag enum if either its bits are a subset of the enum's
15607   // flag bits (the first condition) or we are allowing masks and the same is
15608   // true of its complement (the second condition). When masks are allowed, we
15609   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15610   //
15611   // While it's true that any value could be used as a mask, the assumption is
15612   // that a mask will have all of the insignificant bits set. Anything else is
15613   // likely a logic error.
15614   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15615   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15616 }
15617 
15618 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15619                          Decl *EnumDeclX,
15620                          ArrayRef<Decl *> Elements,
15621                          Scope *S, AttributeList *Attr) {
15622   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15623   QualType EnumType = Context.getTypeDeclType(Enum);
15624 
15625   if (Attr)
15626     ProcessDeclAttributeList(S, Enum, Attr);
15627 
15628   if (Enum->isDependentType()) {
15629     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15630       EnumConstantDecl *ECD =
15631         cast_or_null<EnumConstantDecl>(Elements[i]);
15632       if (!ECD) continue;
15633 
15634       ECD->setType(EnumType);
15635     }
15636 
15637     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15638     return;
15639   }
15640 
15641   // TODO: If the result value doesn't fit in an int, it must be a long or long
15642   // long value.  ISO C does not support this, but GCC does as an extension,
15643   // emit a warning.
15644   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15645   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15646   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15647 
15648   // Verify that all the values are okay, compute the size of the values, and
15649   // reverse the list.
15650   unsigned NumNegativeBits = 0;
15651   unsigned NumPositiveBits = 0;
15652 
15653   // Keep track of whether all elements have type int.
15654   bool AllElementsInt = true;
15655 
15656   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15657     EnumConstantDecl *ECD =
15658       cast_or_null<EnumConstantDecl>(Elements[i]);
15659     if (!ECD) continue;  // Already issued a diagnostic.
15660 
15661     const llvm::APSInt &InitVal = ECD->getInitVal();
15662 
15663     // Keep track of the size of positive and negative values.
15664     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15665       NumPositiveBits = std::max(NumPositiveBits,
15666                                  (unsigned)InitVal.getActiveBits());
15667     else
15668       NumNegativeBits = std::max(NumNegativeBits,
15669                                  (unsigned)InitVal.getMinSignedBits());
15670 
15671     // Keep track of whether every enum element has type int (very commmon).
15672     if (AllElementsInt)
15673       AllElementsInt = ECD->getType() == Context.IntTy;
15674   }
15675 
15676   // Figure out the type that should be used for this enum.
15677   QualType BestType;
15678   unsigned BestWidth;
15679 
15680   // C++0x N3000 [conv.prom]p3:
15681   //   An rvalue of an unscoped enumeration type whose underlying
15682   //   type is not fixed can be converted to an rvalue of the first
15683   //   of the following types that can represent all the values of
15684   //   the enumeration: int, unsigned int, long int, unsigned long
15685   //   int, long long int, or unsigned long long int.
15686   // C99 6.4.4.3p2:
15687   //   An identifier declared as an enumeration constant has type int.
15688   // The C99 rule is modified by a gcc extension
15689   QualType BestPromotionType;
15690 
15691   bool Packed = Enum->hasAttr<PackedAttr>();
15692   // -fshort-enums is the equivalent to specifying the packed attribute on all
15693   // enum definitions.
15694   if (LangOpts.ShortEnums)
15695     Packed = true;
15696 
15697   if (Enum->isFixed()) {
15698     BestType = Enum->getIntegerType();
15699     if (BestType->isPromotableIntegerType())
15700       BestPromotionType = Context.getPromotedIntegerType(BestType);
15701     else
15702       BestPromotionType = BestType;
15703 
15704     BestWidth = Context.getIntWidth(BestType);
15705   }
15706   else if (NumNegativeBits) {
15707     // If there is a negative value, figure out the smallest integer type (of
15708     // int/long/longlong) that fits.
15709     // If it's packed, check also if it fits a char or a short.
15710     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15711       BestType = Context.SignedCharTy;
15712       BestWidth = CharWidth;
15713     } else if (Packed && NumNegativeBits <= ShortWidth &&
15714                NumPositiveBits < ShortWidth) {
15715       BestType = Context.ShortTy;
15716       BestWidth = ShortWidth;
15717     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15718       BestType = Context.IntTy;
15719       BestWidth = IntWidth;
15720     } else {
15721       BestWidth = Context.getTargetInfo().getLongWidth();
15722 
15723       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15724         BestType = Context.LongTy;
15725       } else {
15726         BestWidth = Context.getTargetInfo().getLongLongWidth();
15727 
15728         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15729           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15730         BestType = Context.LongLongTy;
15731       }
15732     }
15733     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15734   } else {
15735     // If there is no negative value, figure out the smallest type that fits
15736     // all of the enumerator values.
15737     // If it's packed, check also if it fits a char or a short.
15738     if (Packed && NumPositiveBits <= CharWidth) {
15739       BestType = Context.UnsignedCharTy;
15740       BestPromotionType = Context.IntTy;
15741       BestWidth = CharWidth;
15742     } else if (Packed && NumPositiveBits <= ShortWidth) {
15743       BestType = Context.UnsignedShortTy;
15744       BestPromotionType = Context.IntTy;
15745       BestWidth = ShortWidth;
15746     } else if (NumPositiveBits <= IntWidth) {
15747       BestType = Context.UnsignedIntTy;
15748       BestWidth = IntWidth;
15749       BestPromotionType
15750         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15751                            ? Context.UnsignedIntTy : Context.IntTy;
15752     } else if (NumPositiveBits <=
15753                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15754       BestType = Context.UnsignedLongTy;
15755       BestPromotionType
15756         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15757                            ? Context.UnsignedLongTy : Context.LongTy;
15758     } else {
15759       BestWidth = Context.getTargetInfo().getLongLongWidth();
15760       assert(NumPositiveBits <= BestWidth &&
15761              "How could an initializer get larger than ULL?");
15762       BestType = Context.UnsignedLongLongTy;
15763       BestPromotionType
15764         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15765                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15766     }
15767   }
15768 
15769   // Loop over all of the enumerator constants, changing their types to match
15770   // the type of the enum if needed.
15771   for (auto *D : Elements) {
15772     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15773     if (!ECD) continue;  // Already issued a diagnostic.
15774 
15775     // Standard C says the enumerators have int type, but we allow, as an
15776     // extension, the enumerators to be larger than int size.  If each
15777     // enumerator value fits in an int, type it as an int, otherwise type it the
15778     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15779     // that X has type 'int', not 'unsigned'.
15780 
15781     // Determine whether the value fits into an int.
15782     llvm::APSInt InitVal = ECD->getInitVal();
15783 
15784     // If it fits into an integer type, force it.  Otherwise force it to match
15785     // the enum decl type.
15786     QualType NewTy;
15787     unsigned NewWidth;
15788     bool NewSign;
15789     if (!getLangOpts().CPlusPlus &&
15790         !Enum->isFixed() &&
15791         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15792       NewTy = Context.IntTy;
15793       NewWidth = IntWidth;
15794       NewSign = true;
15795     } else if (ECD->getType() == BestType) {
15796       // Already the right type!
15797       if (getLangOpts().CPlusPlus)
15798         // C++ [dcl.enum]p4: Following the closing brace of an
15799         // enum-specifier, each enumerator has the type of its
15800         // enumeration.
15801         ECD->setType(EnumType);
15802       continue;
15803     } else {
15804       NewTy = BestType;
15805       NewWidth = BestWidth;
15806       NewSign = BestType->isSignedIntegerOrEnumerationType();
15807     }
15808 
15809     // Adjust the APSInt value.
15810     InitVal = InitVal.extOrTrunc(NewWidth);
15811     InitVal.setIsSigned(NewSign);
15812     ECD->setInitVal(InitVal);
15813 
15814     // Adjust the Expr initializer and type.
15815     if (ECD->getInitExpr() &&
15816         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15817       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15818                                                 CK_IntegralCast,
15819                                                 ECD->getInitExpr(),
15820                                                 /*base paths*/ nullptr,
15821                                                 VK_RValue));
15822     if (getLangOpts().CPlusPlus)
15823       // C++ [dcl.enum]p4: Following the closing brace of an
15824       // enum-specifier, each enumerator has the type of its
15825       // enumeration.
15826       ECD->setType(EnumType);
15827     else
15828       ECD->setType(NewTy);
15829   }
15830 
15831   Enum->completeDefinition(BestType, BestPromotionType,
15832                            NumPositiveBits, NumNegativeBits);
15833 
15834   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15835 
15836   if (Enum->isClosedFlag()) {
15837     for (Decl *D : Elements) {
15838       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15839       if (!ECD) continue;  // Already issued a diagnostic.
15840 
15841       llvm::APSInt InitVal = ECD->getInitVal();
15842       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15843           !IsValueInFlagEnum(Enum, InitVal, true))
15844         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15845           << ECD << Enum;
15846     }
15847   }
15848 
15849   // Now that the enum type is defined, ensure it's not been underaligned.
15850   if (Enum->hasAttrs())
15851     CheckAlignasUnderalignment(Enum);
15852 }
15853 
15854 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15855                                   SourceLocation StartLoc,
15856                                   SourceLocation EndLoc) {
15857   StringLiteral *AsmString = cast<StringLiteral>(expr);
15858 
15859   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15860                                                    AsmString, StartLoc,
15861                                                    EndLoc);
15862   CurContext->addDecl(New);
15863   return New;
15864 }
15865 
15866 static void checkModuleImportContext(Sema &S, Module *M,
15867                                      SourceLocation ImportLoc, DeclContext *DC,
15868                                      bool FromInclude = false) {
15869   SourceLocation ExternCLoc;
15870 
15871   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15872     switch (LSD->getLanguage()) {
15873     case LinkageSpecDecl::lang_c:
15874       if (ExternCLoc.isInvalid())
15875         ExternCLoc = LSD->getLocStart();
15876       break;
15877     case LinkageSpecDecl::lang_cxx:
15878       break;
15879     }
15880     DC = LSD->getParent();
15881   }
15882 
15883   while (isa<LinkageSpecDecl>(DC))
15884     DC = DC->getParent();
15885 
15886   if (!isa<TranslationUnitDecl>(DC)) {
15887     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15888                           ? diag::ext_module_import_not_at_top_level_noop
15889                           : diag::err_module_import_not_at_top_level_fatal)
15890         << M->getFullModuleName() << DC;
15891     S.Diag(cast<Decl>(DC)->getLocStart(),
15892            diag::note_module_import_not_at_top_level) << DC;
15893   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15894     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15895       << M->getFullModuleName();
15896     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15897   }
15898 }
15899 
15900 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
15901                                            SourceLocation ModuleLoc,
15902                                            ModuleDeclKind MDK,
15903                                            ModuleIdPath Path) {
15904   // A module implementation unit requires that we are not compiling a module
15905   // of any kind. A module interface unit requires that we are not compiling a
15906   // module map.
15907   switch (getLangOpts().getCompilingModule()) {
15908   case LangOptions::CMK_None:
15909     // It's OK to compile a module interface as a normal translation unit.
15910     break;
15911 
15912   case LangOptions::CMK_ModuleInterface:
15913     if (MDK != ModuleDeclKind::Implementation)
15914       break;
15915 
15916     // We were asked to compile a module interface unit but this is a module
15917     // implementation unit. That indicates the 'export' is missing.
15918     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15919       << FixItHint::CreateInsertion(ModuleLoc, "export ");
15920     break;
15921 
15922   case LangOptions::CMK_ModuleMap:
15923     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
15924     return nullptr;
15925   }
15926 
15927   // FIXME: Create a ModuleDecl and return it.
15928 
15929   // FIXME: Most of this work should be done by the preprocessor rather than
15930   // here, in order to support macro import.
15931 
15932   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
15933   // modules, the dots here are just another character that can appear in a
15934   // module name.
15935   std::string ModuleName;
15936   for (auto &Piece : Path) {
15937     if (!ModuleName.empty())
15938       ModuleName += ".";
15939     ModuleName += Piece.first->getName();
15940   }
15941 
15942   // If a module name was explicitly specified on the command line, it must be
15943   // correct.
15944   if (!getLangOpts().CurrentModule.empty() &&
15945       getLangOpts().CurrentModule != ModuleName) {
15946     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15947         << SourceRange(Path.front().second, Path.back().second)
15948         << getLangOpts().CurrentModule;
15949     return nullptr;
15950   }
15951   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15952 
15953   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15954 
15955   switch (MDK) {
15956   case ModuleDeclKind::Module: {
15957     // FIXME: Check we're not in a submodule.
15958 
15959     // We can't have parsed or imported a definition of this module or parsed a
15960     // module map defining it already.
15961     if (auto *M = Map.findModule(ModuleName)) {
15962       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15963       if (M->DefinitionLoc.isValid())
15964         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15965       else if (const auto *FE = M->getASTFile())
15966         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15967             << FE->getName();
15968       return nullptr;
15969     }
15970 
15971     // Create a Module for the module that we're defining.
15972     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15973     assert(Mod && "module creation should not fail");
15974 
15975     // Enter the semantic scope of the module.
15976     ActOnModuleBegin(ModuleLoc, Mod);
15977     return nullptr;
15978   }
15979 
15980   case ModuleDeclKind::Partition:
15981     // FIXME: Check we are in a submodule of the named module.
15982     return nullptr;
15983 
15984   case ModuleDeclKind::Implementation:
15985     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15986         PP.getIdentifierInfo(ModuleName), Path[0].second);
15987 
15988     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15989     if (Import.isInvalid())
15990       return nullptr;
15991     return ConvertDeclToDeclGroup(Import.get());
15992   }
15993 
15994   llvm_unreachable("unexpected module decl kind");
15995 }
15996 
15997 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15998                                    SourceLocation ImportLoc,
15999                                    ModuleIdPath Path) {
16000   Module *Mod =
16001       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16002                                    /*IsIncludeDirective=*/false);
16003   if (!Mod)
16004     return true;
16005 
16006   VisibleModules.setVisible(Mod, ImportLoc);
16007 
16008   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16009 
16010   // FIXME: we should support importing a submodule within a different submodule
16011   // of the same top-level module. Until we do, make it an error rather than
16012   // silently ignoring the import.
16013   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16014   // warn on a redundant import of the current module?
16015   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16016       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16017     Diag(ImportLoc, getLangOpts().isCompilingModule()
16018                         ? diag::err_module_self_import
16019                         : diag::err_module_import_in_implementation)
16020         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16021 
16022   SmallVector<SourceLocation, 2> IdentifierLocs;
16023   Module *ModCheck = Mod;
16024   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16025     // If we've run out of module parents, just drop the remaining identifiers.
16026     // We need the length to be consistent.
16027     if (!ModCheck)
16028       break;
16029     ModCheck = ModCheck->Parent;
16030 
16031     IdentifierLocs.push_back(Path[I].second);
16032   }
16033 
16034   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16035   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16036                                           Mod, IdentifierLocs);
16037   if (!ModuleScopes.empty())
16038     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16039   TU->addDecl(Import);
16040   return Import;
16041 }
16042 
16043 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16044   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16045   BuildModuleInclude(DirectiveLoc, Mod);
16046 }
16047 
16048 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16049   // Determine whether we're in the #include buffer for a module. The #includes
16050   // in that buffer do not qualify as module imports; they're just an
16051   // implementation detail of us building the module.
16052   //
16053   // FIXME: Should we even get ActOnModuleInclude calls for those?
16054   bool IsInModuleIncludes =
16055       TUKind == TU_Module &&
16056       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16057 
16058   bool ShouldAddImport = !IsInModuleIncludes;
16059 
16060   // If this module import was due to an inclusion directive, create an
16061   // implicit import declaration to capture it in the AST.
16062   if (ShouldAddImport) {
16063     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16064     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16065                                                      DirectiveLoc, Mod,
16066                                                      DirectiveLoc);
16067     if (!ModuleScopes.empty())
16068       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16069     TU->addDecl(ImportD);
16070     Consumer.HandleImplicitImportDecl(ImportD);
16071   }
16072 
16073   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16074   VisibleModules.setVisible(Mod, DirectiveLoc);
16075 }
16076 
16077 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16078   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16079 
16080   ModuleScopes.push_back({});
16081   ModuleScopes.back().Module = Mod;
16082   if (getLangOpts().ModulesLocalVisibility)
16083     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16084 
16085   VisibleModules.setVisible(Mod, DirectiveLoc);
16086 
16087   // The enclosing context is now part of this module.
16088   // FIXME: Consider creating a child DeclContext to hold the entities
16089   // lexically within the module.
16090   if (getLangOpts().trackLocalOwningModule()) {
16091     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16092       cast<Decl>(DC)->setHidden(true);
16093       cast<Decl>(DC)->setLocalOwningModule(Mod);
16094     }
16095   }
16096 }
16097 
16098 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16099   if (getLangOpts().ModulesLocalVisibility) {
16100     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16101     // Leaving a module hides namespace names, so our visible namespace cache
16102     // is now out of date.
16103     VisibleNamespaceCache.clear();
16104   }
16105 
16106   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16107          "left the wrong module scope");
16108   ModuleScopes.pop_back();
16109 
16110   // We got to the end of processing a local module. Create an
16111   // ImportDecl as we would for an imported module.
16112   FileID File = getSourceManager().getFileID(EomLoc);
16113   SourceLocation DirectiveLoc;
16114   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16115     // We reached the end of a #included module header. Use the #include loc.
16116     assert(File != getSourceManager().getMainFileID() &&
16117            "end of submodule in main source file");
16118     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16119   } else {
16120     // We reached an EOM pragma. Use the pragma location.
16121     DirectiveLoc = EomLoc;
16122   }
16123   BuildModuleInclude(DirectiveLoc, Mod);
16124 
16125   // Any further declarations are in whatever module we returned to.
16126   if (getLangOpts().trackLocalOwningModule()) {
16127     // The parser guarantees that this is the same context that we entered
16128     // the module within.
16129     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16130       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16131       if (!getCurrentModule())
16132         cast<Decl>(DC)->setHidden(false);
16133     }
16134   }
16135 }
16136 
16137 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16138                                                       Module *Mod) {
16139   // Bail if we're not allowed to implicitly import a module here.
16140   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16141       VisibleModules.isVisible(Mod))
16142     return;
16143 
16144   // Create the implicit import declaration.
16145   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16146   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16147                                                    Loc, Mod, Loc);
16148   TU->addDecl(ImportD);
16149   Consumer.HandleImplicitImportDecl(ImportD);
16150 
16151   // Make the module visible.
16152   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16153   VisibleModules.setVisible(Mod, Loc);
16154 }
16155 
16156 /// We have parsed the start of an export declaration, including the '{'
16157 /// (if present).
16158 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16159                                  SourceLocation LBraceLoc) {
16160   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16161 
16162   // C++ Modules TS draft:
16163   //   An export-declaration shall appear in the purview of a module other than
16164   //   the global module.
16165   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16166       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16167     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16168 
16169   //   An export-declaration [...] shall not contain more than one
16170   //   export keyword.
16171   //
16172   // The intent here is that an export-declaration cannot appear within another
16173   // export-declaration.
16174   if (D->isExported())
16175     Diag(ExportLoc, diag::err_export_within_export);
16176 
16177   CurContext->addDecl(D);
16178   PushDeclContext(S, D);
16179   return D;
16180 }
16181 
16182 /// Complete the definition of an export declaration.
16183 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16184   auto *ED = cast<ExportDecl>(D);
16185   if (RBraceLoc.isValid())
16186     ED->setRBraceLoc(RBraceLoc);
16187 
16188   // FIXME: Diagnose export of internal-linkage declaration (including
16189   // anonymous namespace).
16190 
16191   PopDeclContext();
16192   return D;
16193 }
16194 
16195 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16196                                       IdentifierInfo* AliasName,
16197                                       SourceLocation PragmaLoc,
16198                                       SourceLocation NameLoc,
16199                                       SourceLocation AliasNameLoc) {
16200   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16201                                          LookupOrdinaryName);
16202   AsmLabelAttr *Attr =
16203       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16204 
16205   // If a declaration that:
16206   // 1) declares a function or a variable
16207   // 2) has external linkage
16208   // already exists, add a label attribute to it.
16209   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16210     if (isDeclExternC(PrevDecl))
16211       PrevDecl->addAttr(Attr);
16212     else
16213       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16214           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16215   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16216   } else
16217     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16218 }
16219 
16220 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16221                              SourceLocation PragmaLoc,
16222                              SourceLocation NameLoc) {
16223   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16224 
16225   if (PrevDecl) {
16226     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16227   } else {
16228     (void)WeakUndeclaredIdentifiers.insert(
16229       std::pair<IdentifierInfo*,WeakInfo>
16230         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16231   }
16232 }
16233 
16234 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16235                                 IdentifierInfo* AliasName,
16236                                 SourceLocation PragmaLoc,
16237                                 SourceLocation NameLoc,
16238                                 SourceLocation AliasNameLoc) {
16239   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16240                                     LookupOrdinaryName);
16241   WeakInfo W = WeakInfo(Name, NameLoc);
16242 
16243   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16244     if (!PrevDecl->hasAttr<AliasAttr>())
16245       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16246         DeclApplyPragmaWeak(TUScope, ND, W);
16247   } else {
16248     (void)WeakUndeclaredIdentifiers.insert(
16249       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16250   }
16251 }
16252 
16253 Decl *Sema::getObjCDeclContext() const {
16254   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16255 }
16256