1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 
50 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
67                         bool AllowTemplates = false,
68                         bool AllowNonTemplates = true)
69        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
71      WantExpressionKeywords = false;
72      WantCXXNamedCasts = false;
73      WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       if (!AllowInvalidDecl && ND->isInvalidDecl())
79         return false;
80 
81       if (getAsTypeTemplateDecl(ND))
82         return AllowTemplates;
83 
84       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85       if (!IsType)
86         return false;
87 
88       if (AllowNonTemplates)
89         return true;
90 
91       // An injected-class-name of a class template (specialization) is valid
92       // as a template or as a non-template.
93       if (AllowTemplates) {
94         auto *RD = dyn_cast<CXXRecordDecl>(ND);
95         if (!RD || !RD->isInjectedClassName())
96           return false;
97         RD = cast<CXXRecordDecl>(RD->getDeclContext());
98         return RD->getDescribedClassTemplate() ||
99                isa<ClassTemplateSpecializationDecl>(RD);
100       }
101 
102       return false;
103     }
104 
105     return !WantClassName && candidate.isKeyword();
106   }
107 
108  private:
109   bool AllowInvalidDecl;
110   bool WantClassName;
111   bool AllowTemplates;
112   bool AllowNonTemplates;
113 };
114 
115 } // end anonymous namespace
116 
117 /// Determine whether the token kind starts a simple-type-specifier.
118 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
119   switch (Kind) {
120   // FIXME: Take into account the current language when deciding whether a
121   // token kind is a valid type specifier
122   case tok::kw_short:
123   case tok::kw_long:
124   case tok::kw___int64:
125   case tok::kw___int128:
126   case tok::kw_signed:
127   case tok::kw_unsigned:
128   case tok::kw_void:
129   case tok::kw_char:
130   case tok::kw_int:
131   case tok::kw_half:
132   case tok::kw_float:
133   case tok::kw_double:
134   case tok::kw__Float16:
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   case tok::kw_char8_t:
151     return getLangOpts().Char8;
152 
153   default:
154     break;
155   }
156 
157   return false;
158 }
159 
160 namespace {
161 enum class UnqualifiedTypeNameLookupResult {
162   NotFound,
163   FoundNonType,
164   FoundType
165 };
166 } // end anonymous namespace
167 
168 /// Tries to perform unqualified lookup of the type decls in bases for
169 /// dependent class.
170 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
171 /// type decl, \a FoundType if only type decls are found.
172 static UnqualifiedTypeNameLookupResult
173 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
174                                 SourceLocation NameLoc,
175                                 const CXXRecordDecl *RD) {
176   if (!RD->hasDefinition())
177     return UnqualifiedTypeNameLookupResult::NotFound;
178   // Look for type decls in base classes.
179   UnqualifiedTypeNameLookupResult FoundTypeDecl =
180       UnqualifiedTypeNameLookupResult::NotFound;
181   for (const auto &Base : RD->bases()) {
182     const CXXRecordDecl *BaseRD = nullptr;
183     if (auto *BaseTT = Base.getType()->getAs<TagType>())
184       BaseRD = BaseTT->getAsCXXRecordDecl();
185     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
186       // Look for type decls in dependent base classes that have known primary
187       // templates.
188       if (!TST || !TST->isDependentType())
189         continue;
190       auto *TD = TST->getTemplateName().getAsTemplateDecl();
191       if (!TD)
192         continue;
193       if (auto *BasePrimaryTemplate =
194           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
195         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
196           BaseRD = BasePrimaryTemplate;
197         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
198           if (const ClassTemplatePartialSpecializationDecl *PS =
199                   CTD->findPartialSpecialization(Base.getType()))
200             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
201               BaseRD = PS;
202         }
203       }
204     }
205     if (BaseRD) {
206       for (NamedDecl *ND : BaseRD->lookup(&II)) {
207         if (!isa<TypeDecl>(ND))
208           return UnqualifiedTypeNameLookupResult::FoundNonType;
209         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
210       }
211       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
212         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
213         case UnqualifiedTypeNameLookupResult::FoundNonType:
214           return UnqualifiedTypeNameLookupResult::FoundNonType;
215         case UnqualifiedTypeNameLookupResult::FoundType:
216           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217           break;
218         case UnqualifiedTypeNameLookupResult::NotFound:
219           break;
220         }
221       }
222     }
223   }
224 
225   return FoundTypeDecl;
226 }
227 
228 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
229                                                       const IdentifierInfo &II,
230                                                       SourceLocation NameLoc) {
231   // Lookup in the parent class template context, if any.
232   const CXXRecordDecl *RD = nullptr;
233   UnqualifiedTypeNameLookupResult FoundTypeDecl =
234       UnqualifiedTypeNameLookupResult::NotFound;
235   for (DeclContext *DC = S.CurContext;
236        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
237        DC = DC->getParent()) {
238     // Look for type decls in dependent base classes that have known primary
239     // templates.
240     RD = dyn_cast<CXXRecordDecl>(DC);
241     if (RD && RD->getDescribedClassTemplate())
242       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
243   }
244   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
245     return nullptr;
246 
247   // We found some types in dependent base classes.  Recover as if the user
248   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
249   // lookup during template instantiation.
250   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
251 
252   ASTContext &Context = S.Context;
253   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
254                                           cast<Type>(Context.getRecordType(RD)));
255   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
256 
257   CXXScopeSpec SS;
258   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
259 
260   TypeLocBuilder Builder;
261   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
262   DepTL.setNameLoc(NameLoc);
263   DepTL.setElaboratedKeywordLoc(SourceLocation());
264   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
265   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
266 }
267 
268 /// If the identifier refers to a type name within this scope,
269 /// return the declaration of that type.
270 ///
271 /// This routine performs ordinary name lookup of the identifier II
272 /// within the given scope, with optional C++ scope specifier SS, to
273 /// determine whether the name refers to a type. If so, returns an
274 /// opaque pointer (actually a QualType) corresponding to that
275 /// type. Otherwise, returns NULL.
276 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277                              Scope *S, CXXScopeSpec *SS,
278                              bool isClassName, bool HasTrailingDot,
279                              ParsedType ObjectTypePtr,
280                              bool IsCtorOrDtorName,
281                              bool WantNontrivialTypeSourceInfo,
282                              bool IsClassTemplateDeductionContext,
283                              IdentifierInfo **CorrectedII) {
284   // FIXME: Consider allowing this outside C++1z mode as an extension.
285   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
287                               !isClassName && !HasTrailingDot;
288 
289   // Determine where we will perform name lookup.
290   DeclContext *LookupCtx = nullptr;
291   if (ObjectTypePtr) {
292     QualType ObjectType = ObjectTypePtr.get();
293     if (ObjectType->isRecordType())
294       LookupCtx = computeDeclContext(ObjectType);
295   } else if (SS && SS->isNotEmpty()) {
296     LookupCtx = computeDeclContext(*SS, false);
297 
298     if (!LookupCtx) {
299       if (isDependentScopeSpecifier(*SS)) {
300         // C++ [temp.res]p3:
301         //   A qualified-id that refers to a type and in which the
302         //   nested-name-specifier depends on a template-parameter (14.6.2)
303         //   shall be prefixed by the keyword typename to indicate that the
304         //   qualified-id denotes a type, forming an
305         //   elaborated-type-specifier (7.1.5.3).
306         //
307         // We therefore do not perform any name lookup if the result would
308         // refer to a member of an unknown specialization.
309         if (!isClassName && !IsCtorOrDtorName)
310           return nullptr;
311 
312         // We know from the grammar that this name refers to a type,
313         // so build a dependent node to describe the type.
314         if (WantNontrivialTypeSourceInfo)
315           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
316 
317         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
318         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
319                                        II, NameLoc);
320         return ParsedType::make(T);
321       }
322 
323       return nullptr;
324     }
325 
326     if (!LookupCtx->isDependentContext() &&
327         RequireCompleteDeclContext(*SS, LookupCtx))
328       return nullptr;
329   }
330 
331   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
332   // lookup for class-names.
333   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
334                                       LookupOrdinaryName;
335   LookupResult Result(*this, &II, NameLoc, Kind);
336   if (LookupCtx) {
337     // Perform "qualified" name lookup into the declaration context we
338     // computed, which is either the type of the base of a member access
339     // expression or the declaration context associated with a prior
340     // nested-name-specifier.
341     LookupQualifiedName(Result, LookupCtx);
342 
343     if (ObjectTypePtr && Result.empty()) {
344       // C++ [basic.lookup.classref]p3:
345       //   If the unqualified-id is ~type-name, the type-name is looked up
346       //   in the context of the entire postfix-expression. If the type T of
347       //   the object expression is of a class type C, the type-name is also
348       //   looked up in the scope of class C. At least one of the lookups shall
349       //   find a name that refers to (possibly cv-qualified) T.
350       LookupName(Result, S);
351     }
352   } else {
353     // Perform unqualified name lookup.
354     LookupName(Result, S);
355 
356     // For unqualified lookup in a class template in MSVC mode, look into
357     // dependent base classes where the primary class template is known.
358     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
359       if (ParsedType TypeInBase =
360               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
361         return TypeInBase;
362     }
363   }
364 
365   NamedDecl *IIDecl = nullptr;
366   switch (Result.getResultKind()) {
367   case LookupResult::NotFound:
368   case LookupResult::NotFoundInCurrentInstantiation:
369     if (CorrectedII) {
370       TypoCorrection Correction =
371           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
372                       llvm::make_unique<TypeNameValidatorCCC>(
373                           true, isClassName, AllowDeducedTemplate),
374                       CTK_ErrorRecovery);
375       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
376       TemplateTy Template;
377       bool MemberOfUnknownSpecialization;
378       UnqualifiedId TemplateName;
379       TemplateName.setIdentifier(NewII, NameLoc);
380       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
381       CXXScopeSpec NewSS, *NewSSPtr = SS;
382       if (SS && NNS) {
383         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
384         NewSSPtr = &NewSS;
385       }
386       if (Correction && (NNS || NewII != &II) &&
387           // Ignore a correction to a template type as the to-be-corrected
388           // identifier is not a template (typo correction for template names
389           // is handled elsewhere).
390           !(getLangOpts().CPlusPlus && NewSSPtr &&
391             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
392                            Template, MemberOfUnknownSpecialization))) {
393         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
394                                     isClassName, HasTrailingDot, ObjectTypePtr,
395                                     IsCtorOrDtorName,
396                                     WantNontrivialTypeSourceInfo,
397                                     IsClassTemplateDeductionContext);
398         if (Ty) {
399           diagnoseTypo(Correction,
400                        PDiag(diag::err_unknown_type_or_class_name_suggest)
401                          << Result.getLookupName() << isClassName);
402           if (SS && NNS)
403             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
404           *CorrectedII = NewII;
405           return Ty;
406         }
407       }
408     }
409     // If typo correction failed or was not performed, fall through
410     LLVM_FALLTHROUGH;
411   case LookupResult::FoundOverloaded:
412   case LookupResult::FoundUnresolvedValue:
413     Result.suppressDiagnostics();
414     return nullptr;
415 
416   case LookupResult::Ambiguous:
417     // Recover from type-hiding ambiguities by hiding the type.  We'll
418     // do the lookup again when looking for an object, and we can
419     // diagnose the error then.  If we don't do this, then the error
420     // about hiding the type will be immediately followed by an error
421     // that only makes sense if the identifier was treated like a type.
422     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
423       Result.suppressDiagnostics();
424       return nullptr;
425     }
426 
427     // Look to see if we have a type anywhere in the list of results.
428     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
429          Res != ResEnd; ++Res) {
430       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
431           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
432         if (!IIDecl ||
433             (*Res)->getLocation().getRawEncoding() <
434               IIDecl->getLocation().getRawEncoding())
435           IIDecl = *Res;
436       }
437     }
438 
439     if (!IIDecl) {
440       // None of the entities we found is a type, so there is no way
441       // to even assume that the result is a type. In this case, don't
442       // complain about the ambiguity. The parser will either try to
443       // perform this lookup again (e.g., as an object name), which
444       // will produce the ambiguity, or will complain that it expected
445       // a type name.
446       Result.suppressDiagnostics();
447       return nullptr;
448     }
449 
450     // We found a type within the ambiguous lookup; diagnose the
451     // ambiguity and then return that type. This might be the right
452     // answer, or it might not be, but it suppresses any attempt to
453     // perform the name lookup again.
454     break;
455 
456   case LookupResult::Found:
457     IIDecl = Result.getFoundDecl();
458     break;
459   }
460 
461   assert(IIDecl && "Didn't find decl");
462 
463   QualType T;
464   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
465     // C++ [class.qual]p2: A lookup that would find the injected-class-name
466     // instead names the constructors of the class, except when naming a class.
467     // This is ill-formed when we're not actually forming a ctor or dtor name.
468     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
469     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
470     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
471         FoundRD->isInjectedClassName() &&
472         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
473       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
474           << &II << /*Type*/1;
475 
476     DiagnoseUseOfDecl(IIDecl, NameLoc);
477 
478     T = Context.getTypeDeclType(TD);
479     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
480   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
481     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
482     if (!HasTrailingDot)
483       T = Context.getObjCInterfaceType(IDecl);
484   } else if (AllowDeducedTemplate) {
485     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
486       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
487                                                        QualType(), false);
488   }
489 
490   if (T.isNull()) {
491     // If it's not plausibly a type, suppress diagnostics.
492     Result.suppressDiagnostics();
493     return nullptr;
494   }
495 
496   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
497   // constructor or destructor name (in such a case, the scope specifier
498   // will be attached to the enclosing Expr or Decl node).
499   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
500       !isa<ObjCInterfaceDecl>(IIDecl)) {
501     if (WantNontrivialTypeSourceInfo) {
502       // Construct a type with type-source information.
503       TypeLocBuilder Builder;
504       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
505 
506       T = getElaboratedType(ETK_None, *SS, T);
507       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
508       ElabTL.setElaboratedKeywordLoc(SourceLocation());
509       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
510       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
511     } else {
512       T = getElaboratedType(ETK_None, *SS, T);
513     }
514   }
515 
516   return ParsedType::make(T);
517 }
518 
519 // Builds a fake NNS for the given decl context.
520 static NestedNameSpecifier *
521 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
522   for (;; DC = DC->getLookupParent()) {
523     DC = DC->getPrimaryContext();
524     auto *ND = dyn_cast<NamespaceDecl>(DC);
525     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
526       return NestedNameSpecifier::Create(Context, nullptr, ND);
527     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
528       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
529                                          RD->getTypeForDecl());
530     else if (isa<TranslationUnitDecl>(DC))
531       return NestedNameSpecifier::GlobalSpecifier(Context);
532   }
533   llvm_unreachable("something isn't in TU scope?");
534 }
535 
536 /// Find the parent class with dependent bases of the innermost enclosing method
537 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
538 /// up allowing unqualified dependent type names at class-level, which MSVC
539 /// correctly rejects.
540 static const CXXRecordDecl *
541 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
542   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
543     DC = DC->getPrimaryContext();
544     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
545       if (MD->getParent()->hasAnyDependentBases())
546         return MD->getParent();
547   }
548   return nullptr;
549 }
550 
551 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
552                                           SourceLocation NameLoc,
553                                           bool IsTemplateTypeArg) {
554   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
555 
556   NestedNameSpecifier *NNS = nullptr;
557   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
558     // If we weren't able to parse a default template argument, delay lookup
559     // until instantiation time by making a non-dependent DependentTypeName. We
560     // pretend we saw a NestedNameSpecifier referring to the current scope, and
561     // lookup is retried.
562     // FIXME: This hurts our diagnostic quality, since we get errors like "no
563     // type named 'Foo' in 'current_namespace'" when the user didn't write any
564     // name specifiers.
565     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
566     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
567   } else if (const CXXRecordDecl *RD =
568                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
569     // Build a DependentNameType that will perform lookup into RD at
570     // instantiation time.
571     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572                                       RD->getTypeForDecl());
573 
574     // Diagnose that this identifier was undeclared, and retry the lookup during
575     // template instantiation.
576     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
577                                                                       << RD;
578   } else {
579     // This is not a situation that we should recover from.
580     return ParsedType();
581   }
582 
583   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
584 
585   // Build type location information.  We synthesized the qualifier, so we have
586   // to build a fake NestedNameSpecifierLoc.
587   NestedNameSpecifierLocBuilder NNSLocBuilder;
588   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
589   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
590 
591   TypeLocBuilder Builder;
592   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
593   DepTL.setNameLoc(NameLoc);
594   DepTL.setElaboratedKeywordLoc(SourceLocation());
595   DepTL.setQualifierLoc(QualifierLoc);
596   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
597 }
598 
599 /// isTagName() - This method is called *for error recovery purposes only*
600 /// to determine if the specified name is a valid tag name ("struct foo").  If
601 /// so, this returns the TST for the tag corresponding to it (TST_enum,
602 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
603 /// cases in C where the user forgot to specify the tag.
604 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
605   // Do a tag name lookup in this scope.
606   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
607   LookupName(R, S, false);
608   R.suppressDiagnostics();
609   if (R.getResultKind() == LookupResult::Found)
610     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
611       switch (TD->getTagKind()) {
612       case TTK_Struct: return DeclSpec::TST_struct;
613       case TTK_Interface: return DeclSpec::TST_interface;
614       case TTK_Union:  return DeclSpec::TST_union;
615       case TTK_Class:  return DeclSpec::TST_class;
616       case TTK_Enum:   return DeclSpec::TST_enum;
617       }
618     }
619 
620   return DeclSpec::TST_unspecified;
621 }
622 
623 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
624 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
625 /// then downgrade the missing typename error to a warning.
626 /// This is needed for MSVC compatibility; Example:
627 /// @code
628 /// template<class T> class A {
629 /// public:
630 ///   typedef int TYPE;
631 /// };
632 /// template<class T> class B : public A<T> {
633 /// public:
634 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
635 /// };
636 /// @endcode
637 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
638   if (CurContext->isRecord()) {
639     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
640       return true;
641 
642     const Type *Ty = SS->getScopeRep()->getAsType();
643 
644     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
645     for (const auto &Base : RD->bases())
646       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
647         return true;
648     return S->isFunctionPrototypeScope();
649   }
650   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
651 }
652 
653 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
654                                    SourceLocation IILoc,
655                                    Scope *S,
656                                    CXXScopeSpec *SS,
657                                    ParsedType &SuggestedType,
658                                    bool IsTemplateName) {
659   // Don't report typename errors for editor placeholders.
660   if (II->isEditorPlaceholder())
661     return;
662   // We don't have anything to suggest (yet).
663   SuggestedType = nullptr;
664 
665   // There may have been a typo in the name of the type. Look up typo
666   // results, in case we have something that we can suggest.
667   if (TypoCorrection Corrected =
668           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
669                       llvm::make_unique<TypeNameValidatorCCC>(
670                           false, false, IsTemplateName, !IsTemplateName),
671                       CTK_ErrorRecovery)) {
672     // FIXME: Support error recovery for the template-name case.
673     bool CanRecover = !IsTemplateName;
674     if (Corrected.isKeyword()) {
675       // We corrected to a keyword.
676       diagnoseTypo(Corrected,
677                    PDiag(IsTemplateName ? diag::err_no_template_suggest
678                                         : diag::err_unknown_typename_suggest)
679                        << II);
680       II = Corrected.getCorrectionAsIdentifierInfo();
681     } else {
682       // We found a similarly-named type or interface; suggest that.
683       if (!SS || !SS->isSet()) {
684         diagnoseTypo(Corrected,
685                      PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                           : diag::err_unknown_typename_suggest)
687                          << II, CanRecover);
688       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
689         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
690         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
691                                 II->getName().equals(CorrectedStr);
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName
694                                ? diag::err_no_member_template_suggest
695                                : diag::err_unknown_nested_typename_suggest)
696                          << II << DC << DroppedSpecifier << SS->getRange(),
697                      CanRecover);
698       } else {
699         llvm_unreachable("could not have corrected a typo here");
700       }
701 
702       if (!CanRecover)
703         return;
704 
705       CXXScopeSpec tmpSS;
706       if (Corrected.getCorrectionSpecifier())
707         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
708                           SourceRange(IILoc));
709       // FIXME: Support class template argument deduction here.
710       SuggestedType =
711           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
712                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
713                       /*IsCtorOrDtorName=*/false,
714                       /*NonTrivialTypeSourceInfo=*/true);
715     }
716     return;
717   }
718 
719   if (getLangOpts().CPlusPlus && !IsTemplateName) {
720     // See if II is a class template that the user forgot to pass arguments to.
721     UnqualifiedId Name;
722     Name.setIdentifier(II, IILoc);
723     CXXScopeSpec EmptySS;
724     TemplateTy TemplateResult;
725     bool MemberOfUnknownSpecialization;
726     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
727                        Name, nullptr, true, TemplateResult,
728                        MemberOfUnknownSpecialization) == TNK_Type_template) {
729       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
730       return;
731     }
732   }
733 
734   // FIXME: Should we move the logic that tries to recover from a missing tag
735   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
736 
737   if (!SS || (!SS->isSet() && !SS->isInvalid()))
738     Diag(IILoc, IsTemplateName ? diag::err_no_template
739                                : diag::err_unknown_typename)
740         << II;
741   else if (DeclContext *DC = computeDeclContext(*SS, false))
742     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
743                                : diag::err_typename_nested_not_found)
744         << II << DC << SS->getRange();
745   else if (isDependentScopeSpecifier(*SS)) {
746     unsigned DiagID = diag::err_typename_missing;
747     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
748       DiagID = diag::ext_typename_missing;
749 
750     Diag(SS->getRange().getBegin(), DiagID)
751       << SS->getScopeRep() << II->getName()
752       << SourceRange(SS->getRange().getBegin(), IILoc)
753       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
754     SuggestedType = ActOnTypenameType(S, SourceLocation(),
755                                       *SS, *II, IILoc).get();
756   } else {
757     assert(SS && SS->isInvalid() &&
758            "Invalid scope specifier has already been diagnosed");
759   }
760 }
761 
762 /// Determine whether the given result set contains either a type name
763 /// or
764 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
765   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
766                        NextToken.is(tok::less);
767 
768   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
769     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
770       return true;
771 
772     if (CheckTemplate && isa<TemplateDecl>(*I))
773       return true;
774   }
775 
776   return false;
777 }
778 
779 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
780                                     Scope *S, CXXScopeSpec &SS,
781                                     IdentifierInfo *&Name,
782                                     SourceLocation NameLoc) {
783   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
784   SemaRef.LookupParsedName(R, S, &SS);
785   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
786     StringRef FixItTagName;
787     switch (Tag->getTagKind()) {
788       case TTK_Class:
789         FixItTagName = "class ";
790         break;
791 
792       case TTK_Enum:
793         FixItTagName = "enum ";
794         break;
795 
796       case TTK_Struct:
797         FixItTagName = "struct ";
798         break;
799 
800       case TTK_Interface:
801         FixItTagName = "__interface ";
802         break;
803 
804       case TTK_Union:
805         FixItTagName = "union ";
806         break;
807     }
808 
809     StringRef TagName = FixItTagName.drop_back();
810     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
811       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
812       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
813 
814     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
815          I != IEnd; ++I)
816       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
817         << Name << TagName;
818 
819     // Replace lookup results with just the tag decl.
820     Result.clear(Sema::LookupTagName);
821     SemaRef.LookupParsedName(Result, S, &SS);
822     return true;
823   }
824 
825   return false;
826 }
827 
828 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
829 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
830                                   QualType T, SourceLocation NameLoc) {
831   ASTContext &Context = S.Context;
832 
833   TypeLocBuilder Builder;
834   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
835 
836   T = S.getElaboratedType(ETK_None, SS, T);
837   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
838   ElabTL.setElaboratedKeywordLoc(SourceLocation());
839   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
840   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
841 }
842 
843 Sema::NameClassification
844 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
845                    SourceLocation NameLoc, const Token &NextToken,
846                    bool IsAddressOfOperand,
847                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
848   DeclarationNameInfo NameInfo(Name, NameLoc);
849   ObjCMethodDecl *CurMethod = getCurMethodDecl();
850 
851   if (NextToken.is(tok::coloncolon)) {
852     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
853     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
854   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
855              isCurrentClassName(*Name, S, &SS)) {
856     // Per [class.qual]p2, this names the constructors of SS, not the
857     // injected-class-name. We don't have a classification for that.
858     // There's not much point caching this result, since the parser
859     // will reject it later.
860     return NameClassification::Unknown();
861   }
862 
863   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
864   LookupParsedName(Result, S, &SS, !CurMethod);
865 
866   // For unqualified lookup in a class template in MSVC mode, look into
867   // dependent base classes where the primary class template is known.
868   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
869     if (ParsedType TypeInBase =
870             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
871       return TypeInBase;
872   }
873 
874   // Perform lookup for Objective-C instance variables (including automatically
875   // synthesized instance variables), if we're in an Objective-C method.
876   // FIXME: This lookup really, really needs to be folded in to the normal
877   // unqualified lookup mechanism.
878   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
879     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
880     if (E.get() || E.isInvalid())
881       return E;
882   }
883 
884   bool SecondTry = false;
885   bool IsFilteredTemplateName = false;
886 
887 Corrected:
888   switch (Result.getResultKind()) {
889   case LookupResult::NotFound:
890     // If an unqualified-id is followed by a '(', then we have a function
891     // call.
892     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
893       // In C++, this is an ADL-only call.
894       // FIXME: Reference?
895       if (getLangOpts().CPlusPlus)
896         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
897 
898       // C90 6.3.2.2:
899       //   If the expression that precedes the parenthesized argument list in a
900       //   function call consists solely of an identifier, and if no
901       //   declaration is visible for this identifier, the identifier is
902       //   implicitly declared exactly as if, in the innermost block containing
903       //   the function call, the declaration
904       //
905       //     extern int identifier ();
906       //
907       //   appeared.
908       //
909       // We also allow this in C99 as an extension.
910       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
911         Result.addDecl(D);
912         Result.resolveKind();
913         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
914       }
915     }
916 
917     // In C, we first see whether there is a tag type by the same name, in
918     // which case it's likely that the user just forgot to write "enum",
919     // "struct", or "union".
920     if (!getLangOpts().CPlusPlus && !SecondTry &&
921         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
922       break;
923     }
924 
925     // Perform typo correction to determine if there is another name that is
926     // close to this name.
927     if (!SecondTry && CCC) {
928       SecondTry = true;
929       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
930                                                  Result.getLookupKind(), S,
931                                                  &SS, std::move(CCC),
932                                                  CTK_ErrorRecovery)) {
933         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
934         unsigned QualifiedDiag = diag::err_no_member_suggest;
935 
936         NamedDecl *FirstDecl = Corrected.getFoundDecl();
937         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
938         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
939             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
940           UnqualifiedDiag = diag::err_no_template_suggest;
941           QualifiedDiag = diag::err_no_member_template_suggest;
942         } else if (UnderlyingFirstDecl &&
943                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
944                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
946           UnqualifiedDiag = diag::err_unknown_typename_suggest;
947           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
948         }
949 
950         if (SS.isEmpty()) {
951           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
952         } else {// FIXME: is this even reachable? Test it.
953           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
954           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
955                                   Name->getName().equals(CorrectedStr);
956           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
957                                     << Name << computeDeclContext(SS, false)
958                                     << DroppedSpecifier << SS.getRange());
959         }
960 
961         // Update the name, so that the caller has the new name.
962         Name = Corrected.getCorrectionAsIdentifierInfo();
963 
964         // Typo correction corrected to a keyword.
965         if (Corrected.isKeyword())
966           return Name;
967 
968         // Also update the LookupResult...
969         // FIXME: This should probably go away at some point
970         Result.clear();
971         Result.setLookupName(Corrected.getCorrection());
972         if (FirstDecl)
973           Result.addDecl(FirstDecl);
974 
975         // If we found an Objective-C instance variable, let
976         // LookupInObjCMethod build the appropriate expression to
977         // reference the ivar.
978         // FIXME: This is a gross hack.
979         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
980           Result.clear();
981           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
982           return E;
983         }
984 
985         goto Corrected;
986       }
987     }
988 
989     // We failed to correct; just fall through and let the parser deal with it.
990     Result.suppressDiagnostics();
991     return NameClassification::Unknown();
992 
993   case LookupResult::NotFoundInCurrentInstantiation: {
994     // We performed name lookup into the current instantiation, and there were
995     // dependent bases, so we treat this result the same way as any other
996     // dependent nested-name-specifier.
997 
998     // C++ [temp.res]p2:
999     //   A name used in a template declaration or definition and that is
1000     //   dependent on a template-parameter is assumed not to name a type
1001     //   unless the applicable name lookup finds a type name or the name is
1002     //   qualified by the keyword typename.
1003     //
1004     // FIXME: If the next token is '<', we might want to ask the parser to
1005     // perform some heroics to see if we actually have a
1006     // template-argument-list, which would indicate a missing 'template'
1007     // keyword here.
1008     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1009                                       NameInfo, IsAddressOfOperand,
1010                                       /*TemplateArgs=*/nullptr);
1011   }
1012 
1013   case LookupResult::Found:
1014   case LookupResult::FoundOverloaded:
1015   case LookupResult::FoundUnresolvedValue:
1016     break;
1017 
1018   case LookupResult::Ambiguous:
1019     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1020         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1021                                       /*AllowDependent=*/false)) {
1022       // C++ [temp.local]p3:
1023       //   A lookup that finds an injected-class-name (10.2) can result in an
1024       //   ambiguity in certain cases (for example, if it is found in more than
1025       //   one base class). If all of the injected-class-names that are found
1026       //   refer to specializations of the same class template, and if the name
1027       //   is followed by a template-argument-list, the reference refers to the
1028       //   class template itself and not a specialization thereof, and is not
1029       //   ambiguous.
1030       //
1031       // This filtering can make an ambiguous result into an unambiguous one,
1032       // so try again after filtering out template names.
1033       FilterAcceptableTemplateNames(Result);
1034       if (!Result.isAmbiguous()) {
1035         IsFilteredTemplateName = true;
1036         break;
1037       }
1038     }
1039 
1040     // Diagnose the ambiguity and return an error.
1041     return NameClassification::Error();
1042   }
1043 
1044   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045       (IsFilteredTemplateName ||
1046        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                      /*AllowDependent=*/false))) {
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         auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1067             *Result.begin(), /*AllowFunctionTemplates=*/true,
1068             /*AllowDependent=*/false));
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template =
1074               Context.getQualifiedTemplateName(SS.getScopeRep(),
1075                                                /*TemplateKeyword=*/false, TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454   // FIXME: The Modules TS is not clear about how friend declarations are
1455   // to be treated. It's not meaningful to have different owning modules for
1456   // linkage in redeclarations of the same entity, so for now allow the
1457   // redeclaration and change the owning modules to match.
1458   if (New->getFriendObjectKind() &&
1459       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460     New->setLocalOwningModule(Old->getOwningModule());
1461     makeMergedDefinitionVisible(New);
1462     return false;
1463   }
1464 
1465   Module *NewM = New->getOwningModule();
1466   Module *OldM = Old->getOwningModule();
1467   if (NewM == OldM)
1468     return false;
1469 
1470   // FIXME: Check proclaimed-ownership-declarations here too.
1471   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473   if (NewIsModuleInterface || OldIsModuleInterface) {
1474     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475     //   if a declaration of D [...] appears in the purview of a module, all
1476     //   other such declarations shall appear in the purview of the same module
1477     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478       << New
1479       << NewIsModuleInterface
1480       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481       << OldIsModuleInterface
1482       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483     Diag(Old->getLocation(), diag::note_previous_declaration);
1484     New->setInvalidDecl();
1485     return true;
1486   }
1487 
1488   return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492   return isa<UsingShadowDecl>(D) ||
1493          isa<UnresolvedUsingTypenameDecl>(D) ||
1494          isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1498 static void RemoveUsingDecls(LookupResult &R) {
1499   LookupResult::Filter F = R.makeFilter();
1500   while (F.hasNext())
1501     if (isUsingDecl(F.next()))
1502       F.erase();
1503 
1504   F.done();
1505 }
1506 
1507 /// Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 ///   S(const S&); // DO NOT IMPLEMENT
1511 ///   void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515   // FIXME: Should check for private access too but access is set after we get
1516   // the decl here.
1517   if (D->doesThisDeclarationHaveABody())
1518     return false;
1519 
1520   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521     return CD->isCopyConstructor();
1522   return D->isCopyAssignmentOperator();
1523 }
1524 
1525 // We need this to handle
1526 //
1527 // typedef struct {
1528 //   void *foo() { return 0; }
1529 // } A;
1530 //
1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532 // for example. If 'A', foo will have external linkage. If we have '*A',
1533 // foo will have no linkage. Since we can't know until we get to the end
1534 // of the typedef, this function finds out if D might have non-external linkage.
1535 // Callers should verify at the end of the TU if it D has external linkage or
1536 // not.
1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538   const DeclContext *DC = D->getDeclContext();
1539   while (!DC->isTranslationUnit()) {
1540     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541       if (!RD->hasNameForLinkage())
1542         return true;
1543     }
1544     DC = DC->getParent();
1545   }
1546 
1547   return !D->isExternallyVisible();
1548 }
1549 
1550 // FIXME: This needs to be refactored; some other isInMainFile users want
1551 // these semantics.
1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553   if (S.TUKind != TU_Complete)
1554     return false;
1555   return S.SourceMgr.isInMainFile(Loc);
1556 }
1557 
1558 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1559   assert(D);
1560 
1561   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562     return false;
1563 
1564   // Ignore all entities declared within templates, and out-of-line definitions
1565   // of members of class templates.
1566   if (D->getDeclContext()->isDependentContext() ||
1567       D->getLexicalDeclContext()->isDependentContext())
1568     return false;
1569 
1570   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572       return false;
1573     // A non-out-of-line declaration of a member specialization was implicitly
1574     // instantiated; it's the out-of-line declaration that we're interested in.
1575     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577       return false;
1578 
1579     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581         return false;
1582     } else {
1583       // 'static inline' functions are defined in headers; don't warn.
1584       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585         return false;
1586     }
1587 
1588     if (FD->doesThisDeclarationHaveABody() &&
1589         Context.DeclMustBeEmitted(FD))
1590       return false;
1591   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592     // Constants and utility variables are defined in headers with internal
1593     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1594     // like "inline".)
1595     if (!isMainFileLoc(*this, VD->getLocation()))
1596       return false;
1597 
1598     if (Context.DeclMustBeEmitted(VD))
1599       return false;
1600 
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603       return false;
1604     if (VD->isStaticDataMember() &&
1605         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607       return false;
1608 
1609     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610       return false;
1611   } else {
1612     return false;
1613   }
1614 
1615   // Only warn for unused decls internal to the translation unit.
1616   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617   // for inline functions defined in the main source file, for instance.
1618   return mightHaveNonExternalLinkage(D);
1619 }
1620 
1621 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622   if (!D)
1623     return;
1624 
1625   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626     const FunctionDecl *First = FD->getFirstDecl();
1627     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628       return; // First should already be in the vector.
1629   }
1630 
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632     const VarDecl *First = VD->getFirstDecl();
1633     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634       return; // First should already be in the vector.
1635   }
1636 
1637   if (ShouldWarnIfUnusedFileScopedDecl(D))
1638     UnusedFileScopedDecls.push_back(D);
1639 }
1640 
1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642   if (D->isInvalidDecl())
1643     return false;
1644 
1645   bool Referenced = false;
1646   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647     // For a decomposition declaration, warn if none of the bindings are
1648     // referenced, instead of if the variable itself is referenced (which
1649     // it is, by the bindings' expressions).
1650     for (auto *BD : DD->bindings()) {
1651       if (BD->isReferenced()) {
1652         Referenced = true;
1653         break;
1654       }
1655     }
1656   } else if (!D->getDeclName()) {
1657     return false;
1658   } else if (D->isReferenced() || D->isUsed()) {
1659     Referenced = true;
1660   }
1661 
1662   if (Referenced || D->hasAttr<UnusedAttr>() ||
1663       D->hasAttr<ObjCPreciseLifetimeAttr>())
1664     return false;
1665 
1666   if (isa<LabelDecl>(D))
1667     return true;
1668 
1669   // Except for labels, we only care about unused decls that are local to
1670   // functions.
1671   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673     // For dependent types, the diagnostic is deferred.
1674     WithinFunction =
1675         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676   if (!WithinFunction)
1677     return false;
1678 
1679   if (isa<TypedefNameDecl>(D))
1680     return true;
1681 
1682   // White-list anything that isn't a local variable.
1683   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684     return false;
1685 
1686   // Types of valid local variables should be complete, so this should succeed.
1687   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688 
1689     // White-list anything with an __attribute__((unused)) type.
1690     const auto *Ty = VD->getType().getTypePtr();
1691 
1692     // Only look at the outermost level of typedef.
1693     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694       if (TT->getDecl()->hasAttr<UnusedAttr>())
1695         return false;
1696     }
1697 
1698     // If we failed to complete the type for some reason, or if the type is
1699     // dependent, don't diagnose the variable.
1700     if (Ty->isIncompleteType() || Ty->isDependentType())
1701       return false;
1702 
1703     // Look at the element type to ensure that the warning behaviour is
1704     // consistent for both scalars and arrays.
1705     Ty = Ty->getBaseElementTypeUnsafe();
1706 
1707     if (const TagType *TT = Ty->getAs<TagType>()) {
1708       const TagDecl *Tag = TT->getDecl();
1709       if (Tag->hasAttr<UnusedAttr>())
1710         return false;
1711 
1712       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714           return false;
1715 
1716         if (const Expr *Init = VD->getInit()) {
1717           if (const ExprWithCleanups *Cleanups =
1718                   dyn_cast<ExprWithCleanups>(Init))
1719             Init = Cleanups->getSubExpr();
1720           const CXXConstructExpr *Construct =
1721             dyn_cast<CXXConstructExpr>(Init);
1722           if (Construct && !Construct->isElidable()) {
1723             CXXConstructorDecl *CD = Construct->getConstructor();
1724             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726               return false;
1727           }
1728         }
1729       }
1730     }
1731 
1732     // TODO: __attribute__((unused)) templates?
1733   }
1734 
1735   return true;
1736 }
1737 
1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739                                      FixItHint &Hint) {
1740   if (isa<LabelDecl>(D)) {
1741     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1742         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1743         true);
1744     if (AfterColon.isInvalid())
1745       return;
1746     Hint = FixItHint::CreateRemoval(
1747         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1748   }
1749 }
1750 
1751 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1752   if (D->getTypeForDecl()->isDependentType())
1753     return;
1754 
1755   for (auto *TmpD : D->decls()) {
1756     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1757       DiagnoseUnusedDecl(T);
1758     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1759       DiagnoseUnusedNestedTypedefs(R);
1760   }
1761 }
1762 
1763 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1764 /// unless they are marked attr(unused).
1765 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1766   if (!ShouldDiagnoseUnusedDecl(D))
1767     return;
1768 
1769   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1770     // typedefs can be referenced later on, so the diagnostics are emitted
1771     // at end-of-translation-unit.
1772     UnusedLocalTypedefNameCandidates.insert(TD);
1773     return;
1774   }
1775 
1776   FixItHint Hint;
1777   GenerateFixForUnusedDecl(D, Context, Hint);
1778 
1779   unsigned DiagID;
1780   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1781     DiagID = diag::warn_unused_exception_param;
1782   else if (isa<LabelDecl>(D))
1783     DiagID = diag::warn_unused_label;
1784   else
1785     DiagID = diag::warn_unused_variable;
1786 
1787   Diag(D->getLocation(), DiagID) << D << Hint;
1788 }
1789 
1790 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1791   // Verify that we have no forward references left.  If so, there was a goto
1792   // or address of a label taken, but no definition of it.  Label fwd
1793   // definitions are indicated with a null substmt which is also not a resolved
1794   // MS inline assembly label name.
1795   bool Diagnose = false;
1796   if (L->isMSAsmLabel())
1797     Diagnose = !L->isResolvedMSAsmLabel();
1798   else
1799     Diagnose = L->getStmt() == nullptr;
1800   if (Diagnose)
1801     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1802 }
1803 
1804 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1805   S->mergeNRVOIntoParent();
1806 
1807   if (S->decl_empty()) return;
1808   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1809          "Scope shouldn't contain decls!");
1810 
1811   for (auto *TmpD : S->decls()) {
1812     assert(TmpD && "This decl didn't get pushed??");
1813 
1814     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1815     NamedDecl *D = cast<NamedDecl>(TmpD);
1816 
1817     // Diagnose unused variables in this scope.
1818     if (!S->hasUnrecoverableErrorOccurred()) {
1819       DiagnoseUnusedDecl(D);
1820       if (const auto *RD = dyn_cast<RecordDecl>(D))
1821         DiagnoseUnusedNestedTypedefs(RD);
1822     }
1823 
1824     if (!D->getDeclName()) continue;
1825 
1826     // If this was a forward reference to a label, verify it was defined.
1827     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1828       CheckPoppedLabel(LD, *this);
1829 
1830     // Remove this name from our lexical scope, and warn on it if we haven't
1831     // already.
1832     IdResolver.RemoveDecl(D);
1833     auto ShadowI = ShadowingDecls.find(D);
1834     if (ShadowI != ShadowingDecls.end()) {
1835       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1836         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1837             << D << FD << FD->getParent();
1838         Diag(FD->getLocation(), diag::note_previous_declaration);
1839       }
1840       ShadowingDecls.erase(ShadowI);
1841     }
1842   }
1843 }
1844 
1845 /// Look for an Objective-C class in the translation unit.
1846 ///
1847 /// \param Id The name of the Objective-C class we're looking for. If
1848 /// typo-correction fixes this name, the Id will be updated
1849 /// to the fixed name.
1850 ///
1851 /// \param IdLoc The location of the name in the translation unit.
1852 ///
1853 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1854 /// if there is no class with the given name.
1855 ///
1856 /// \returns The declaration of the named Objective-C class, or NULL if the
1857 /// class could not be found.
1858 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1859                                               SourceLocation IdLoc,
1860                                               bool DoTypoCorrection) {
1861   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1862   // creation from this context.
1863   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1864 
1865   if (!IDecl && DoTypoCorrection) {
1866     // Perform typo correction at the given location, but only if we
1867     // find an Objective-C class name.
1868     if (TypoCorrection C = CorrectTypo(
1869             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1870             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1871             CTK_ErrorRecovery)) {
1872       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1873       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1874       Id = IDecl->getIdentifier();
1875     }
1876   }
1877   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1878   // This routine must always return a class definition, if any.
1879   if (Def && Def->getDefinition())
1880       Def = Def->getDefinition();
1881   return Def;
1882 }
1883 
1884 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1885 /// from S, where a non-field would be declared. This routine copes
1886 /// with the difference between C and C++ scoping rules in structs and
1887 /// unions. For example, the following code is well-formed in C but
1888 /// ill-formed in C++:
1889 /// @code
1890 /// struct S6 {
1891 ///   enum { BAR } e;
1892 /// };
1893 ///
1894 /// void test_S6() {
1895 ///   struct S6 a;
1896 ///   a.e = BAR;
1897 /// }
1898 /// @endcode
1899 /// For the declaration of BAR, this routine will return a different
1900 /// scope. The scope S will be the scope of the unnamed enumeration
1901 /// within S6. In C++, this routine will return the scope associated
1902 /// with S6, because the enumeration's scope is a transparent
1903 /// context but structures can contain non-field names. In C, this
1904 /// routine will return the translation unit scope, since the
1905 /// enumeration's scope is a transparent context and structures cannot
1906 /// contain non-field names.
1907 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1908   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1909          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1910          (S->isClassScope() && !getLangOpts().CPlusPlus))
1911     S = S->getParent();
1912   return S;
1913 }
1914 
1915 /// Looks up the declaration of "struct objc_super" and
1916 /// saves it for later use in building builtin declaration of
1917 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1918 /// pre-existing declaration exists no action takes place.
1919 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1920                                         IdentifierInfo *II) {
1921   if (!II->isStr("objc_msgSendSuper"))
1922     return;
1923   ASTContext &Context = ThisSema.Context;
1924 
1925   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1926                       SourceLocation(), Sema::LookupTagName);
1927   ThisSema.LookupName(Result, S);
1928   if (Result.getResultKind() == LookupResult::Found)
1929     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1930       Context.setObjCSuperType(Context.getTagDeclType(TD));
1931 }
1932 
1933 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1934                                ASTContext::GetBuiltinTypeError Error) {
1935   switch (Error) {
1936   case ASTContext::GE_None:
1937     return "";
1938   case ASTContext::GE_Missing_type:
1939     return BuiltinInfo.getHeaderName(ID);
1940   case ASTContext::GE_Missing_stdio:
1941     return "stdio.h";
1942   case ASTContext::GE_Missing_setjmp:
1943     return "setjmp.h";
1944   case ASTContext::GE_Missing_ucontext:
1945     return "ucontext.h";
1946   }
1947   llvm_unreachable("unhandled error kind");
1948 }
1949 
1950 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1951 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1952 /// if we're creating this built-in in anticipation of redeclaring the
1953 /// built-in.
1954 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1955                                      Scope *S, bool ForRedeclaration,
1956                                      SourceLocation Loc) {
1957   LookupPredefedObjCSuperType(*this, S, II);
1958 
1959   ASTContext::GetBuiltinTypeError Error;
1960   QualType R = Context.GetBuiltinType(ID, Error);
1961   if (Error) {
1962     if (ForRedeclaration)
1963       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1964           << getHeaderName(Context.BuiltinInfo, ID, Error)
1965           << Context.BuiltinInfo.getName(ID);
1966     return nullptr;
1967   }
1968 
1969   if (!ForRedeclaration &&
1970       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1971        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1972     Diag(Loc, diag::ext_implicit_lib_function_decl)
1973         << Context.BuiltinInfo.getName(ID) << R;
1974     if (Context.BuiltinInfo.getHeaderName(ID) &&
1975         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1976       Diag(Loc, diag::note_include_header_or_declare)
1977           << Context.BuiltinInfo.getHeaderName(ID)
1978           << Context.BuiltinInfo.getName(ID);
1979   }
1980 
1981   if (R.isNull())
1982     return nullptr;
1983 
1984   DeclContext *Parent = Context.getTranslationUnitDecl();
1985   if (getLangOpts().CPlusPlus) {
1986     LinkageSpecDecl *CLinkageDecl =
1987         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1988                                 LinkageSpecDecl::lang_c, false);
1989     CLinkageDecl->setImplicit();
1990     Parent->addDecl(CLinkageDecl);
1991     Parent = CLinkageDecl;
1992   }
1993 
1994   FunctionDecl *New = FunctionDecl::Create(Context,
1995                                            Parent,
1996                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1997                                            SC_Extern,
1998                                            false,
1999                                            R->isFunctionProtoType());
2000   New->setImplicit();
2001 
2002   // Create Decl objects for each parameter, adding them to the
2003   // FunctionDecl.
2004   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2005     SmallVector<ParmVarDecl*, 16> Params;
2006     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2007       ParmVarDecl *parm =
2008           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2009                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2010                               SC_None, nullptr);
2011       parm->setScopeInfo(0, i);
2012       Params.push_back(parm);
2013     }
2014     New->setParams(Params);
2015   }
2016 
2017   AddKnownFunctionAttributes(New);
2018   RegisterLocallyScopedExternCDecl(New, S);
2019 
2020   // TUScope is the translation-unit scope to insert this function into.
2021   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2022   // relate Scopes to DeclContexts, and probably eliminate CurContext
2023   // entirely, but we're not there yet.
2024   DeclContext *SavedContext = CurContext;
2025   CurContext = Parent;
2026   PushOnScopeChains(New, TUScope);
2027   CurContext = SavedContext;
2028   return New;
2029 }
2030 
2031 /// Typedef declarations don't have linkage, but they still denote the same
2032 /// entity if their types are the same.
2033 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2034 /// isSameEntity.
2035 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2036                                                      TypedefNameDecl *Decl,
2037                                                      LookupResult &Previous) {
2038   // This is only interesting when modules are enabled.
2039   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2040     return;
2041 
2042   // Empty sets are uninteresting.
2043   if (Previous.empty())
2044     return;
2045 
2046   LookupResult::Filter Filter = Previous.makeFilter();
2047   while (Filter.hasNext()) {
2048     NamedDecl *Old = Filter.next();
2049 
2050     // Non-hidden declarations are never ignored.
2051     if (S.isVisible(Old))
2052       continue;
2053 
2054     // Declarations of the same entity are not ignored, even if they have
2055     // different linkages.
2056     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2057       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2058                                 Decl->getUnderlyingType()))
2059         continue;
2060 
2061       // If both declarations give a tag declaration a typedef name for linkage
2062       // purposes, then they declare the same entity.
2063       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2064           Decl->getAnonDeclWithTypedefName())
2065         continue;
2066     }
2067 
2068     Filter.erase();
2069   }
2070 
2071   Filter.done();
2072 }
2073 
2074 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2075   QualType OldType;
2076   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2077     OldType = OldTypedef->getUnderlyingType();
2078   else
2079     OldType = Context.getTypeDeclType(Old);
2080   QualType NewType = New->getUnderlyingType();
2081 
2082   if (NewType->isVariablyModifiedType()) {
2083     // Must not redefine a typedef with a variably-modified type.
2084     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2085     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2086       << Kind << NewType;
2087     if (Old->getLocation().isValid())
2088       notePreviousDefinition(Old, New->getLocation());
2089     New->setInvalidDecl();
2090     return true;
2091   }
2092 
2093   if (OldType != NewType &&
2094       !OldType->isDependentType() &&
2095       !NewType->isDependentType() &&
2096       !Context.hasSameType(OldType, NewType)) {
2097     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2098     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2099       << Kind << NewType << OldType;
2100     if (Old->getLocation().isValid())
2101       notePreviousDefinition(Old, New->getLocation());
2102     New->setInvalidDecl();
2103     return true;
2104   }
2105   return false;
2106 }
2107 
2108 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2109 /// same name and scope as a previous declaration 'Old'.  Figure out
2110 /// how to resolve this situation, merging decls or emitting
2111 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2112 ///
2113 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2114                                 LookupResult &OldDecls) {
2115   // If the new decl is known invalid already, don't bother doing any
2116   // merging checks.
2117   if (New->isInvalidDecl()) return;
2118 
2119   // Allow multiple definitions for ObjC built-in typedefs.
2120   // FIXME: Verify the underlying types are equivalent!
2121   if (getLangOpts().ObjC) {
2122     const IdentifierInfo *TypeID = New->getIdentifier();
2123     switch (TypeID->getLength()) {
2124     default: break;
2125     case 2:
2126       {
2127         if (!TypeID->isStr("id"))
2128           break;
2129         QualType T = New->getUnderlyingType();
2130         if (!T->isPointerType())
2131           break;
2132         if (!T->isVoidPointerType()) {
2133           QualType PT = T->getAs<PointerType>()->getPointeeType();
2134           if (!PT->isStructureType())
2135             break;
2136         }
2137         Context.setObjCIdRedefinitionType(T);
2138         // Install the built-in type for 'id', ignoring the current definition.
2139         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2140         return;
2141       }
2142     case 5:
2143       if (!TypeID->isStr("Class"))
2144         break;
2145       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2146       // Install the built-in type for 'Class', ignoring the current definition.
2147       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2148       return;
2149     case 3:
2150       if (!TypeID->isStr("SEL"))
2151         break;
2152       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2153       // Install the built-in type for 'SEL', ignoring the current definition.
2154       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2155       return;
2156     }
2157     // Fall through - the typedef name was not a builtin type.
2158   }
2159 
2160   // Verify the old decl was also a type.
2161   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2162   if (!Old) {
2163     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2164       << New->getDeclName();
2165 
2166     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2167     if (OldD->getLocation().isValid())
2168       notePreviousDefinition(OldD, New->getLocation());
2169 
2170     return New->setInvalidDecl();
2171   }
2172 
2173   // If the old declaration is invalid, just give up here.
2174   if (Old->isInvalidDecl())
2175     return New->setInvalidDecl();
2176 
2177   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2179     auto *NewTag = New->getAnonDeclWithTypedefName();
2180     NamedDecl *Hidden = nullptr;
2181     if (OldTag && NewTag &&
2182         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2183         !hasVisibleDefinition(OldTag, &Hidden)) {
2184       // There is a definition of this tag, but it is not visible. Use it
2185       // instead of our tag.
2186       New->setTypeForDecl(OldTD->getTypeForDecl());
2187       if (OldTD->isModed())
2188         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2189                                     OldTD->getUnderlyingType());
2190       else
2191         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2192 
2193       // Make the old tag definition visible.
2194       makeMergedDefinitionVisible(Hidden);
2195 
2196       // If this was an unscoped enumeration, yank all of its enumerators
2197       // out of the scope.
2198       if (isa<EnumDecl>(NewTag)) {
2199         Scope *EnumScope = getNonFieldDeclScope(S);
2200         for (auto *D : NewTag->decls()) {
2201           auto *ED = cast<EnumConstantDecl>(D);
2202           assert(EnumScope->isDeclScope(ED));
2203           EnumScope->RemoveDecl(ED);
2204           IdResolver.RemoveDecl(ED);
2205           ED->getLexicalDeclContext()->removeDecl(ED);
2206         }
2207       }
2208     }
2209   }
2210 
2211   // If the typedef types are not identical, reject them in all languages and
2212   // with any extensions enabled.
2213   if (isIncompatibleTypedef(Old, New))
2214     return;
2215 
2216   // The types match.  Link up the redeclaration chain and merge attributes if
2217   // the old declaration was a typedef.
2218   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2219     New->setPreviousDecl(Typedef);
2220     mergeDeclAttributes(New, Old);
2221   }
2222 
2223   if (getLangOpts().MicrosoftExt)
2224     return;
2225 
2226   if (getLangOpts().CPlusPlus) {
2227     // C++ [dcl.typedef]p2:
2228     //   In a given non-class scope, a typedef specifier can be used to
2229     //   redefine the name of any type declared in that scope to refer
2230     //   to the type to which it already refers.
2231     if (!isa<CXXRecordDecl>(CurContext))
2232       return;
2233 
2234     // C++0x [dcl.typedef]p4:
2235     //   In a given class scope, a typedef specifier can be used to redefine
2236     //   any class-name declared in that scope that is not also a typedef-name
2237     //   to refer to the type to which it already refers.
2238     //
2239     // This wording came in via DR424, which was a correction to the
2240     // wording in DR56, which accidentally banned code like:
2241     //
2242     //   struct S {
2243     //     typedef struct A { } A;
2244     //   };
2245     //
2246     // in the C++03 standard. We implement the C++0x semantics, which
2247     // allow the above but disallow
2248     //
2249     //   struct S {
2250     //     typedef int I;
2251     //     typedef int I;
2252     //   };
2253     //
2254     // since that was the intent of DR56.
2255     if (!isa<TypedefNameDecl>(Old))
2256       return;
2257 
2258     Diag(New->getLocation(), diag::err_redefinition)
2259       << New->getDeclName();
2260     notePreviousDefinition(Old, New->getLocation());
2261     return New->setInvalidDecl();
2262   }
2263 
2264   // Modules always permit redefinition of typedefs, as does C11.
2265   if (getLangOpts().Modules || getLangOpts().C11)
2266     return;
2267 
2268   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2269   // is normally mapped to an error, but can be controlled with
2270   // -Wtypedef-redefinition.  If either the original or the redefinition is
2271   // in a system header, don't emit this for compatibility with GCC.
2272   if (getDiagnostics().getSuppressSystemWarnings() &&
2273       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2274       (Old->isImplicit() ||
2275        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2276        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2277     return;
2278 
2279   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2280     << New->getDeclName();
2281   notePreviousDefinition(Old, New->getLocation());
2282 }
2283 
2284 /// DeclhasAttr - returns true if decl Declaration already has the target
2285 /// attribute.
2286 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2287   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2288   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2289   for (const auto *i : D->attrs())
2290     if (i->getKind() == A->getKind()) {
2291       if (Ann) {
2292         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2293           return true;
2294         continue;
2295       }
2296       // FIXME: Don't hardcode this check
2297       if (OA && isa<OwnershipAttr>(i))
2298         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2299       return true;
2300     }
2301 
2302   return false;
2303 }
2304 
2305 static bool isAttributeTargetADefinition(Decl *D) {
2306   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2307     return VD->isThisDeclarationADefinition();
2308   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2309     return TD->isCompleteDefinition() || TD->isBeingDefined();
2310   return true;
2311 }
2312 
2313 /// Merge alignment attributes from \p Old to \p New, taking into account the
2314 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2315 ///
2316 /// \return \c true if any attributes were added to \p New.
2317 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2318   // Look for alignas attributes on Old, and pick out whichever attribute
2319   // specifies the strictest alignment requirement.
2320   AlignedAttr *OldAlignasAttr = nullptr;
2321   AlignedAttr *OldStrictestAlignAttr = nullptr;
2322   unsigned OldAlign = 0;
2323   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2324     // FIXME: We have no way of representing inherited dependent alignments
2325     // in a case like:
2326     //   template<int A, int B> struct alignas(A) X;
2327     //   template<int A, int B> struct alignas(B) X {};
2328     // For now, we just ignore any alignas attributes which are not on the
2329     // definition in such a case.
2330     if (I->isAlignmentDependent())
2331       return false;
2332 
2333     if (I->isAlignas())
2334       OldAlignasAttr = I;
2335 
2336     unsigned Align = I->getAlignment(S.Context);
2337     if (Align > OldAlign) {
2338       OldAlign = Align;
2339       OldStrictestAlignAttr = I;
2340     }
2341   }
2342 
2343   // Look for alignas attributes on New.
2344   AlignedAttr *NewAlignasAttr = nullptr;
2345   unsigned NewAlign = 0;
2346   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2347     if (I->isAlignmentDependent())
2348       return false;
2349 
2350     if (I->isAlignas())
2351       NewAlignasAttr = I;
2352 
2353     unsigned Align = I->getAlignment(S.Context);
2354     if (Align > NewAlign)
2355       NewAlign = Align;
2356   }
2357 
2358   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2359     // Both declarations have 'alignas' attributes. We require them to match.
2360     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2361     // fall short. (If two declarations both have alignas, they must both match
2362     // every definition, and so must match each other if there is a definition.)
2363 
2364     // If either declaration only contains 'alignas(0)' specifiers, then it
2365     // specifies the natural alignment for the type.
2366     if (OldAlign == 0 || NewAlign == 0) {
2367       QualType Ty;
2368       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2369         Ty = VD->getType();
2370       else
2371         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2372 
2373       if (OldAlign == 0)
2374         OldAlign = S.Context.getTypeAlign(Ty);
2375       if (NewAlign == 0)
2376         NewAlign = S.Context.getTypeAlign(Ty);
2377     }
2378 
2379     if (OldAlign != NewAlign) {
2380       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2381         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2382         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2383       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2384     }
2385   }
2386 
2387   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2388     // C++11 [dcl.align]p6:
2389     //   if any declaration of an entity has an alignment-specifier,
2390     //   every defining declaration of that entity shall specify an
2391     //   equivalent alignment.
2392     // C11 6.7.5/7:
2393     //   If the definition of an object does not have an alignment
2394     //   specifier, any other declaration of that object shall also
2395     //   have no alignment specifier.
2396     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2397       << OldAlignasAttr;
2398     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2399       << OldAlignasAttr;
2400   }
2401 
2402   bool AnyAdded = false;
2403 
2404   // Ensure we have an attribute representing the strictest alignment.
2405   if (OldAlign > NewAlign) {
2406     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2407     Clone->setInherited(true);
2408     New->addAttr(Clone);
2409     AnyAdded = true;
2410   }
2411 
2412   // Ensure we have an alignas attribute if the old declaration had one.
2413   if (OldAlignasAttr && !NewAlignasAttr &&
2414       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2415     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2416     Clone->setInherited(true);
2417     New->addAttr(Clone);
2418     AnyAdded = true;
2419   }
2420 
2421   return AnyAdded;
2422 }
2423 
2424 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2425                                const InheritableAttr *Attr,
2426                                Sema::AvailabilityMergeKind AMK) {
2427   // This function copies an attribute Attr from a previous declaration to the
2428   // new declaration D if the new declaration doesn't itself have that attribute
2429   // yet or if that attribute allows duplicates.
2430   // If you're adding a new attribute that requires logic different from
2431   // "use explicit attribute on decl if present, else use attribute from
2432   // previous decl", for example if the attribute needs to be consistent
2433   // between redeclarations, you need to call a custom merge function here.
2434   InheritableAttr *NewAttr = nullptr;
2435   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2436   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2437     NewAttr = S.mergeAvailabilityAttr(
2438         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2439         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2440         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2441         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2442   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2443     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444                                     AttrSpellingListIndex);
2445   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2446     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2447                                         AttrSpellingListIndex);
2448   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2449     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2450                                    AttrSpellingListIndex);
2451   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2452     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2453                                    AttrSpellingListIndex);
2454   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2455     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2456                                 FA->getFormatIdx(), FA->getFirstArg(),
2457                                 AttrSpellingListIndex);
2458   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2459     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2460                                  AttrSpellingListIndex);
2461   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2462     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2463                                  AttrSpellingListIndex);
2464   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2465     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2466                                        AttrSpellingListIndex,
2467                                        IA->getSemanticSpelling());
2468   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2469     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2470                                       &S.Context.Idents.get(AA->getSpelling()),
2471                                       AttrSpellingListIndex);
2472   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2473            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2474             isa<CUDAGlobalAttr>(Attr))) {
2475     // CUDA target attributes are part of function signature for
2476     // overloading purposes and must not be merged.
2477     return false;
2478   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2479     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2480   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2481     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2482   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2483     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2484   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2485     NewAttr = S.mergeCommonAttr(D, *CommonA);
2486   else if (isa<AlignedAttr>(Attr))
2487     // AlignedAttrs are handled separately, because we need to handle all
2488     // such attributes on a declaration at the same time.
2489     NewAttr = nullptr;
2490   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2491            (AMK == Sema::AMK_Override ||
2492             AMK == Sema::AMK_ProtocolImplementation))
2493     NewAttr = nullptr;
2494   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2495     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2496                               UA->getGuid());
2497   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2498     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2499   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2500     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2501   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2502     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2503 
2504   if (NewAttr) {
2505     NewAttr->setInherited(true);
2506     D->addAttr(NewAttr);
2507     if (isa<MSInheritanceAttr>(NewAttr))
2508       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2509     return true;
2510   }
2511 
2512   return false;
2513 }
2514 
2515 static const NamedDecl *getDefinition(const Decl *D) {
2516   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2517     return TD->getDefinition();
2518   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2519     const VarDecl *Def = VD->getDefinition();
2520     if (Def)
2521       return Def;
2522     return VD->getActingDefinition();
2523   }
2524   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2525     return FD->getDefinition();
2526   return nullptr;
2527 }
2528 
2529 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2530   for (const auto *Attribute : D->attrs())
2531     if (Attribute->getKind() == Kind)
2532       return true;
2533   return false;
2534 }
2535 
2536 /// checkNewAttributesAfterDef - If we already have a definition, check that
2537 /// there are no new attributes in this declaration.
2538 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2539   if (!New->hasAttrs())
2540     return;
2541 
2542   const NamedDecl *Def = getDefinition(Old);
2543   if (!Def || Def == New)
2544     return;
2545 
2546   AttrVec &NewAttributes = New->getAttrs();
2547   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2548     const Attr *NewAttribute = NewAttributes[I];
2549 
2550     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2551       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2552         Sema::SkipBodyInfo SkipBody;
2553         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2554 
2555         // If we're skipping this definition, drop the "alias" attribute.
2556         if (SkipBody.ShouldSkip) {
2557           NewAttributes.erase(NewAttributes.begin() + I);
2558           --E;
2559           continue;
2560         }
2561       } else {
2562         VarDecl *VD = cast<VarDecl>(New);
2563         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2564                                 VarDecl::TentativeDefinition
2565                             ? diag::err_alias_after_tentative
2566                             : diag::err_redefinition;
2567         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2568         if (Diag == diag::err_redefinition)
2569           S.notePreviousDefinition(Def, VD->getLocation());
2570         else
2571           S.Diag(Def->getLocation(), diag::note_previous_definition);
2572         VD->setInvalidDecl();
2573       }
2574       ++I;
2575       continue;
2576     }
2577 
2578     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2579       // Tentative definitions are only interesting for the alias check above.
2580       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2581         ++I;
2582         continue;
2583       }
2584     }
2585 
2586     if (hasAttribute(Def, NewAttribute->getKind())) {
2587       ++I;
2588       continue; // regular attr merging will take care of validating this.
2589     }
2590 
2591     if (isa<C11NoReturnAttr>(NewAttribute)) {
2592       // C's _Noreturn is allowed to be added to a function after it is defined.
2593       ++I;
2594       continue;
2595     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2596       if (AA->isAlignas()) {
2597         // C++11 [dcl.align]p6:
2598         //   if any declaration of an entity has an alignment-specifier,
2599         //   every defining declaration of that entity shall specify an
2600         //   equivalent alignment.
2601         // C11 6.7.5/7:
2602         //   If the definition of an object does not have an alignment
2603         //   specifier, any other declaration of that object shall also
2604         //   have no alignment specifier.
2605         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2606           << AA;
2607         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2608           << AA;
2609         NewAttributes.erase(NewAttributes.begin() + I);
2610         --E;
2611         continue;
2612       }
2613     }
2614 
2615     S.Diag(NewAttribute->getLocation(),
2616            diag::warn_attribute_precede_definition);
2617     S.Diag(Def->getLocation(), diag::note_previous_definition);
2618     NewAttributes.erase(NewAttributes.begin() + I);
2619     --E;
2620   }
2621 }
2622 
2623 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2624 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2625                                AvailabilityMergeKind AMK) {
2626   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2627     UsedAttr *NewAttr = OldAttr->clone(Context);
2628     NewAttr->setInherited(true);
2629     New->addAttr(NewAttr);
2630   }
2631 
2632   if (!Old->hasAttrs() && !New->hasAttrs())
2633     return;
2634 
2635   // Attributes declared post-definition are currently ignored.
2636   checkNewAttributesAfterDef(*this, New, Old);
2637 
2638   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2639     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2640       if (OldA->getLabel() != NewA->getLabel()) {
2641         // This redeclaration changes __asm__ label.
2642         Diag(New->getLocation(), diag::err_different_asm_label);
2643         Diag(OldA->getLocation(), diag::note_previous_declaration);
2644       }
2645     } else if (Old->isUsed()) {
2646       // This redeclaration adds an __asm__ label to a declaration that has
2647       // already been ODR-used.
2648       Diag(New->getLocation(), diag::err_late_asm_label_name)
2649         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2650     }
2651   }
2652 
2653   // Re-declaration cannot add abi_tag's.
2654   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2655     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2656       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2657         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2658                       NewTag) == OldAbiTagAttr->tags_end()) {
2659           Diag(NewAbiTagAttr->getLocation(),
2660                diag::err_new_abi_tag_on_redeclaration)
2661               << NewTag;
2662           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2663         }
2664       }
2665     } else {
2666       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2667       Diag(Old->getLocation(), diag::note_previous_declaration);
2668     }
2669   }
2670 
2671   // This redeclaration adds a section attribute.
2672   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2673     if (auto *VD = dyn_cast<VarDecl>(New)) {
2674       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2675         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2676         Diag(Old->getLocation(), diag::note_previous_declaration);
2677       }
2678     }
2679   }
2680 
2681   // Redeclaration adds code-seg attribute.
2682   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2683   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2684       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2685     Diag(New->getLocation(), diag::warn_mismatched_section)
2686          << 0 /*codeseg*/;
2687     Diag(Old->getLocation(), diag::note_previous_declaration);
2688   }
2689 
2690   if (!Old->hasAttrs())
2691     return;
2692 
2693   bool foundAny = New->hasAttrs();
2694 
2695   // Ensure that any moving of objects within the allocated map is done before
2696   // we process them.
2697   if (!foundAny) New->setAttrs(AttrVec());
2698 
2699   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2700     // Ignore deprecated/unavailable/availability attributes if requested.
2701     AvailabilityMergeKind LocalAMK = AMK_None;
2702     if (isa<DeprecatedAttr>(I) ||
2703         isa<UnavailableAttr>(I) ||
2704         isa<AvailabilityAttr>(I)) {
2705       switch (AMK) {
2706       case AMK_None:
2707         continue;
2708 
2709       case AMK_Redeclaration:
2710       case AMK_Override:
2711       case AMK_ProtocolImplementation:
2712         LocalAMK = AMK;
2713         break;
2714       }
2715     }
2716 
2717     // Already handled.
2718     if (isa<UsedAttr>(I))
2719       continue;
2720 
2721     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2722       foundAny = true;
2723   }
2724 
2725   if (mergeAlignedAttrs(*this, New, Old))
2726     foundAny = true;
2727 
2728   if (!foundAny) New->dropAttrs();
2729 }
2730 
2731 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2732 /// to the new one.
2733 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2734                                      const ParmVarDecl *oldDecl,
2735                                      Sema &S) {
2736   // C++11 [dcl.attr.depend]p2:
2737   //   The first declaration of a function shall specify the
2738   //   carries_dependency attribute for its declarator-id if any declaration
2739   //   of the function specifies the carries_dependency attribute.
2740   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2741   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2742     S.Diag(CDA->getLocation(),
2743            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2744     // Find the first declaration of the parameter.
2745     // FIXME: Should we build redeclaration chains for function parameters?
2746     const FunctionDecl *FirstFD =
2747       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2748     const ParmVarDecl *FirstVD =
2749       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2750     S.Diag(FirstVD->getLocation(),
2751            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2752   }
2753 
2754   if (!oldDecl->hasAttrs())
2755     return;
2756 
2757   bool foundAny = newDecl->hasAttrs();
2758 
2759   // Ensure that any moving of objects within the allocated map is
2760   // done before we process them.
2761   if (!foundAny) newDecl->setAttrs(AttrVec());
2762 
2763   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2764     if (!DeclHasAttr(newDecl, I)) {
2765       InheritableAttr *newAttr =
2766         cast<InheritableParamAttr>(I->clone(S.Context));
2767       newAttr->setInherited(true);
2768       newDecl->addAttr(newAttr);
2769       foundAny = true;
2770     }
2771   }
2772 
2773   if (!foundAny) newDecl->dropAttrs();
2774 }
2775 
2776 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2777                                 const ParmVarDecl *OldParam,
2778                                 Sema &S) {
2779   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2780     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2781       if (*Oldnullability != *Newnullability) {
2782         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2783           << DiagNullabilityKind(
2784                *Newnullability,
2785                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2786                 != 0))
2787           << DiagNullabilityKind(
2788                *Oldnullability,
2789                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2790                 != 0));
2791         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2792       }
2793     } else {
2794       QualType NewT = NewParam->getType();
2795       NewT = S.Context.getAttributedType(
2796                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2797                          NewT, NewT);
2798       NewParam->setType(NewT);
2799     }
2800   }
2801 }
2802 
2803 namespace {
2804 
2805 /// Used in MergeFunctionDecl to keep track of function parameters in
2806 /// C.
2807 struct GNUCompatibleParamWarning {
2808   ParmVarDecl *OldParm;
2809   ParmVarDecl *NewParm;
2810   QualType PromotedType;
2811 };
2812 
2813 } // end anonymous namespace
2814 
2815 /// getSpecialMember - get the special member enum for a method.
2816 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2817   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2818     if (Ctor->isDefaultConstructor())
2819       return Sema::CXXDefaultConstructor;
2820 
2821     if (Ctor->isCopyConstructor())
2822       return Sema::CXXCopyConstructor;
2823 
2824     if (Ctor->isMoveConstructor())
2825       return Sema::CXXMoveConstructor;
2826   } else if (isa<CXXDestructorDecl>(MD)) {
2827     return Sema::CXXDestructor;
2828   } else if (MD->isCopyAssignmentOperator()) {
2829     return Sema::CXXCopyAssignment;
2830   } else if (MD->isMoveAssignmentOperator()) {
2831     return Sema::CXXMoveAssignment;
2832   }
2833 
2834   return Sema::CXXInvalid;
2835 }
2836 
2837 // Determine whether the previous declaration was a definition, implicit
2838 // declaration, or a declaration.
2839 template <typename T>
2840 static std::pair<diag::kind, SourceLocation>
2841 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2842   diag::kind PrevDiag;
2843   SourceLocation OldLocation = Old->getLocation();
2844   if (Old->isThisDeclarationADefinition())
2845     PrevDiag = diag::note_previous_definition;
2846   else if (Old->isImplicit()) {
2847     PrevDiag = diag::note_previous_implicit_declaration;
2848     if (OldLocation.isInvalid())
2849       OldLocation = New->getLocation();
2850   } else
2851     PrevDiag = diag::note_previous_declaration;
2852   return std::make_pair(PrevDiag, OldLocation);
2853 }
2854 
2855 /// canRedefineFunction - checks if a function can be redefined. Currently,
2856 /// only extern inline functions can be redefined, and even then only in
2857 /// GNU89 mode.
2858 static bool canRedefineFunction(const FunctionDecl *FD,
2859                                 const LangOptions& LangOpts) {
2860   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2861           !LangOpts.CPlusPlus &&
2862           FD->isInlineSpecified() &&
2863           FD->getStorageClass() == SC_Extern);
2864 }
2865 
2866 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2867   const AttributedType *AT = T->getAs<AttributedType>();
2868   while (AT && !AT->isCallingConv())
2869     AT = AT->getModifiedType()->getAs<AttributedType>();
2870   return AT;
2871 }
2872 
2873 template <typename T>
2874 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2875   const DeclContext *DC = Old->getDeclContext();
2876   if (DC->isRecord())
2877     return false;
2878 
2879   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2880   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2881     return true;
2882   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2883     return true;
2884   return false;
2885 }
2886 
2887 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2888 static bool isExternC(VarTemplateDecl *) { return false; }
2889 
2890 /// Check whether a redeclaration of an entity introduced by a
2891 /// using-declaration is valid, given that we know it's not an overload
2892 /// (nor a hidden tag declaration).
2893 template<typename ExpectedDecl>
2894 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2895                                    ExpectedDecl *New) {
2896   // C++11 [basic.scope.declarative]p4:
2897   //   Given a set of declarations in a single declarative region, each of
2898   //   which specifies the same unqualified name,
2899   //   -- they shall all refer to the same entity, or all refer to functions
2900   //      and function templates; or
2901   //   -- exactly one declaration shall declare a class name or enumeration
2902   //      name that is not a typedef name and the other declarations shall all
2903   //      refer to the same variable or enumerator, or all refer to functions
2904   //      and function templates; in this case the class name or enumeration
2905   //      name is hidden (3.3.10).
2906 
2907   // C++11 [namespace.udecl]p14:
2908   //   If a function declaration in namespace scope or block scope has the
2909   //   same name and the same parameter-type-list as a function introduced
2910   //   by a using-declaration, and the declarations do not declare the same
2911   //   function, the program is ill-formed.
2912 
2913   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2914   if (Old &&
2915       !Old->getDeclContext()->getRedeclContext()->Equals(
2916           New->getDeclContext()->getRedeclContext()) &&
2917       !(isExternC(Old) && isExternC(New)))
2918     Old = nullptr;
2919 
2920   if (!Old) {
2921     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2922     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2923     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2924     return true;
2925   }
2926   return false;
2927 }
2928 
2929 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2930                                             const FunctionDecl *B) {
2931   assert(A->getNumParams() == B->getNumParams());
2932 
2933   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2934     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2935     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2936     if (AttrA == AttrB)
2937       return true;
2938     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2939            AttrA->isDynamic() == AttrB->isDynamic();
2940   };
2941 
2942   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2943 }
2944 
2945 /// If necessary, adjust the semantic declaration context for a qualified
2946 /// declaration to name the correct inline namespace within the qualifier.
2947 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2948                                                DeclaratorDecl *OldD) {
2949   // The only case where we need to update the DeclContext is when
2950   // redeclaration lookup for a qualified name finds a declaration
2951   // in an inline namespace within the context named by the qualifier:
2952   //
2953   //   inline namespace N { int f(); }
2954   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2955   //
2956   // For unqualified declarations, the semantic context *can* change
2957   // along the redeclaration chain (for local extern declarations,
2958   // extern "C" declarations, and friend declarations in particular).
2959   if (!NewD->getQualifier())
2960     return;
2961 
2962   // NewD is probably already in the right context.
2963   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2964   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2965   if (NamedDC->Equals(SemaDC))
2966     return;
2967 
2968   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2969           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2970          "unexpected context for redeclaration");
2971 
2972   auto *LexDC = NewD->getLexicalDeclContext();
2973   auto FixSemaDC = [=](NamedDecl *D) {
2974     if (!D)
2975       return;
2976     D->setDeclContext(SemaDC);
2977     D->setLexicalDeclContext(LexDC);
2978   };
2979 
2980   FixSemaDC(NewD);
2981   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2982     FixSemaDC(FD->getDescribedFunctionTemplate());
2983   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2984     FixSemaDC(VD->getDescribedVarTemplate());
2985 }
2986 
2987 /// MergeFunctionDecl - We just parsed a function 'New' from
2988 /// declarator D which has the same name and scope as a previous
2989 /// declaration 'Old'.  Figure out how to resolve this situation,
2990 /// merging decls or emitting diagnostics as appropriate.
2991 ///
2992 /// In C++, New and Old must be declarations that are not
2993 /// overloaded. Use IsOverload to determine whether New and Old are
2994 /// overloaded, and to select the Old declaration that New should be
2995 /// merged with.
2996 ///
2997 /// Returns true if there was an error, false otherwise.
2998 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2999                              Scope *S, bool MergeTypeWithOld) {
3000   // Verify the old decl was also a function.
3001   FunctionDecl *Old = OldD->getAsFunction();
3002   if (!Old) {
3003     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3004       if (New->getFriendObjectKind()) {
3005         Diag(New->getLocation(), diag::err_using_decl_friend);
3006         Diag(Shadow->getTargetDecl()->getLocation(),
3007              diag::note_using_decl_target);
3008         Diag(Shadow->getUsingDecl()->getLocation(),
3009              diag::note_using_decl) << 0;
3010         return true;
3011       }
3012 
3013       // Check whether the two declarations might declare the same function.
3014       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3015         return true;
3016       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3017     } else {
3018       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3019         << New->getDeclName();
3020       notePreviousDefinition(OldD, New->getLocation());
3021       return true;
3022     }
3023   }
3024 
3025   // If the old declaration is invalid, just give up here.
3026   if (Old->isInvalidDecl())
3027     return true;
3028 
3029   // Disallow redeclaration of some builtins.
3030   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3031     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3032     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3033         << Old << Old->getType();
3034     return true;
3035   }
3036 
3037   diag::kind PrevDiag;
3038   SourceLocation OldLocation;
3039   std::tie(PrevDiag, OldLocation) =
3040       getNoteDiagForInvalidRedeclaration(Old, New);
3041 
3042   // Don't complain about this if we're in GNU89 mode and the old function
3043   // is an extern inline function.
3044   // Don't complain about specializations. They are not supposed to have
3045   // storage classes.
3046   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3047       New->getStorageClass() == SC_Static &&
3048       Old->hasExternalFormalLinkage() &&
3049       !New->getTemplateSpecializationInfo() &&
3050       !canRedefineFunction(Old, getLangOpts())) {
3051     if (getLangOpts().MicrosoftExt) {
3052       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3053       Diag(OldLocation, PrevDiag);
3054     } else {
3055       Diag(New->getLocation(), diag::err_static_non_static) << New;
3056       Diag(OldLocation, PrevDiag);
3057       return true;
3058     }
3059   }
3060 
3061   if (New->hasAttr<InternalLinkageAttr>() &&
3062       !Old->hasAttr<InternalLinkageAttr>()) {
3063     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3064         << New->getDeclName();
3065     notePreviousDefinition(Old, New->getLocation());
3066     New->dropAttr<InternalLinkageAttr>();
3067   }
3068 
3069   if (CheckRedeclarationModuleOwnership(New, Old))
3070     return true;
3071 
3072   if (!getLangOpts().CPlusPlus) {
3073     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3074     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3075       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3076         << New << OldOvl;
3077 
3078       // Try our best to find a decl that actually has the overloadable
3079       // attribute for the note. In most cases (e.g. programs with only one
3080       // broken declaration/definition), this won't matter.
3081       //
3082       // FIXME: We could do this if we juggled some extra state in
3083       // OverloadableAttr, rather than just removing it.
3084       const Decl *DiagOld = Old;
3085       if (OldOvl) {
3086         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3087           const auto *A = D->getAttr<OverloadableAttr>();
3088           return A && !A->isImplicit();
3089         });
3090         // If we've implicitly added *all* of the overloadable attrs to this
3091         // chain, emitting a "previous redecl" note is pointless.
3092         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3093       }
3094 
3095       if (DiagOld)
3096         Diag(DiagOld->getLocation(),
3097              diag::note_attribute_overloadable_prev_overload)
3098           << OldOvl;
3099 
3100       if (OldOvl)
3101         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3102       else
3103         New->dropAttr<OverloadableAttr>();
3104     }
3105   }
3106 
3107   // If a function is first declared with a calling convention, but is later
3108   // declared or defined without one, all following decls assume the calling
3109   // convention of the first.
3110   //
3111   // It's OK if a function is first declared without a calling convention,
3112   // but is later declared or defined with the default calling convention.
3113   //
3114   // To test if either decl has an explicit calling convention, we look for
3115   // AttributedType sugar nodes on the type as written.  If they are missing or
3116   // were canonicalized away, we assume the calling convention was implicit.
3117   //
3118   // Note also that we DO NOT return at this point, because we still have
3119   // other tests to run.
3120   QualType OldQType = Context.getCanonicalType(Old->getType());
3121   QualType NewQType = Context.getCanonicalType(New->getType());
3122   const FunctionType *OldType = cast<FunctionType>(OldQType);
3123   const FunctionType *NewType = cast<FunctionType>(NewQType);
3124   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3125   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3126   bool RequiresAdjustment = false;
3127 
3128   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3129     FunctionDecl *First = Old->getFirstDecl();
3130     const FunctionType *FT =
3131         First->getType().getCanonicalType()->castAs<FunctionType>();
3132     FunctionType::ExtInfo FI = FT->getExtInfo();
3133     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3134     if (!NewCCExplicit) {
3135       // Inherit the CC from the previous declaration if it was specified
3136       // there but not here.
3137       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3138       RequiresAdjustment = true;
3139     } else {
3140       // Calling conventions aren't compatible, so complain.
3141       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3142       Diag(New->getLocation(), diag::err_cconv_change)
3143         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3144         << !FirstCCExplicit
3145         << (!FirstCCExplicit ? "" :
3146             FunctionType::getNameForCallConv(FI.getCC()));
3147 
3148       // Put the note on the first decl, since it is the one that matters.
3149       Diag(First->getLocation(), diag::note_previous_declaration);
3150       return true;
3151     }
3152   }
3153 
3154   // FIXME: diagnose the other way around?
3155   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3156     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3157     RequiresAdjustment = true;
3158   }
3159 
3160   // Merge regparm attribute.
3161   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3162       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3163     if (NewTypeInfo.getHasRegParm()) {
3164       Diag(New->getLocation(), diag::err_regparm_mismatch)
3165         << NewType->getRegParmType()
3166         << OldType->getRegParmType();
3167       Diag(OldLocation, diag::note_previous_declaration);
3168       return true;
3169     }
3170 
3171     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3172     RequiresAdjustment = true;
3173   }
3174 
3175   // Merge ns_returns_retained attribute.
3176   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3177     if (NewTypeInfo.getProducesResult()) {
3178       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3179           << "'ns_returns_retained'";
3180       Diag(OldLocation, diag::note_previous_declaration);
3181       return true;
3182     }
3183 
3184     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3185     RequiresAdjustment = true;
3186   }
3187 
3188   if (OldTypeInfo.getNoCallerSavedRegs() !=
3189       NewTypeInfo.getNoCallerSavedRegs()) {
3190     if (NewTypeInfo.getNoCallerSavedRegs()) {
3191       AnyX86NoCallerSavedRegistersAttr *Attr =
3192         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3193       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3194       Diag(OldLocation, diag::note_previous_declaration);
3195       return true;
3196     }
3197 
3198     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3199     RequiresAdjustment = true;
3200   }
3201 
3202   if (RequiresAdjustment) {
3203     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3204     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3205     New->setType(QualType(AdjustedType, 0));
3206     NewQType = Context.getCanonicalType(New->getType());
3207     NewType = cast<FunctionType>(NewQType);
3208   }
3209 
3210   // If this redeclaration makes the function inline, we may need to add it to
3211   // UndefinedButUsed.
3212   if (!Old->isInlined() && New->isInlined() &&
3213       !New->hasAttr<GNUInlineAttr>() &&
3214       !getLangOpts().GNUInline &&
3215       Old->isUsed(false) &&
3216       !Old->isDefined() && !New->isThisDeclarationADefinition())
3217     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3218                                            SourceLocation()));
3219 
3220   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3221   // about it.
3222   if (New->hasAttr<GNUInlineAttr>() &&
3223       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3224     UndefinedButUsed.erase(Old->getCanonicalDecl());
3225   }
3226 
3227   // If pass_object_size params don't match up perfectly, this isn't a valid
3228   // redeclaration.
3229   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3230       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3231     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3232         << New->getDeclName();
3233     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3234     return true;
3235   }
3236 
3237   if (getLangOpts().CPlusPlus) {
3238     // C++1z [over.load]p2
3239     //   Certain function declarations cannot be overloaded:
3240     //     -- Function declarations that differ only in the return type,
3241     //        the exception specification, or both cannot be overloaded.
3242 
3243     // Check the exception specifications match. This may recompute the type of
3244     // both Old and New if it resolved exception specifications, so grab the
3245     // types again after this. Because this updates the type, we do this before
3246     // any of the other checks below, which may update the "de facto" NewQType
3247     // but do not necessarily update the type of New.
3248     if (CheckEquivalentExceptionSpec(Old, New))
3249       return true;
3250     OldQType = Context.getCanonicalType(Old->getType());
3251     NewQType = Context.getCanonicalType(New->getType());
3252 
3253     // Go back to the type source info to compare the declared return types,
3254     // per C++1y [dcl.type.auto]p13:
3255     //   Redeclarations or specializations of a function or function template
3256     //   with a declared return type that uses a placeholder type shall also
3257     //   use that placeholder, not a deduced type.
3258     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3259     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3260     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3261         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3262                                        OldDeclaredReturnType)) {
3263       QualType ResQT;
3264       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3265           OldDeclaredReturnType->isObjCObjectPointerType())
3266         // FIXME: This does the wrong thing for a deduced return type.
3267         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3268       if (ResQT.isNull()) {
3269         if (New->isCXXClassMember() && New->isOutOfLine())
3270           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3271               << New << New->getReturnTypeSourceRange();
3272         else
3273           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3274               << New->getReturnTypeSourceRange();
3275         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3276                                     << Old->getReturnTypeSourceRange();
3277         return true;
3278       }
3279       else
3280         NewQType = ResQT;
3281     }
3282 
3283     QualType OldReturnType = OldType->getReturnType();
3284     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3285     if (OldReturnType != NewReturnType) {
3286       // If this function has a deduced return type and has already been
3287       // defined, copy the deduced value from the old declaration.
3288       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3289       if (OldAT && OldAT->isDeduced()) {
3290         New->setType(
3291             SubstAutoType(New->getType(),
3292                           OldAT->isDependentType() ? Context.DependentTy
3293                                                    : OldAT->getDeducedType()));
3294         NewQType = Context.getCanonicalType(
3295             SubstAutoType(NewQType,
3296                           OldAT->isDependentType() ? Context.DependentTy
3297                                                    : OldAT->getDeducedType()));
3298       }
3299     }
3300 
3301     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3302     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3303     if (OldMethod && NewMethod) {
3304       // Preserve triviality.
3305       NewMethod->setTrivial(OldMethod->isTrivial());
3306 
3307       // MSVC allows explicit template specialization at class scope:
3308       // 2 CXXMethodDecls referring to the same function will be injected.
3309       // We don't want a redeclaration error.
3310       bool IsClassScopeExplicitSpecialization =
3311                               OldMethod->isFunctionTemplateSpecialization() &&
3312                               NewMethod->isFunctionTemplateSpecialization();
3313       bool isFriend = NewMethod->getFriendObjectKind();
3314 
3315       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3316           !IsClassScopeExplicitSpecialization) {
3317         //    -- Member function declarations with the same name and the
3318         //       same parameter types cannot be overloaded if any of them
3319         //       is a static member function declaration.
3320         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3321           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3322           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3323           return true;
3324         }
3325 
3326         // C++ [class.mem]p1:
3327         //   [...] A member shall not be declared twice in the
3328         //   member-specification, except that a nested class or member
3329         //   class template can be declared and then later defined.
3330         if (!inTemplateInstantiation()) {
3331           unsigned NewDiag;
3332           if (isa<CXXConstructorDecl>(OldMethod))
3333             NewDiag = diag::err_constructor_redeclared;
3334           else if (isa<CXXDestructorDecl>(NewMethod))
3335             NewDiag = diag::err_destructor_redeclared;
3336           else if (isa<CXXConversionDecl>(NewMethod))
3337             NewDiag = diag::err_conv_function_redeclared;
3338           else
3339             NewDiag = diag::err_member_redeclared;
3340 
3341           Diag(New->getLocation(), NewDiag);
3342         } else {
3343           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3344             << New << New->getType();
3345         }
3346         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3347         return true;
3348 
3349       // Complain if this is an explicit declaration of a special
3350       // member that was initially declared implicitly.
3351       //
3352       // As an exception, it's okay to befriend such methods in order
3353       // to permit the implicit constructor/destructor/operator calls.
3354       } else if (OldMethod->isImplicit()) {
3355         if (isFriend) {
3356           NewMethod->setImplicit();
3357         } else {
3358           Diag(NewMethod->getLocation(),
3359                diag::err_definition_of_implicitly_declared_member)
3360             << New << getSpecialMember(OldMethod);
3361           return true;
3362         }
3363       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3364         Diag(NewMethod->getLocation(),
3365              diag::err_definition_of_explicitly_defaulted_member)
3366           << getSpecialMember(OldMethod);
3367         return true;
3368       }
3369     }
3370 
3371     // C++11 [dcl.attr.noreturn]p1:
3372     //   The first declaration of a function shall specify the noreturn
3373     //   attribute if any declaration of that function specifies the noreturn
3374     //   attribute.
3375     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3376     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3377       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3378       Diag(Old->getFirstDecl()->getLocation(),
3379            diag::note_noreturn_missing_first_decl);
3380     }
3381 
3382     // C++11 [dcl.attr.depend]p2:
3383     //   The first declaration of a function shall specify the
3384     //   carries_dependency attribute for its declarator-id if any declaration
3385     //   of the function specifies the carries_dependency attribute.
3386     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3387     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3388       Diag(CDA->getLocation(),
3389            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3390       Diag(Old->getFirstDecl()->getLocation(),
3391            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3392     }
3393 
3394     // (C++98 8.3.5p3):
3395     //   All declarations for a function shall agree exactly in both the
3396     //   return type and the parameter-type-list.
3397     // We also want to respect all the extended bits except noreturn.
3398 
3399     // noreturn should now match unless the old type info didn't have it.
3400     QualType OldQTypeForComparison = OldQType;
3401     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3402       auto *OldType = OldQType->castAs<FunctionProtoType>();
3403       const FunctionType *OldTypeForComparison
3404         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3405       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3406       assert(OldQTypeForComparison.isCanonical());
3407     }
3408 
3409     if (haveIncompatibleLanguageLinkages(Old, New)) {
3410       // As a special case, retain the language linkage from previous
3411       // declarations of a friend function as an extension.
3412       //
3413       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3414       // and is useful because there's otherwise no way to specify language
3415       // linkage within class scope.
3416       //
3417       // Check cautiously as the friend object kind isn't yet complete.
3418       if (New->getFriendObjectKind() != Decl::FOK_None) {
3419         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3420         Diag(OldLocation, PrevDiag);
3421       } else {
3422         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3423         Diag(OldLocation, PrevDiag);
3424         return true;
3425       }
3426     }
3427 
3428     if (OldQTypeForComparison == NewQType)
3429       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3430 
3431     // If the types are imprecise (due to dependent constructs in friends or
3432     // local extern declarations), it's OK if they differ. We'll check again
3433     // during instantiation.
3434     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3435       return false;
3436 
3437     // Fall through for conflicting redeclarations and redefinitions.
3438   }
3439 
3440   // C: Function types need to be compatible, not identical. This handles
3441   // duplicate function decls like "void f(int); void f(enum X);" properly.
3442   if (!getLangOpts().CPlusPlus &&
3443       Context.typesAreCompatible(OldQType, NewQType)) {
3444     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3445     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3446     const FunctionProtoType *OldProto = nullptr;
3447     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3448         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3449       // The old declaration provided a function prototype, but the
3450       // new declaration does not. Merge in the prototype.
3451       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3452       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3453       NewQType =
3454           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3455                                   OldProto->getExtProtoInfo());
3456       New->setType(NewQType);
3457       New->setHasInheritedPrototype();
3458 
3459       // Synthesize parameters with the same types.
3460       SmallVector<ParmVarDecl*, 16> Params;
3461       for (const auto &ParamType : OldProto->param_types()) {
3462         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3463                                                  SourceLocation(), nullptr,
3464                                                  ParamType, /*TInfo=*/nullptr,
3465                                                  SC_None, nullptr);
3466         Param->setScopeInfo(0, Params.size());
3467         Param->setImplicit();
3468         Params.push_back(Param);
3469       }
3470 
3471       New->setParams(Params);
3472     }
3473 
3474     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3475   }
3476 
3477   // GNU C permits a K&R definition to follow a prototype declaration
3478   // if the declared types of the parameters in the K&R definition
3479   // match the types in the prototype declaration, even when the
3480   // promoted types of the parameters from the K&R definition differ
3481   // from the types in the prototype. GCC then keeps the types from
3482   // the prototype.
3483   //
3484   // If a variadic prototype is followed by a non-variadic K&R definition,
3485   // the K&R definition becomes variadic.  This is sort of an edge case, but
3486   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3487   // C99 6.9.1p8.
3488   if (!getLangOpts().CPlusPlus &&
3489       Old->hasPrototype() && !New->hasPrototype() &&
3490       New->getType()->getAs<FunctionProtoType>() &&
3491       Old->getNumParams() == New->getNumParams()) {
3492     SmallVector<QualType, 16> ArgTypes;
3493     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3494     const FunctionProtoType *OldProto
3495       = Old->getType()->getAs<FunctionProtoType>();
3496     const FunctionProtoType *NewProto
3497       = New->getType()->getAs<FunctionProtoType>();
3498 
3499     // Determine whether this is the GNU C extension.
3500     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3501                                                NewProto->getReturnType());
3502     bool LooseCompatible = !MergedReturn.isNull();
3503     for (unsigned Idx = 0, End = Old->getNumParams();
3504          LooseCompatible && Idx != End; ++Idx) {
3505       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3506       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3507       if (Context.typesAreCompatible(OldParm->getType(),
3508                                      NewProto->getParamType(Idx))) {
3509         ArgTypes.push_back(NewParm->getType());
3510       } else if (Context.typesAreCompatible(OldParm->getType(),
3511                                             NewParm->getType(),
3512                                             /*CompareUnqualified=*/true)) {
3513         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3514                                            NewProto->getParamType(Idx) };
3515         Warnings.push_back(Warn);
3516         ArgTypes.push_back(NewParm->getType());
3517       } else
3518         LooseCompatible = false;
3519     }
3520 
3521     if (LooseCompatible) {
3522       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3523         Diag(Warnings[Warn].NewParm->getLocation(),
3524              diag::ext_param_promoted_not_compatible_with_prototype)
3525           << Warnings[Warn].PromotedType
3526           << Warnings[Warn].OldParm->getType();
3527         if (Warnings[Warn].OldParm->getLocation().isValid())
3528           Diag(Warnings[Warn].OldParm->getLocation(),
3529                diag::note_previous_declaration);
3530       }
3531 
3532       if (MergeTypeWithOld)
3533         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3534                                              OldProto->getExtProtoInfo()));
3535       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3536     }
3537 
3538     // Fall through to diagnose conflicting types.
3539   }
3540 
3541   // A function that has already been declared has been redeclared or
3542   // defined with a different type; show an appropriate diagnostic.
3543 
3544   // If the previous declaration was an implicitly-generated builtin
3545   // declaration, then at the very least we should use a specialized note.
3546   unsigned BuiltinID;
3547   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3548     // If it's actually a library-defined builtin function like 'malloc'
3549     // or 'printf', just warn about the incompatible redeclaration.
3550     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3551       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3552       Diag(OldLocation, diag::note_previous_builtin_declaration)
3553         << Old << Old->getType();
3554 
3555       // If this is a global redeclaration, just forget hereafter
3556       // about the "builtin-ness" of the function.
3557       //
3558       // Doing this for local extern declarations is problematic.  If
3559       // the builtin declaration remains visible, a second invalid
3560       // local declaration will produce a hard error; if it doesn't
3561       // remain visible, a single bogus local redeclaration (which is
3562       // actually only a warning) could break all the downstream code.
3563       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3564         New->getIdentifier()->revertBuiltin();
3565 
3566       return false;
3567     }
3568 
3569     PrevDiag = diag::note_previous_builtin_declaration;
3570   }
3571 
3572   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3573   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3574   return true;
3575 }
3576 
3577 /// Completes the merge of two function declarations that are
3578 /// known to be compatible.
3579 ///
3580 /// This routine handles the merging of attributes and other
3581 /// properties of function declarations from the old declaration to
3582 /// the new declaration, once we know that New is in fact a
3583 /// redeclaration of Old.
3584 ///
3585 /// \returns false
3586 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3587                                         Scope *S, bool MergeTypeWithOld) {
3588   // Merge the attributes
3589   mergeDeclAttributes(New, Old);
3590 
3591   // Merge "pure" flag.
3592   if (Old->isPure())
3593     New->setPure();
3594 
3595   // Merge "used" flag.
3596   if (Old->getMostRecentDecl()->isUsed(false))
3597     New->setIsUsed();
3598 
3599   // Merge attributes from the parameters.  These can mismatch with K&R
3600   // declarations.
3601   if (New->getNumParams() == Old->getNumParams())
3602       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3603         ParmVarDecl *NewParam = New->getParamDecl(i);
3604         ParmVarDecl *OldParam = Old->getParamDecl(i);
3605         mergeParamDeclAttributes(NewParam, OldParam, *this);
3606         mergeParamDeclTypes(NewParam, OldParam, *this);
3607       }
3608 
3609   if (getLangOpts().CPlusPlus)
3610     return MergeCXXFunctionDecl(New, Old, S);
3611 
3612   // Merge the function types so the we get the composite types for the return
3613   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3614   // was visible.
3615   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3616   if (!Merged.isNull() && MergeTypeWithOld)
3617     New->setType(Merged);
3618 
3619   return false;
3620 }
3621 
3622 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3623                                 ObjCMethodDecl *oldMethod) {
3624   // Merge the attributes, including deprecated/unavailable
3625   AvailabilityMergeKind MergeKind =
3626     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3627       ? AMK_ProtocolImplementation
3628       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3629                                                        : AMK_Override;
3630 
3631   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3632 
3633   // Merge attributes from the parameters.
3634   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3635                                        oe = oldMethod->param_end();
3636   for (ObjCMethodDecl::param_iterator
3637          ni = newMethod->param_begin(), ne = newMethod->param_end();
3638        ni != ne && oi != oe; ++ni, ++oi)
3639     mergeParamDeclAttributes(*ni, *oi, *this);
3640 
3641   CheckObjCMethodOverride(newMethod, oldMethod);
3642 }
3643 
3644 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3645   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3646 
3647   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3648          ? diag::err_redefinition_different_type
3649          : diag::err_redeclaration_different_type)
3650     << New->getDeclName() << New->getType() << Old->getType();
3651 
3652   diag::kind PrevDiag;
3653   SourceLocation OldLocation;
3654   std::tie(PrevDiag, OldLocation)
3655     = getNoteDiagForInvalidRedeclaration(Old, New);
3656   S.Diag(OldLocation, PrevDiag);
3657   New->setInvalidDecl();
3658 }
3659 
3660 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3661 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3662 /// emitting diagnostics as appropriate.
3663 ///
3664 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3665 /// to here in AddInitializerToDecl. We can't check them before the initializer
3666 /// is attached.
3667 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3668                              bool MergeTypeWithOld) {
3669   if (New->isInvalidDecl() || Old->isInvalidDecl())
3670     return;
3671 
3672   QualType MergedT;
3673   if (getLangOpts().CPlusPlus) {
3674     if (New->getType()->isUndeducedType()) {
3675       // We don't know what the new type is until the initializer is attached.
3676       return;
3677     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3678       // These could still be something that needs exception specs checked.
3679       return MergeVarDeclExceptionSpecs(New, Old);
3680     }
3681     // C++ [basic.link]p10:
3682     //   [...] the types specified by all declarations referring to a given
3683     //   object or function shall be identical, except that declarations for an
3684     //   array object can specify array types that differ by the presence or
3685     //   absence of a major array bound (8.3.4).
3686     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3687       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3688       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3689 
3690       // We are merging a variable declaration New into Old. If it has an array
3691       // bound, and that bound differs from Old's bound, we should diagnose the
3692       // mismatch.
3693       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3694         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3695              PrevVD = PrevVD->getPreviousDecl()) {
3696           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3697           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3698             continue;
3699 
3700           if (!Context.hasSameType(NewArray, PrevVDTy))
3701             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3702         }
3703       }
3704 
3705       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3706         if (Context.hasSameType(OldArray->getElementType(),
3707                                 NewArray->getElementType()))
3708           MergedT = New->getType();
3709       }
3710       // FIXME: Check visibility. New is hidden but has a complete type. If New
3711       // has no array bound, it should not inherit one from Old, if Old is not
3712       // visible.
3713       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3714         if (Context.hasSameType(OldArray->getElementType(),
3715                                 NewArray->getElementType()))
3716           MergedT = Old->getType();
3717       }
3718     }
3719     else if (New->getType()->isObjCObjectPointerType() &&
3720                Old->getType()->isObjCObjectPointerType()) {
3721       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3722                                               Old->getType());
3723     }
3724   } else {
3725     // C 6.2.7p2:
3726     //   All declarations that refer to the same object or function shall have
3727     //   compatible type.
3728     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3729   }
3730   if (MergedT.isNull()) {
3731     // It's OK if we couldn't merge types if either type is dependent, for a
3732     // block-scope variable. In other cases (static data members of class
3733     // templates, variable templates, ...), we require the types to be
3734     // equivalent.
3735     // FIXME: The C++ standard doesn't say anything about this.
3736     if ((New->getType()->isDependentType() ||
3737          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3738       // If the old type was dependent, we can't merge with it, so the new type
3739       // becomes dependent for now. We'll reproduce the original type when we
3740       // instantiate the TypeSourceInfo for the variable.
3741       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3742         New->setType(Context.DependentTy);
3743       return;
3744     }
3745     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3746   }
3747 
3748   // Don't actually update the type on the new declaration if the old
3749   // declaration was an extern declaration in a different scope.
3750   if (MergeTypeWithOld)
3751     New->setType(MergedT);
3752 }
3753 
3754 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3755                                   LookupResult &Previous) {
3756   // C11 6.2.7p4:
3757   //   For an identifier with internal or external linkage declared
3758   //   in a scope in which a prior declaration of that identifier is
3759   //   visible, if the prior declaration specifies internal or
3760   //   external linkage, the type of the identifier at the later
3761   //   declaration becomes the composite type.
3762   //
3763   // If the variable isn't visible, we do not merge with its type.
3764   if (Previous.isShadowed())
3765     return false;
3766 
3767   if (S.getLangOpts().CPlusPlus) {
3768     // C++11 [dcl.array]p3:
3769     //   If there is a preceding declaration of the entity in the same
3770     //   scope in which the bound was specified, an omitted array bound
3771     //   is taken to be the same as in that earlier declaration.
3772     return NewVD->isPreviousDeclInSameBlockScope() ||
3773            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3774             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3775   } else {
3776     // If the old declaration was function-local, don't merge with its
3777     // type unless we're in the same function.
3778     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3779            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3780   }
3781 }
3782 
3783 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3784 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3785 /// situation, merging decls or emitting diagnostics as appropriate.
3786 ///
3787 /// Tentative definition rules (C99 6.9.2p2) are checked by
3788 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3789 /// definitions here, since the initializer hasn't been attached.
3790 ///
3791 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3792   // If the new decl is already invalid, don't do any other checking.
3793   if (New->isInvalidDecl())
3794     return;
3795 
3796   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3797     return;
3798 
3799   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3800 
3801   // Verify the old decl was also a variable or variable template.
3802   VarDecl *Old = nullptr;
3803   VarTemplateDecl *OldTemplate = nullptr;
3804   if (Previous.isSingleResult()) {
3805     if (NewTemplate) {
3806       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3807       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3808 
3809       if (auto *Shadow =
3810               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3811         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3812           return New->setInvalidDecl();
3813     } else {
3814       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3815 
3816       if (auto *Shadow =
3817               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3818         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3819           return New->setInvalidDecl();
3820     }
3821   }
3822   if (!Old) {
3823     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3824         << New->getDeclName();
3825     notePreviousDefinition(Previous.getRepresentativeDecl(),
3826                            New->getLocation());
3827     return New->setInvalidDecl();
3828   }
3829 
3830   // Ensure the template parameters are compatible.
3831   if (NewTemplate &&
3832       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3833                                       OldTemplate->getTemplateParameters(),
3834                                       /*Complain=*/true, TPL_TemplateMatch))
3835     return New->setInvalidDecl();
3836 
3837   // C++ [class.mem]p1:
3838   //   A member shall not be declared twice in the member-specification [...]
3839   //
3840   // Here, we need only consider static data members.
3841   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3842     Diag(New->getLocation(), diag::err_duplicate_member)
3843       << New->getIdentifier();
3844     Diag(Old->getLocation(), diag::note_previous_declaration);
3845     New->setInvalidDecl();
3846   }
3847 
3848   mergeDeclAttributes(New, Old);
3849   // Warn if an already-declared variable is made a weak_import in a subsequent
3850   // declaration
3851   if (New->hasAttr<WeakImportAttr>() &&
3852       Old->getStorageClass() == SC_None &&
3853       !Old->hasAttr<WeakImportAttr>()) {
3854     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3855     notePreviousDefinition(Old, New->getLocation());
3856     // Remove weak_import attribute on new declaration.
3857     New->dropAttr<WeakImportAttr>();
3858   }
3859 
3860   if (New->hasAttr<InternalLinkageAttr>() &&
3861       !Old->hasAttr<InternalLinkageAttr>()) {
3862     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3863         << New->getDeclName();
3864     notePreviousDefinition(Old, New->getLocation());
3865     New->dropAttr<InternalLinkageAttr>();
3866   }
3867 
3868   // Merge the types.
3869   VarDecl *MostRecent = Old->getMostRecentDecl();
3870   if (MostRecent != Old) {
3871     MergeVarDeclTypes(New, MostRecent,
3872                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3873     if (New->isInvalidDecl())
3874       return;
3875   }
3876 
3877   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3878   if (New->isInvalidDecl())
3879     return;
3880 
3881   diag::kind PrevDiag;
3882   SourceLocation OldLocation;
3883   std::tie(PrevDiag, OldLocation) =
3884       getNoteDiagForInvalidRedeclaration(Old, New);
3885 
3886   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3887   if (New->getStorageClass() == SC_Static &&
3888       !New->isStaticDataMember() &&
3889       Old->hasExternalFormalLinkage()) {
3890     if (getLangOpts().MicrosoftExt) {
3891       Diag(New->getLocation(), diag::ext_static_non_static)
3892           << New->getDeclName();
3893       Diag(OldLocation, PrevDiag);
3894     } else {
3895       Diag(New->getLocation(), diag::err_static_non_static)
3896           << New->getDeclName();
3897       Diag(OldLocation, PrevDiag);
3898       return New->setInvalidDecl();
3899     }
3900   }
3901   // C99 6.2.2p4:
3902   //   For an identifier declared with the storage-class specifier
3903   //   extern in a scope in which a prior declaration of that
3904   //   identifier is visible,23) if the prior declaration specifies
3905   //   internal or external linkage, the linkage of the identifier at
3906   //   the later declaration is the same as the linkage specified at
3907   //   the prior declaration. If no prior declaration is visible, or
3908   //   if the prior declaration specifies no linkage, then the
3909   //   identifier has external linkage.
3910   if (New->hasExternalStorage() && Old->hasLinkage())
3911     /* Okay */;
3912   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3913            !New->isStaticDataMember() &&
3914            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3915     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3916     Diag(OldLocation, PrevDiag);
3917     return New->setInvalidDecl();
3918   }
3919 
3920   // Check if extern is followed by non-extern and vice-versa.
3921   if (New->hasExternalStorage() &&
3922       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3923     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3924     Diag(OldLocation, PrevDiag);
3925     return New->setInvalidDecl();
3926   }
3927   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3928       !New->hasExternalStorage()) {
3929     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3930     Diag(OldLocation, PrevDiag);
3931     return New->setInvalidDecl();
3932   }
3933 
3934   if (CheckRedeclarationModuleOwnership(New, Old))
3935     return;
3936 
3937   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3938 
3939   // FIXME: The test for external storage here seems wrong? We still
3940   // need to check for mismatches.
3941   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3942       // Don't complain about out-of-line definitions of static members.
3943       !(Old->getLexicalDeclContext()->isRecord() &&
3944         !New->getLexicalDeclContext()->isRecord())) {
3945     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3946     Diag(OldLocation, PrevDiag);
3947     return New->setInvalidDecl();
3948   }
3949 
3950   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3951     if (VarDecl *Def = Old->getDefinition()) {
3952       // C++1z [dcl.fcn.spec]p4:
3953       //   If the definition of a variable appears in a translation unit before
3954       //   its first declaration as inline, the program is ill-formed.
3955       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3956       Diag(Def->getLocation(), diag::note_previous_definition);
3957     }
3958   }
3959 
3960   // If this redeclaration makes the variable inline, we may need to add it to
3961   // UndefinedButUsed.
3962   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3963       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3964     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3965                                            SourceLocation()));
3966 
3967   if (New->getTLSKind() != Old->getTLSKind()) {
3968     if (!Old->getTLSKind()) {
3969       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3970       Diag(OldLocation, PrevDiag);
3971     } else if (!New->getTLSKind()) {
3972       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3973       Diag(OldLocation, PrevDiag);
3974     } else {
3975       // Do not allow redeclaration to change the variable between requiring
3976       // static and dynamic initialization.
3977       // FIXME: GCC allows this, but uses the TLS keyword on the first
3978       // declaration to determine the kind. Do we need to be compatible here?
3979       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3980         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3981       Diag(OldLocation, PrevDiag);
3982     }
3983   }
3984 
3985   // C++ doesn't have tentative definitions, so go right ahead and check here.
3986   if (getLangOpts().CPlusPlus &&
3987       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3988     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3989         Old->getCanonicalDecl()->isConstexpr()) {
3990       // This definition won't be a definition any more once it's been merged.
3991       Diag(New->getLocation(),
3992            diag::warn_deprecated_redundant_constexpr_static_def);
3993     } else if (VarDecl *Def = Old->getDefinition()) {
3994       if (checkVarDeclRedefinition(Def, New))
3995         return;
3996     }
3997   }
3998 
3999   if (haveIncompatibleLanguageLinkages(Old, New)) {
4000     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4001     Diag(OldLocation, PrevDiag);
4002     New->setInvalidDecl();
4003     return;
4004   }
4005 
4006   // Merge "used" flag.
4007   if (Old->getMostRecentDecl()->isUsed(false))
4008     New->setIsUsed();
4009 
4010   // Keep a chain of previous declarations.
4011   New->setPreviousDecl(Old);
4012   if (NewTemplate)
4013     NewTemplate->setPreviousDecl(OldTemplate);
4014   adjustDeclContextForDeclaratorDecl(New, Old);
4015 
4016   // Inherit access appropriately.
4017   New->setAccess(Old->getAccess());
4018   if (NewTemplate)
4019     NewTemplate->setAccess(New->getAccess());
4020 
4021   if (Old->isInline())
4022     New->setImplicitlyInline();
4023 }
4024 
4025 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4026   SourceManager &SrcMgr = getSourceManager();
4027   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4028   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4029   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4030   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4031   auto &HSI = PP.getHeaderSearchInfo();
4032   StringRef HdrFilename =
4033       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4034 
4035   auto noteFromModuleOrInclude = [&](Module *Mod,
4036                                      SourceLocation IncLoc) -> bool {
4037     // Redefinition errors with modules are common with non modular mapped
4038     // headers, example: a non-modular header H in module A that also gets
4039     // included directly in a TU. Pointing twice to the same header/definition
4040     // is confusing, try to get better diagnostics when modules is on.
4041     if (IncLoc.isValid()) {
4042       if (Mod) {
4043         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4044             << HdrFilename.str() << Mod->getFullModuleName();
4045         if (!Mod->DefinitionLoc.isInvalid())
4046           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4047               << Mod->getFullModuleName();
4048       } else {
4049         Diag(IncLoc, diag::note_redefinition_include_same_file)
4050             << HdrFilename.str();
4051       }
4052       return true;
4053     }
4054 
4055     return false;
4056   };
4057 
4058   // Is it the same file and same offset? Provide more information on why
4059   // this leads to a redefinition error.
4060   bool EmittedDiag = false;
4061   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4062     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4063     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4064     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4065     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4066 
4067     // If the header has no guards, emit a note suggesting one.
4068     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4069       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4070 
4071     if (EmittedDiag)
4072       return;
4073   }
4074 
4075   // Redefinition coming from different files or couldn't do better above.
4076   if (Old->getLocation().isValid())
4077     Diag(Old->getLocation(), diag::note_previous_definition);
4078 }
4079 
4080 /// We've just determined that \p Old and \p New both appear to be definitions
4081 /// of the same variable. Either diagnose or fix the problem.
4082 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4083   if (!hasVisibleDefinition(Old) &&
4084       (New->getFormalLinkage() == InternalLinkage ||
4085        New->isInline() ||
4086        New->getDescribedVarTemplate() ||
4087        New->getNumTemplateParameterLists() ||
4088        New->getDeclContext()->isDependentContext())) {
4089     // The previous definition is hidden, and multiple definitions are
4090     // permitted (in separate TUs). Demote this to a declaration.
4091     New->demoteThisDefinitionToDeclaration();
4092 
4093     // Make the canonical definition visible.
4094     if (auto *OldTD = Old->getDescribedVarTemplate())
4095       makeMergedDefinitionVisible(OldTD);
4096     makeMergedDefinitionVisible(Old);
4097     return false;
4098   } else {
4099     Diag(New->getLocation(), diag::err_redefinition) << New;
4100     notePreviousDefinition(Old, New->getLocation());
4101     New->setInvalidDecl();
4102     return true;
4103   }
4104 }
4105 
4106 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4107 /// no declarator (e.g. "struct foo;") is parsed.
4108 Decl *
4109 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4110                                  RecordDecl *&AnonRecord) {
4111   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4112                                     AnonRecord);
4113 }
4114 
4115 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4116 // disambiguate entities defined in different scopes.
4117 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4118 // compatibility.
4119 // We will pick our mangling number depending on which version of MSVC is being
4120 // targeted.
4121 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4122   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4123              ? S->getMSCurManglingNumber()
4124              : S->getMSLastManglingNumber();
4125 }
4126 
4127 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4128   if (!Context.getLangOpts().CPlusPlus)
4129     return;
4130 
4131   if (isa<CXXRecordDecl>(Tag->getParent())) {
4132     // If this tag is the direct child of a class, number it if
4133     // it is anonymous.
4134     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4135       return;
4136     MangleNumberingContext &MCtx =
4137         Context.getManglingNumberContext(Tag->getParent());
4138     Context.setManglingNumber(
4139         Tag, MCtx.getManglingNumber(
4140                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4141     return;
4142   }
4143 
4144   // If this tag isn't a direct child of a class, number it if it is local.
4145   Decl *ManglingContextDecl;
4146   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4147           Tag->getDeclContext(), ManglingContextDecl)) {
4148     Context.setManglingNumber(
4149         Tag, MCtx->getManglingNumber(
4150                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4151   }
4152 }
4153 
4154 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4155                                         TypedefNameDecl *NewTD) {
4156   if (TagFromDeclSpec->isInvalidDecl())
4157     return;
4158 
4159   // Do nothing if the tag already has a name for linkage purposes.
4160   if (TagFromDeclSpec->hasNameForLinkage())
4161     return;
4162 
4163   // A well-formed anonymous tag must always be a TUK_Definition.
4164   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4165 
4166   // The type must match the tag exactly;  no qualifiers allowed.
4167   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4168                            Context.getTagDeclType(TagFromDeclSpec))) {
4169     if (getLangOpts().CPlusPlus)
4170       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4171     return;
4172   }
4173 
4174   // If we've already computed linkage for the anonymous tag, then
4175   // adding a typedef name for the anonymous decl can change that
4176   // linkage, which might be a serious problem.  Diagnose this as
4177   // unsupported and ignore the typedef name.  TODO: we should
4178   // pursue this as a language defect and establish a formal rule
4179   // for how to handle it.
4180   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4181     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4182 
4183     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4184     tagLoc = getLocForEndOfToken(tagLoc);
4185 
4186     llvm::SmallString<40> textToInsert;
4187     textToInsert += ' ';
4188     textToInsert += NewTD->getIdentifier()->getName();
4189     Diag(tagLoc, diag::note_typedef_changes_linkage)
4190         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4191     return;
4192   }
4193 
4194   // Otherwise, set this is the anon-decl typedef for the tag.
4195   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4196 }
4197 
4198 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4199   switch (T) {
4200   case DeclSpec::TST_class:
4201     return 0;
4202   case DeclSpec::TST_struct:
4203     return 1;
4204   case DeclSpec::TST_interface:
4205     return 2;
4206   case DeclSpec::TST_union:
4207     return 3;
4208   case DeclSpec::TST_enum:
4209     return 4;
4210   default:
4211     llvm_unreachable("unexpected type specifier");
4212   }
4213 }
4214 
4215 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4216 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4217 /// parameters to cope with template friend declarations.
4218 Decl *
4219 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4220                                  MultiTemplateParamsArg TemplateParams,
4221                                  bool IsExplicitInstantiation,
4222                                  RecordDecl *&AnonRecord) {
4223   Decl *TagD = nullptr;
4224   TagDecl *Tag = nullptr;
4225   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4226       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4227       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4228       DS.getTypeSpecType() == DeclSpec::TST_union ||
4229       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4230     TagD = DS.getRepAsDecl();
4231 
4232     if (!TagD) // We probably had an error
4233       return nullptr;
4234 
4235     // Note that the above type specs guarantee that the
4236     // type rep is a Decl, whereas in many of the others
4237     // it's a Type.
4238     if (isa<TagDecl>(TagD))
4239       Tag = cast<TagDecl>(TagD);
4240     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4241       Tag = CTD->getTemplatedDecl();
4242   }
4243 
4244   if (Tag) {
4245     handleTagNumbering(Tag, S);
4246     Tag->setFreeStanding();
4247     if (Tag->isInvalidDecl())
4248       return Tag;
4249   }
4250 
4251   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4252     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4253     // or incomplete types shall not be restrict-qualified."
4254     if (TypeQuals & DeclSpec::TQ_restrict)
4255       Diag(DS.getRestrictSpecLoc(),
4256            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4257            << DS.getSourceRange();
4258   }
4259 
4260   if (DS.isInlineSpecified())
4261     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4262         << getLangOpts().CPlusPlus17;
4263 
4264   if (DS.isConstexprSpecified()) {
4265     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4266     // and definitions of functions and variables.
4267     if (Tag)
4268       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4269           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4270     else
4271       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4272     // Don't emit warnings after this error.
4273     return TagD;
4274   }
4275 
4276   DiagnoseFunctionSpecifiers(DS);
4277 
4278   if (DS.isFriendSpecified()) {
4279     // If we're dealing with a decl but not a TagDecl, assume that
4280     // whatever routines created it handled the friendship aspect.
4281     if (TagD && !Tag)
4282       return nullptr;
4283     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4284   }
4285 
4286   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4287   bool IsExplicitSpecialization =
4288     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4289   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4290       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4291       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4292     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4293     // nested-name-specifier unless it is an explicit instantiation
4294     // or an explicit specialization.
4295     //
4296     // FIXME: We allow class template partial specializations here too, per the
4297     // obvious intent of DR1819.
4298     //
4299     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4300     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4301         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4302     return nullptr;
4303   }
4304 
4305   // Track whether this decl-specifier declares anything.
4306   bool DeclaresAnything = true;
4307 
4308   // Handle anonymous struct definitions.
4309   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4310     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4311         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4312       if (getLangOpts().CPlusPlus ||
4313           Record->getDeclContext()->isRecord()) {
4314         // If CurContext is a DeclContext that can contain statements,
4315         // RecursiveASTVisitor won't visit the decls that
4316         // BuildAnonymousStructOrUnion() will put into CurContext.
4317         // Also store them here so that they can be part of the
4318         // DeclStmt that gets created in this case.
4319         // FIXME: Also return the IndirectFieldDecls created by
4320         // BuildAnonymousStructOr union, for the same reason?
4321         if (CurContext->isFunctionOrMethod())
4322           AnonRecord = Record;
4323         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4324                                            Context.getPrintingPolicy());
4325       }
4326 
4327       DeclaresAnything = false;
4328     }
4329   }
4330 
4331   // C11 6.7.2.1p2:
4332   //   A struct-declaration that does not declare an anonymous structure or
4333   //   anonymous union shall contain a struct-declarator-list.
4334   //
4335   // This rule also existed in C89 and C99; the grammar for struct-declaration
4336   // did not permit a struct-declaration without a struct-declarator-list.
4337   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4338       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4339     // Check for Microsoft C extension: anonymous struct/union member.
4340     // Handle 2 kinds of anonymous struct/union:
4341     //   struct STRUCT;
4342     //   union UNION;
4343     // and
4344     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4345     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4346     if ((Tag && Tag->getDeclName()) ||
4347         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4348       RecordDecl *Record = nullptr;
4349       if (Tag)
4350         Record = dyn_cast<RecordDecl>(Tag);
4351       else if (const RecordType *RT =
4352                    DS.getRepAsType().get()->getAsStructureType())
4353         Record = RT->getDecl();
4354       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4355         Record = UT->getDecl();
4356 
4357       if (Record && getLangOpts().MicrosoftExt) {
4358         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4359             << Record->isUnion() << DS.getSourceRange();
4360         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4361       }
4362 
4363       DeclaresAnything = false;
4364     }
4365   }
4366 
4367   // Skip all the checks below if we have a type error.
4368   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4369       (TagD && TagD->isInvalidDecl()))
4370     return TagD;
4371 
4372   if (getLangOpts().CPlusPlus &&
4373       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4374     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4375       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4376           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4377         DeclaresAnything = false;
4378 
4379   if (!DS.isMissingDeclaratorOk()) {
4380     // Customize diagnostic for a typedef missing a name.
4381     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4382       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4383           << DS.getSourceRange();
4384     else
4385       DeclaresAnything = false;
4386   }
4387 
4388   if (DS.isModulePrivateSpecified() &&
4389       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4390     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4391       << Tag->getTagKind()
4392       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4393 
4394   ActOnDocumentableDecl(TagD);
4395 
4396   // C 6.7/2:
4397   //   A declaration [...] shall declare at least a declarator [...], a tag,
4398   //   or the members of an enumeration.
4399   // C++ [dcl.dcl]p3:
4400   //   [If there are no declarators], and except for the declaration of an
4401   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4402   //   names into the program, or shall redeclare a name introduced by a
4403   //   previous declaration.
4404   if (!DeclaresAnything) {
4405     // In C, we allow this as a (popular) extension / bug. Don't bother
4406     // producing further diagnostics for redundant qualifiers after this.
4407     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4408     return TagD;
4409   }
4410 
4411   // C++ [dcl.stc]p1:
4412   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4413   //   init-declarator-list of the declaration shall not be empty.
4414   // C++ [dcl.fct.spec]p1:
4415   //   If a cv-qualifier appears in a decl-specifier-seq, the
4416   //   init-declarator-list of the declaration shall not be empty.
4417   //
4418   // Spurious qualifiers here appear to be valid in C.
4419   unsigned DiagID = diag::warn_standalone_specifier;
4420   if (getLangOpts().CPlusPlus)
4421     DiagID = diag::ext_standalone_specifier;
4422 
4423   // Note that a linkage-specification sets a storage class, but
4424   // 'extern "C" struct foo;' is actually valid and not theoretically
4425   // useless.
4426   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4427     if (SCS == DeclSpec::SCS_mutable)
4428       // Since mutable is not a viable storage class specifier in C, there is
4429       // no reason to treat it as an extension. Instead, diagnose as an error.
4430       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4431     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4432       Diag(DS.getStorageClassSpecLoc(), DiagID)
4433         << DeclSpec::getSpecifierName(SCS);
4434   }
4435 
4436   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4437     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4438       << DeclSpec::getSpecifierName(TSCS);
4439   if (DS.getTypeQualifiers()) {
4440     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4441       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4442     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4443       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4444     // Restrict is covered above.
4445     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4446       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4447     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4448       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4449   }
4450 
4451   // Warn about ignored type attributes, for example:
4452   // __attribute__((aligned)) struct A;
4453   // Attributes should be placed after tag to apply to type declaration.
4454   if (!DS.getAttributes().empty()) {
4455     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4456     if (TypeSpecType == DeclSpec::TST_class ||
4457         TypeSpecType == DeclSpec::TST_struct ||
4458         TypeSpecType == DeclSpec::TST_interface ||
4459         TypeSpecType == DeclSpec::TST_union ||
4460         TypeSpecType == DeclSpec::TST_enum) {
4461       for (const ParsedAttr &AL : DS.getAttributes())
4462         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4463             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4464     }
4465   }
4466 
4467   return TagD;
4468 }
4469 
4470 /// We are trying to inject an anonymous member into the given scope;
4471 /// check if there's an existing declaration that can't be overloaded.
4472 ///
4473 /// \return true if this is a forbidden redeclaration
4474 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4475                                          Scope *S,
4476                                          DeclContext *Owner,
4477                                          DeclarationName Name,
4478                                          SourceLocation NameLoc,
4479                                          bool IsUnion) {
4480   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4481                  Sema::ForVisibleRedeclaration);
4482   if (!SemaRef.LookupName(R, S)) return false;
4483 
4484   // Pick a representative declaration.
4485   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4486   assert(PrevDecl && "Expected a non-null Decl");
4487 
4488   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4489     return false;
4490 
4491   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4492     << IsUnion << Name;
4493   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4494 
4495   return true;
4496 }
4497 
4498 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4499 /// anonymous struct or union AnonRecord into the owning context Owner
4500 /// and scope S. This routine will be invoked just after we realize
4501 /// that an unnamed union or struct is actually an anonymous union or
4502 /// struct, e.g.,
4503 ///
4504 /// @code
4505 /// union {
4506 ///   int i;
4507 ///   float f;
4508 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4509 ///    // f into the surrounding scope.x
4510 /// @endcode
4511 ///
4512 /// This routine is recursive, injecting the names of nested anonymous
4513 /// structs/unions into the owning context and scope as well.
4514 static bool
4515 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4516                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4517                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4518   bool Invalid = false;
4519 
4520   // Look every FieldDecl and IndirectFieldDecl with a name.
4521   for (auto *D : AnonRecord->decls()) {
4522     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4523         cast<NamedDecl>(D)->getDeclName()) {
4524       ValueDecl *VD = cast<ValueDecl>(D);
4525       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4526                                        VD->getLocation(),
4527                                        AnonRecord->isUnion())) {
4528         // C++ [class.union]p2:
4529         //   The names of the members of an anonymous union shall be
4530         //   distinct from the names of any other entity in the
4531         //   scope in which the anonymous union is declared.
4532         Invalid = true;
4533       } else {
4534         // C++ [class.union]p2:
4535         //   For the purpose of name lookup, after the anonymous union
4536         //   definition, the members of the anonymous union are
4537         //   considered to have been defined in the scope in which the
4538         //   anonymous union is declared.
4539         unsigned OldChainingSize = Chaining.size();
4540         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4541           Chaining.append(IF->chain_begin(), IF->chain_end());
4542         else
4543           Chaining.push_back(VD);
4544 
4545         assert(Chaining.size() >= 2);
4546         NamedDecl **NamedChain =
4547           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4548         for (unsigned i = 0; i < Chaining.size(); i++)
4549           NamedChain[i] = Chaining[i];
4550 
4551         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4552             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4553             VD->getType(), {NamedChain, Chaining.size()});
4554 
4555         for (const auto *Attr : VD->attrs())
4556           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4557 
4558         IndirectField->setAccess(AS);
4559         IndirectField->setImplicit();
4560         SemaRef.PushOnScopeChains(IndirectField, S);
4561 
4562         // That includes picking up the appropriate access specifier.
4563         if (AS != AS_none) IndirectField->setAccess(AS);
4564 
4565         Chaining.resize(OldChainingSize);
4566       }
4567     }
4568   }
4569 
4570   return Invalid;
4571 }
4572 
4573 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4574 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4575 /// illegal input values are mapped to SC_None.
4576 static StorageClass
4577 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4578   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4579   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4580          "Parser allowed 'typedef' as storage class VarDecl.");
4581   switch (StorageClassSpec) {
4582   case DeclSpec::SCS_unspecified:    return SC_None;
4583   case DeclSpec::SCS_extern:
4584     if (DS.isExternInLinkageSpec())
4585       return SC_None;
4586     return SC_Extern;
4587   case DeclSpec::SCS_static:         return SC_Static;
4588   case DeclSpec::SCS_auto:           return SC_Auto;
4589   case DeclSpec::SCS_register:       return SC_Register;
4590   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4591     // Illegal SCSs map to None: error reporting is up to the caller.
4592   case DeclSpec::SCS_mutable:        // Fall through.
4593   case DeclSpec::SCS_typedef:        return SC_None;
4594   }
4595   llvm_unreachable("unknown storage class specifier");
4596 }
4597 
4598 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4599   assert(Record->hasInClassInitializer());
4600 
4601   for (const auto *I : Record->decls()) {
4602     const auto *FD = dyn_cast<FieldDecl>(I);
4603     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4604       FD = IFD->getAnonField();
4605     if (FD && FD->hasInClassInitializer())
4606       return FD->getLocation();
4607   }
4608 
4609   llvm_unreachable("couldn't find in-class initializer");
4610 }
4611 
4612 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4613                                       SourceLocation DefaultInitLoc) {
4614   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4615     return;
4616 
4617   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4618   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4619 }
4620 
4621 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4622                                       CXXRecordDecl *AnonUnion) {
4623   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4624     return;
4625 
4626   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4627 }
4628 
4629 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4630 /// anonymous structure or union. Anonymous unions are a C++ feature
4631 /// (C++ [class.union]) and a C11 feature; anonymous structures
4632 /// are a C11 feature and GNU C++ extension.
4633 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4634                                         AccessSpecifier AS,
4635                                         RecordDecl *Record,
4636                                         const PrintingPolicy &Policy) {
4637   DeclContext *Owner = Record->getDeclContext();
4638 
4639   // Diagnose whether this anonymous struct/union is an extension.
4640   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4641     Diag(Record->getLocation(), diag::ext_anonymous_union);
4642   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4643     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4644   else if (!Record->isUnion() && !getLangOpts().C11)
4645     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4646 
4647   // C and C++ require different kinds of checks for anonymous
4648   // structs/unions.
4649   bool Invalid = false;
4650   if (getLangOpts().CPlusPlus) {
4651     const char *PrevSpec = nullptr;
4652     unsigned DiagID;
4653     if (Record->isUnion()) {
4654       // C++ [class.union]p6:
4655       // C++17 [class.union.anon]p2:
4656       //   Anonymous unions declared in a named namespace or in the
4657       //   global namespace shall be declared static.
4658       DeclContext *OwnerScope = Owner->getRedeclContext();
4659       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4660           (OwnerScope->isTranslationUnit() ||
4661            (OwnerScope->isNamespace() &&
4662             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4663         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4664           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4665 
4666         // Recover by adding 'static'.
4667         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4668                                PrevSpec, DiagID, Policy);
4669       }
4670       // C++ [class.union]p6:
4671       //   A storage class is not allowed in a declaration of an
4672       //   anonymous union in a class scope.
4673       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4674                isa<RecordDecl>(Owner)) {
4675         Diag(DS.getStorageClassSpecLoc(),
4676              diag::err_anonymous_union_with_storage_spec)
4677           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4678 
4679         // Recover by removing the storage specifier.
4680         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4681                                SourceLocation(),
4682                                PrevSpec, DiagID, Context.getPrintingPolicy());
4683       }
4684     }
4685 
4686     // Ignore const/volatile/restrict qualifiers.
4687     if (DS.getTypeQualifiers()) {
4688       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4689         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4690           << Record->isUnion() << "const"
4691           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4692       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4693         Diag(DS.getVolatileSpecLoc(),
4694              diag::ext_anonymous_struct_union_qualified)
4695           << Record->isUnion() << "volatile"
4696           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4697       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4698         Diag(DS.getRestrictSpecLoc(),
4699              diag::ext_anonymous_struct_union_qualified)
4700           << Record->isUnion() << "restrict"
4701           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4702       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4703         Diag(DS.getAtomicSpecLoc(),
4704              diag::ext_anonymous_struct_union_qualified)
4705           << Record->isUnion() << "_Atomic"
4706           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4707       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4708         Diag(DS.getUnalignedSpecLoc(),
4709              diag::ext_anonymous_struct_union_qualified)
4710           << Record->isUnion() << "__unaligned"
4711           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4712 
4713       DS.ClearTypeQualifiers();
4714     }
4715 
4716     // C++ [class.union]p2:
4717     //   The member-specification of an anonymous union shall only
4718     //   define non-static data members. [Note: nested types and
4719     //   functions cannot be declared within an anonymous union. ]
4720     for (auto *Mem : Record->decls()) {
4721       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4722         // C++ [class.union]p3:
4723         //   An anonymous union shall not have private or protected
4724         //   members (clause 11).
4725         assert(FD->getAccess() != AS_none);
4726         if (FD->getAccess() != AS_public) {
4727           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4728             << Record->isUnion() << (FD->getAccess() == AS_protected);
4729           Invalid = true;
4730         }
4731 
4732         // C++ [class.union]p1
4733         //   An object of a class with a non-trivial constructor, a non-trivial
4734         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4735         //   assignment operator cannot be a member of a union, nor can an
4736         //   array of such objects.
4737         if (CheckNontrivialField(FD))
4738           Invalid = true;
4739       } else if (Mem->isImplicit()) {
4740         // Any implicit members are fine.
4741       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4742         // This is a type that showed up in an
4743         // elaborated-type-specifier inside the anonymous struct or
4744         // union, but which actually declares a type outside of the
4745         // anonymous struct or union. It's okay.
4746       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4747         if (!MemRecord->isAnonymousStructOrUnion() &&
4748             MemRecord->getDeclName()) {
4749           // Visual C++ allows type definition in anonymous struct or union.
4750           if (getLangOpts().MicrosoftExt)
4751             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4752               << Record->isUnion();
4753           else {
4754             // This is a nested type declaration.
4755             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4756               << Record->isUnion();
4757             Invalid = true;
4758           }
4759         } else {
4760           // This is an anonymous type definition within another anonymous type.
4761           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4762           // not part of standard C++.
4763           Diag(MemRecord->getLocation(),
4764                diag::ext_anonymous_record_with_anonymous_type)
4765             << Record->isUnion();
4766         }
4767       } else if (isa<AccessSpecDecl>(Mem)) {
4768         // Any access specifier is fine.
4769       } else if (isa<StaticAssertDecl>(Mem)) {
4770         // In C++1z, static_assert declarations are also fine.
4771       } else {
4772         // We have something that isn't a non-static data
4773         // member. Complain about it.
4774         unsigned DK = diag::err_anonymous_record_bad_member;
4775         if (isa<TypeDecl>(Mem))
4776           DK = diag::err_anonymous_record_with_type;
4777         else if (isa<FunctionDecl>(Mem))
4778           DK = diag::err_anonymous_record_with_function;
4779         else if (isa<VarDecl>(Mem))
4780           DK = diag::err_anonymous_record_with_static;
4781 
4782         // Visual C++ allows type definition in anonymous struct or union.
4783         if (getLangOpts().MicrosoftExt &&
4784             DK == diag::err_anonymous_record_with_type)
4785           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4786             << Record->isUnion();
4787         else {
4788           Diag(Mem->getLocation(), DK) << Record->isUnion();
4789           Invalid = true;
4790         }
4791       }
4792     }
4793 
4794     // C++11 [class.union]p8 (DR1460):
4795     //   At most one variant member of a union may have a
4796     //   brace-or-equal-initializer.
4797     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4798         Owner->isRecord())
4799       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4800                                 cast<CXXRecordDecl>(Record));
4801   }
4802 
4803   if (!Record->isUnion() && !Owner->isRecord()) {
4804     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4805       << getLangOpts().CPlusPlus;
4806     Invalid = true;
4807   }
4808 
4809   // Mock up a declarator.
4810   Declarator Dc(DS, DeclaratorContext::MemberContext);
4811   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4812   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4813 
4814   // Create a declaration for this anonymous struct/union.
4815   NamedDecl *Anon = nullptr;
4816   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4817     Anon = FieldDecl::Create(
4818         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4819         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4820         /*BitWidth=*/nullptr, /*Mutable=*/false,
4821         /*InitStyle=*/ICIS_NoInit);
4822     Anon->setAccess(AS);
4823     if (getLangOpts().CPlusPlus)
4824       FieldCollector->Add(cast<FieldDecl>(Anon));
4825   } else {
4826     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4827     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4828     if (SCSpec == DeclSpec::SCS_mutable) {
4829       // mutable can only appear on non-static class members, so it's always
4830       // an error here
4831       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4832       Invalid = true;
4833       SC = SC_None;
4834     }
4835 
4836     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4837                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4838                            Context.getTypeDeclType(Record), TInfo, SC);
4839 
4840     // Default-initialize the implicit variable. This initialization will be
4841     // trivial in almost all cases, except if a union member has an in-class
4842     // initializer:
4843     //   union { int n = 0; };
4844     ActOnUninitializedDecl(Anon);
4845   }
4846   Anon->setImplicit();
4847 
4848   // Mark this as an anonymous struct/union type.
4849   Record->setAnonymousStructOrUnion(true);
4850 
4851   // Add the anonymous struct/union object to the current
4852   // context. We'll be referencing this object when we refer to one of
4853   // its members.
4854   Owner->addDecl(Anon);
4855 
4856   // Inject the members of the anonymous struct/union into the owning
4857   // context and into the identifier resolver chain for name lookup
4858   // purposes.
4859   SmallVector<NamedDecl*, 2> Chain;
4860   Chain.push_back(Anon);
4861 
4862   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4863     Invalid = true;
4864 
4865   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4866     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4867       Decl *ManglingContextDecl;
4868       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4869               NewVD->getDeclContext(), ManglingContextDecl)) {
4870         Context.setManglingNumber(
4871             NewVD, MCtx->getManglingNumber(
4872                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4873         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4874       }
4875     }
4876   }
4877 
4878   if (Invalid)
4879     Anon->setInvalidDecl();
4880 
4881   return Anon;
4882 }
4883 
4884 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4885 /// Microsoft C anonymous structure.
4886 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4887 /// Example:
4888 ///
4889 /// struct A { int a; };
4890 /// struct B { struct A; int b; };
4891 ///
4892 /// void foo() {
4893 ///   B var;
4894 ///   var.a = 3;
4895 /// }
4896 ///
4897 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4898                                            RecordDecl *Record) {
4899   assert(Record && "expected a record!");
4900 
4901   // Mock up a declarator.
4902   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4903   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4904   assert(TInfo && "couldn't build declarator info for anonymous struct");
4905 
4906   auto *ParentDecl = cast<RecordDecl>(CurContext);
4907   QualType RecTy = Context.getTypeDeclType(Record);
4908 
4909   // Create a declaration for this anonymous struct.
4910   NamedDecl *Anon =
4911       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4912                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4913                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4914                         /*InitStyle=*/ICIS_NoInit);
4915   Anon->setImplicit();
4916 
4917   // Add the anonymous struct object to the current context.
4918   CurContext->addDecl(Anon);
4919 
4920   // Inject the members of the anonymous struct into the current
4921   // context and into the identifier resolver chain for name lookup
4922   // purposes.
4923   SmallVector<NamedDecl*, 2> Chain;
4924   Chain.push_back(Anon);
4925 
4926   RecordDecl *RecordDef = Record->getDefinition();
4927   if (RequireCompleteType(Anon->getLocation(), RecTy,
4928                           diag::err_field_incomplete) ||
4929       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4930                                           AS_none, Chain)) {
4931     Anon->setInvalidDecl();
4932     ParentDecl->setInvalidDecl();
4933   }
4934 
4935   return Anon;
4936 }
4937 
4938 /// GetNameForDeclarator - Determine the full declaration name for the
4939 /// given Declarator.
4940 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4941   return GetNameFromUnqualifiedId(D.getName());
4942 }
4943 
4944 /// Retrieves the declaration name from a parsed unqualified-id.
4945 DeclarationNameInfo
4946 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4947   DeclarationNameInfo NameInfo;
4948   NameInfo.setLoc(Name.StartLocation);
4949 
4950   switch (Name.getKind()) {
4951 
4952   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4953   case UnqualifiedIdKind::IK_Identifier:
4954     NameInfo.setName(Name.Identifier);
4955     return NameInfo;
4956 
4957   case UnqualifiedIdKind::IK_DeductionGuideName: {
4958     // C++ [temp.deduct.guide]p3:
4959     //   The simple-template-id shall name a class template specialization.
4960     //   The template-name shall be the same identifier as the template-name
4961     //   of the simple-template-id.
4962     // These together intend to imply that the template-name shall name a
4963     // class template.
4964     // FIXME: template<typename T> struct X {};
4965     //        template<typename T> using Y = X<T>;
4966     //        Y(int) -> Y<int>;
4967     //   satisfies these rules but does not name a class template.
4968     TemplateName TN = Name.TemplateName.get().get();
4969     auto *Template = TN.getAsTemplateDecl();
4970     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4971       Diag(Name.StartLocation,
4972            diag::err_deduction_guide_name_not_class_template)
4973         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4974       if (Template)
4975         Diag(Template->getLocation(), diag::note_template_decl_here);
4976       return DeclarationNameInfo();
4977     }
4978 
4979     NameInfo.setName(
4980         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4981     return NameInfo;
4982   }
4983 
4984   case UnqualifiedIdKind::IK_OperatorFunctionId:
4985     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4986                                            Name.OperatorFunctionId.Operator));
4987     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4988       = Name.OperatorFunctionId.SymbolLocations[0];
4989     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4990       = Name.EndLocation.getRawEncoding();
4991     return NameInfo;
4992 
4993   case UnqualifiedIdKind::IK_LiteralOperatorId:
4994     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4995                                                            Name.Identifier));
4996     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4997     return NameInfo;
4998 
4999   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5000     TypeSourceInfo *TInfo;
5001     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5002     if (Ty.isNull())
5003       return DeclarationNameInfo();
5004     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5005                                                Context.getCanonicalType(Ty)));
5006     NameInfo.setNamedTypeInfo(TInfo);
5007     return NameInfo;
5008   }
5009 
5010   case UnqualifiedIdKind::IK_ConstructorName: {
5011     TypeSourceInfo *TInfo;
5012     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5013     if (Ty.isNull())
5014       return DeclarationNameInfo();
5015     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5016                                               Context.getCanonicalType(Ty)));
5017     NameInfo.setNamedTypeInfo(TInfo);
5018     return NameInfo;
5019   }
5020 
5021   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5022     // In well-formed code, we can only have a constructor
5023     // template-id that refers to the current context, so go there
5024     // to find the actual type being constructed.
5025     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5026     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5027       return DeclarationNameInfo();
5028 
5029     // Determine the type of the class being constructed.
5030     QualType CurClassType = Context.getTypeDeclType(CurClass);
5031 
5032     // FIXME: Check two things: that the template-id names the same type as
5033     // CurClassType, and that the template-id does not occur when the name
5034     // was qualified.
5035 
5036     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5037                                     Context.getCanonicalType(CurClassType)));
5038     // FIXME: should we retrieve TypeSourceInfo?
5039     NameInfo.setNamedTypeInfo(nullptr);
5040     return NameInfo;
5041   }
5042 
5043   case UnqualifiedIdKind::IK_DestructorName: {
5044     TypeSourceInfo *TInfo;
5045     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5046     if (Ty.isNull())
5047       return DeclarationNameInfo();
5048     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5049                                               Context.getCanonicalType(Ty)));
5050     NameInfo.setNamedTypeInfo(TInfo);
5051     return NameInfo;
5052   }
5053 
5054   case UnqualifiedIdKind::IK_TemplateId: {
5055     TemplateName TName = Name.TemplateId->Template.get();
5056     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5057     return Context.getNameForTemplate(TName, TNameLoc);
5058   }
5059 
5060   } // switch (Name.getKind())
5061 
5062   llvm_unreachable("Unknown name kind");
5063 }
5064 
5065 static QualType getCoreType(QualType Ty) {
5066   do {
5067     if (Ty->isPointerType() || Ty->isReferenceType())
5068       Ty = Ty->getPointeeType();
5069     else if (Ty->isArrayType())
5070       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5071     else
5072       return Ty.withoutLocalFastQualifiers();
5073   } while (true);
5074 }
5075 
5076 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5077 /// and Definition have "nearly" matching parameters. This heuristic is
5078 /// used to improve diagnostics in the case where an out-of-line function
5079 /// definition doesn't match any declaration within the class or namespace.
5080 /// Also sets Params to the list of indices to the parameters that differ
5081 /// between the declaration and the definition. If hasSimilarParameters
5082 /// returns true and Params is empty, then all of the parameters match.
5083 static bool hasSimilarParameters(ASTContext &Context,
5084                                      FunctionDecl *Declaration,
5085                                      FunctionDecl *Definition,
5086                                      SmallVectorImpl<unsigned> &Params) {
5087   Params.clear();
5088   if (Declaration->param_size() != Definition->param_size())
5089     return false;
5090   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5091     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5092     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5093 
5094     // The parameter types are identical
5095     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5096       continue;
5097 
5098     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5099     QualType DefParamBaseTy = getCoreType(DefParamTy);
5100     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5101     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5102 
5103     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5104         (DeclTyName && DeclTyName == DefTyName))
5105       Params.push_back(Idx);
5106     else  // The two parameters aren't even close
5107       return false;
5108   }
5109 
5110   return true;
5111 }
5112 
5113 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5114 /// declarator needs to be rebuilt in the current instantiation.
5115 /// Any bits of declarator which appear before the name are valid for
5116 /// consideration here.  That's specifically the type in the decl spec
5117 /// and the base type in any member-pointer chunks.
5118 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5119                                                     DeclarationName Name) {
5120   // The types we specifically need to rebuild are:
5121   //   - typenames, typeofs, and decltypes
5122   //   - types which will become injected class names
5123   // Of course, we also need to rebuild any type referencing such a
5124   // type.  It's safest to just say "dependent", but we call out a
5125   // few cases here.
5126 
5127   DeclSpec &DS = D.getMutableDeclSpec();
5128   switch (DS.getTypeSpecType()) {
5129   case DeclSpec::TST_typename:
5130   case DeclSpec::TST_typeofType:
5131   case DeclSpec::TST_underlyingType:
5132   case DeclSpec::TST_atomic: {
5133     // Grab the type from the parser.
5134     TypeSourceInfo *TSI = nullptr;
5135     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5136     if (T.isNull() || !T->isDependentType()) break;
5137 
5138     // Make sure there's a type source info.  This isn't really much
5139     // of a waste; most dependent types should have type source info
5140     // attached already.
5141     if (!TSI)
5142       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5143 
5144     // Rebuild the type in the current instantiation.
5145     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5146     if (!TSI) return true;
5147 
5148     // Store the new type back in the decl spec.
5149     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5150     DS.UpdateTypeRep(LocType);
5151     break;
5152   }
5153 
5154   case DeclSpec::TST_decltype:
5155   case DeclSpec::TST_typeofExpr: {
5156     Expr *E = DS.getRepAsExpr();
5157     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5158     if (Result.isInvalid()) return true;
5159     DS.UpdateExprRep(Result.get());
5160     break;
5161   }
5162 
5163   default:
5164     // Nothing to do for these decl specs.
5165     break;
5166   }
5167 
5168   // It doesn't matter what order we do this in.
5169   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5170     DeclaratorChunk &Chunk = D.getTypeObject(I);
5171 
5172     // The only type information in the declarator which can come
5173     // before the declaration name is the base type of a member
5174     // pointer.
5175     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5176       continue;
5177 
5178     // Rebuild the scope specifier in-place.
5179     CXXScopeSpec &SS = Chunk.Mem.Scope();
5180     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5181       return true;
5182   }
5183 
5184   return false;
5185 }
5186 
5187 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5188   D.setFunctionDefinitionKind(FDK_Declaration);
5189   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5190 
5191   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5192       Dcl && Dcl->getDeclContext()->isFileContext())
5193     Dcl->setTopLevelDeclInObjCContainer();
5194 
5195   if (getLangOpts().OpenCL)
5196     setCurrentOpenCLExtensionForDecl(Dcl);
5197 
5198   return Dcl;
5199 }
5200 
5201 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5202 ///   If T is the name of a class, then each of the following shall have a
5203 ///   name different from T:
5204 ///     - every static data member of class T;
5205 ///     - every member function of class T
5206 ///     - every member of class T that is itself a type;
5207 /// \returns true if the declaration name violates these rules.
5208 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5209                                    DeclarationNameInfo NameInfo) {
5210   DeclarationName Name = NameInfo.getName();
5211 
5212   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5213   while (Record && Record->isAnonymousStructOrUnion())
5214     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5215   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5216     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5217     return true;
5218   }
5219 
5220   return false;
5221 }
5222 
5223 /// Diagnose a declaration whose declarator-id has the given
5224 /// nested-name-specifier.
5225 ///
5226 /// \param SS The nested-name-specifier of the declarator-id.
5227 ///
5228 /// \param DC The declaration context to which the nested-name-specifier
5229 /// resolves.
5230 ///
5231 /// \param Name The name of the entity being declared.
5232 ///
5233 /// \param Loc The location of the name of the entity being declared.
5234 ///
5235 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5236 /// we're declaring an explicit / partial specialization / instantiation.
5237 ///
5238 /// \returns true if we cannot safely recover from this error, false otherwise.
5239 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5240                                         DeclarationName Name,
5241                                         SourceLocation Loc, bool IsTemplateId) {
5242   DeclContext *Cur = CurContext;
5243   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5244     Cur = Cur->getParent();
5245 
5246   // If the user provided a superfluous scope specifier that refers back to the
5247   // class in which the entity is already declared, diagnose and ignore it.
5248   //
5249   // class X {
5250   //   void X::f();
5251   // };
5252   //
5253   // Note, it was once ill-formed to give redundant qualification in all
5254   // contexts, but that rule was removed by DR482.
5255   if (Cur->Equals(DC)) {
5256     if (Cur->isRecord()) {
5257       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5258                                       : diag::err_member_extra_qualification)
5259         << Name << FixItHint::CreateRemoval(SS.getRange());
5260       SS.clear();
5261     } else {
5262       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5263     }
5264     return false;
5265   }
5266 
5267   // Check whether the qualifying scope encloses the scope of the original
5268   // declaration. For a template-id, we perform the checks in
5269   // CheckTemplateSpecializationScope.
5270   if (!Cur->Encloses(DC) && !IsTemplateId) {
5271     if (Cur->isRecord())
5272       Diag(Loc, diag::err_member_qualification)
5273         << Name << SS.getRange();
5274     else if (isa<TranslationUnitDecl>(DC))
5275       Diag(Loc, diag::err_invalid_declarator_global_scope)
5276         << Name << SS.getRange();
5277     else if (isa<FunctionDecl>(Cur))
5278       Diag(Loc, diag::err_invalid_declarator_in_function)
5279         << Name << SS.getRange();
5280     else if (isa<BlockDecl>(Cur))
5281       Diag(Loc, diag::err_invalid_declarator_in_block)
5282         << Name << SS.getRange();
5283     else
5284       Diag(Loc, diag::err_invalid_declarator_scope)
5285       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5286 
5287     return true;
5288   }
5289 
5290   if (Cur->isRecord()) {
5291     // Cannot qualify members within a class.
5292     Diag(Loc, diag::err_member_qualification)
5293       << Name << SS.getRange();
5294     SS.clear();
5295 
5296     // C++ constructors and destructors with incorrect scopes can break
5297     // our AST invariants by having the wrong underlying types. If
5298     // that's the case, then drop this declaration entirely.
5299     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5300          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5301         !Context.hasSameType(Name.getCXXNameType(),
5302                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5303       return true;
5304 
5305     return false;
5306   }
5307 
5308   // C++11 [dcl.meaning]p1:
5309   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5310   //   not begin with a decltype-specifer"
5311   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5312   while (SpecLoc.getPrefix())
5313     SpecLoc = SpecLoc.getPrefix();
5314   if (dyn_cast_or_null<DecltypeType>(
5315         SpecLoc.getNestedNameSpecifier()->getAsType()))
5316     Diag(Loc, diag::err_decltype_in_declarator)
5317       << SpecLoc.getTypeLoc().getSourceRange();
5318 
5319   return false;
5320 }
5321 
5322 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5323                                   MultiTemplateParamsArg TemplateParamLists) {
5324   // TODO: consider using NameInfo for diagnostic.
5325   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5326   DeclarationName Name = NameInfo.getName();
5327 
5328   // All of these full declarators require an identifier.  If it doesn't have
5329   // one, the ParsedFreeStandingDeclSpec action should be used.
5330   if (D.isDecompositionDeclarator()) {
5331     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5332   } else if (!Name) {
5333     if (!D.isInvalidType())  // Reject this if we think it is valid.
5334       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5335           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5336     return nullptr;
5337   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5338     return nullptr;
5339 
5340   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5341   // we find one that is.
5342   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5343          (S->getFlags() & Scope::TemplateParamScope) != 0)
5344     S = S->getParent();
5345 
5346   DeclContext *DC = CurContext;
5347   if (D.getCXXScopeSpec().isInvalid())
5348     D.setInvalidType();
5349   else if (D.getCXXScopeSpec().isSet()) {
5350     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5351                                         UPPC_DeclarationQualifier))
5352       return nullptr;
5353 
5354     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5355     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5356     if (!DC || isa<EnumDecl>(DC)) {
5357       // If we could not compute the declaration context, it's because the
5358       // declaration context is dependent but does not refer to a class,
5359       // class template, or class template partial specialization. Complain
5360       // and return early, to avoid the coming semantic disaster.
5361       Diag(D.getIdentifierLoc(),
5362            diag::err_template_qualified_declarator_no_match)
5363         << D.getCXXScopeSpec().getScopeRep()
5364         << D.getCXXScopeSpec().getRange();
5365       return nullptr;
5366     }
5367     bool IsDependentContext = DC->isDependentContext();
5368 
5369     if (!IsDependentContext &&
5370         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5371       return nullptr;
5372 
5373     // If a class is incomplete, do not parse entities inside it.
5374     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5375       Diag(D.getIdentifierLoc(),
5376            diag::err_member_def_undefined_record)
5377         << Name << DC << D.getCXXScopeSpec().getRange();
5378       return nullptr;
5379     }
5380     if (!D.getDeclSpec().isFriendSpecified()) {
5381       if (diagnoseQualifiedDeclaration(
5382               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5383               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5384         if (DC->isRecord())
5385           return nullptr;
5386 
5387         D.setInvalidType();
5388       }
5389     }
5390 
5391     // Check whether we need to rebuild the type of the given
5392     // declaration in the current instantiation.
5393     if (EnteringContext && IsDependentContext &&
5394         TemplateParamLists.size() != 0) {
5395       ContextRAII SavedContext(*this, DC);
5396       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5397         D.setInvalidType();
5398     }
5399   }
5400 
5401   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5402   QualType R = TInfo->getType();
5403 
5404   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5405                                       UPPC_DeclarationType))
5406     D.setInvalidType();
5407 
5408   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5409                         forRedeclarationInCurContext());
5410 
5411   // See if this is a redefinition of a variable in the same scope.
5412   if (!D.getCXXScopeSpec().isSet()) {
5413     bool IsLinkageLookup = false;
5414     bool CreateBuiltins = false;
5415 
5416     // If the declaration we're planning to build will be a function
5417     // or object with linkage, then look for another declaration with
5418     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5419     //
5420     // If the declaration we're planning to build will be declared with
5421     // external linkage in the translation unit, create any builtin with
5422     // the same name.
5423     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5424       /* Do nothing*/;
5425     else if (CurContext->isFunctionOrMethod() &&
5426              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5427               R->isFunctionType())) {
5428       IsLinkageLookup = true;
5429       CreateBuiltins =
5430           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5431     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5432                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5433       CreateBuiltins = true;
5434 
5435     if (IsLinkageLookup) {
5436       Previous.clear(LookupRedeclarationWithLinkage);
5437       Previous.setRedeclarationKind(ForExternalRedeclaration);
5438     }
5439 
5440     LookupName(Previous, S, CreateBuiltins);
5441   } else { // Something like "int foo::x;"
5442     LookupQualifiedName(Previous, DC);
5443 
5444     // C++ [dcl.meaning]p1:
5445     //   When the declarator-id is qualified, the declaration shall refer to a
5446     //  previously declared member of the class or namespace to which the
5447     //  qualifier refers (or, in the case of a namespace, of an element of the
5448     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5449     //  thereof; [...]
5450     //
5451     // Note that we already checked the context above, and that we do not have
5452     // enough information to make sure that Previous contains the declaration
5453     // we want to match. For example, given:
5454     //
5455     //   class X {
5456     //     void f();
5457     //     void f(float);
5458     //   };
5459     //
5460     //   void X::f(int) { } // ill-formed
5461     //
5462     // In this case, Previous will point to the overload set
5463     // containing the two f's declared in X, but neither of them
5464     // matches.
5465 
5466     // C++ [dcl.meaning]p1:
5467     //   [...] the member shall not merely have been introduced by a
5468     //   using-declaration in the scope of the class or namespace nominated by
5469     //   the nested-name-specifier of the declarator-id.
5470     RemoveUsingDecls(Previous);
5471   }
5472 
5473   if (Previous.isSingleResult() &&
5474       Previous.getFoundDecl()->isTemplateParameter()) {
5475     // Maybe we will complain about the shadowed template parameter.
5476     if (!D.isInvalidType())
5477       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5478                                       Previous.getFoundDecl());
5479 
5480     // Just pretend that we didn't see the previous declaration.
5481     Previous.clear();
5482   }
5483 
5484   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5485     // Forget that the previous declaration is the injected-class-name.
5486     Previous.clear();
5487 
5488   // In C++, the previous declaration we find might be a tag type
5489   // (class or enum). In this case, the new declaration will hide the
5490   // tag type. Note that this applies to functions, function templates, and
5491   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5492   if (Previous.isSingleTagDecl() &&
5493       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5494       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5495     Previous.clear();
5496 
5497   // Check that there are no default arguments other than in the parameters
5498   // of a function declaration (C++ only).
5499   if (getLangOpts().CPlusPlus)
5500     CheckExtraCXXDefaultArguments(D);
5501 
5502   NamedDecl *New;
5503 
5504   bool AddToScope = true;
5505   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5506     if (TemplateParamLists.size()) {
5507       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5508       return nullptr;
5509     }
5510 
5511     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5512   } else if (R->isFunctionType()) {
5513     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5514                                   TemplateParamLists,
5515                                   AddToScope);
5516   } else {
5517     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5518                                   AddToScope);
5519   }
5520 
5521   if (!New)
5522     return nullptr;
5523 
5524   // If this has an identifier and is not a function template specialization,
5525   // add it to the scope stack.
5526   if (New->getDeclName() && AddToScope)
5527     PushOnScopeChains(New, S);
5528 
5529   if (isInOpenMPDeclareTargetContext())
5530     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5531 
5532   return New;
5533 }
5534 
5535 /// Helper method to turn variable array types into constant array
5536 /// types in certain situations which would otherwise be errors (for
5537 /// GCC compatibility).
5538 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5539                                                     ASTContext &Context,
5540                                                     bool &SizeIsNegative,
5541                                                     llvm::APSInt &Oversized) {
5542   // This method tries to turn a variable array into a constant
5543   // array even when the size isn't an ICE.  This is necessary
5544   // for compatibility with code that depends on gcc's buggy
5545   // constant expression folding, like struct {char x[(int)(char*)2];}
5546   SizeIsNegative = false;
5547   Oversized = 0;
5548 
5549   if (T->isDependentType())
5550     return QualType();
5551 
5552   QualifierCollector Qs;
5553   const Type *Ty = Qs.strip(T);
5554 
5555   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5556     QualType Pointee = PTy->getPointeeType();
5557     QualType FixedType =
5558         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5559                                             Oversized);
5560     if (FixedType.isNull()) return FixedType;
5561     FixedType = Context.getPointerType(FixedType);
5562     return Qs.apply(Context, FixedType);
5563   }
5564   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5565     QualType Inner = PTy->getInnerType();
5566     QualType FixedType =
5567         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5568                                             Oversized);
5569     if (FixedType.isNull()) return FixedType;
5570     FixedType = Context.getParenType(FixedType);
5571     return Qs.apply(Context, FixedType);
5572   }
5573 
5574   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5575   if (!VLATy)
5576     return QualType();
5577   // FIXME: We should probably handle this case
5578   if (VLATy->getElementType()->isVariablyModifiedType())
5579     return QualType();
5580 
5581   Expr::EvalResult Result;
5582   if (!VLATy->getSizeExpr() ||
5583       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5584     return QualType();
5585 
5586   llvm::APSInt Res = Result.Val.getInt();
5587 
5588   // Check whether the array size is negative.
5589   if (Res.isSigned() && Res.isNegative()) {
5590     SizeIsNegative = true;
5591     return QualType();
5592   }
5593 
5594   // Check whether the array is too large to be addressed.
5595   unsigned ActiveSizeBits
5596     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5597                                               Res);
5598   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5599     Oversized = Res;
5600     return QualType();
5601   }
5602 
5603   return Context.getConstantArrayType(VLATy->getElementType(),
5604                                       Res, ArrayType::Normal, 0);
5605 }
5606 
5607 static void
5608 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5609   SrcTL = SrcTL.getUnqualifiedLoc();
5610   DstTL = DstTL.getUnqualifiedLoc();
5611   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5612     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5613     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5614                                       DstPTL.getPointeeLoc());
5615     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5616     return;
5617   }
5618   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5619     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5620     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5621                                       DstPTL.getInnerLoc());
5622     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5623     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5624     return;
5625   }
5626   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5627   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5628   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5629   TypeLoc DstElemTL = DstATL.getElementLoc();
5630   DstElemTL.initializeFullCopy(SrcElemTL);
5631   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5632   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5633   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5634 }
5635 
5636 /// Helper method to turn variable array types into constant array
5637 /// types in certain situations which would otherwise be errors (for
5638 /// GCC compatibility).
5639 static TypeSourceInfo*
5640 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5641                                               ASTContext &Context,
5642                                               bool &SizeIsNegative,
5643                                               llvm::APSInt &Oversized) {
5644   QualType FixedTy
5645     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5646                                           SizeIsNegative, Oversized);
5647   if (FixedTy.isNull())
5648     return nullptr;
5649   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5650   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5651                                     FixedTInfo->getTypeLoc());
5652   return FixedTInfo;
5653 }
5654 
5655 /// Register the given locally-scoped extern "C" declaration so
5656 /// that it can be found later for redeclarations. We include any extern "C"
5657 /// declaration that is not visible in the translation unit here, not just
5658 /// function-scope declarations.
5659 void
5660 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5661   if (!getLangOpts().CPlusPlus &&
5662       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5663     // Don't need to track declarations in the TU in C.
5664     return;
5665 
5666   // Note that we have a locally-scoped external with this name.
5667   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5668 }
5669 
5670 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5671   // FIXME: We can have multiple results via __attribute__((overloadable)).
5672   auto Result = Context.getExternCContextDecl()->lookup(Name);
5673   return Result.empty() ? nullptr : *Result.begin();
5674 }
5675 
5676 /// Diagnose function specifiers on a declaration of an identifier that
5677 /// does not identify a function.
5678 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5679   // FIXME: We should probably indicate the identifier in question to avoid
5680   // confusion for constructs like "virtual int a(), b;"
5681   if (DS.isVirtualSpecified())
5682     Diag(DS.getVirtualSpecLoc(),
5683          diag::err_virtual_non_function);
5684 
5685   if (DS.isExplicitSpecified())
5686     Diag(DS.getExplicitSpecLoc(),
5687          diag::err_explicit_non_function);
5688 
5689   if (DS.isNoreturnSpecified())
5690     Diag(DS.getNoreturnSpecLoc(),
5691          diag::err_noreturn_non_function);
5692 }
5693 
5694 NamedDecl*
5695 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5696                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5697   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5698   if (D.getCXXScopeSpec().isSet()) {
5699     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5700       << D.getCXXScopeSpec().getRange();
5701     D.setInvalidType();
5702     // Pretend we didn't see the scope specifier.
5703     DC = CurContext;
5704     Previous.clear();
5705   }
5706 
5707   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5708 
5709   if (D.getDeclSpec().isInlineSpecified())
5710     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5711         << getLangOpts().CPlusPlus17;
5712   if (D.getDeclSpec().isConstexprSpecified())
5713     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5714       << 1;
5715 
5716   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5717     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5718       Diag(D.getName().StartLocation,
5719            diag::err_deduction_guide_invalid_specifier)
5720           << "typedef";
5721     else
5722       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5723           << D.getName().getSourceRange();
5724     return nullptr;
5725   }
5726 
5727   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5728   if (!NewTD) return nullptr;
5729 
5730   // Handle attributes prior to checking for duplicates in MergeVarDecl
5731   ProcessDeclAttributes(S, NewTD, D);
5732 
5733   CheckTypedefForVariablyModifiedType(S, NewTD);
5734 
5735   bool Redeclaration = D.isRedeclaration();
5736   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5737   D.setRedeclaration(Redeclaration);
5738   return ND;
5739 }
5740 
5741 void
5742 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5743   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5744   // then it shall have block scope.
5745   // Note that variably modified types must be fixed before merging the decl so
5746   // that redeclarations will match.
5747   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5748   QualType T = TInfo->getType();
5749   if (T->isVariablyModifiedType()) {
5750     setFunctionHasBranchProtectedScope();
5751 
5752     if (S->getFnParent() == nullptr) {
5753       bool SizeIsNegative;
5754       llvm::APSInt Oversized;
5755       TypeSourceInfo *FixedTInfo =
5756         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5757                                                       SizeIsNegative,
5758                                                       Oversized);
5759       if (FixedTInfo) {
5760         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5761         NewTD->setTypeSourceInfo(FixedTInfo);
5762       } else {
5763         if (SizeIsNegative)
5764           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5765         else if (T->isVariableArrayType())
5766           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5767         else if (Oversized.getBoolValue())
5768           Diag(NewTD->getLocation(), diag::err_array_too_large)
5769             << Oversized.toString(10);
5770         else
5771           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5772         NewTD->setInvalidDecl();
5773       }
5774     }
5775   }
5776 }
5777 
5778 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5779 /// declares a typedef-name, either using the 'typedef' type specifier or via
5780 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5781 NamedDecl*
5782 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5783                            LookupResult &Previous, bool &Redeclaration) {
5784 
5785   // Find the shadowed declaration before filtering for scope.
5786   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5787 
5788   // Merge the decl with the existing one if appropriate. If the decl is
5789   // in an outer scope, it isn't the same thing.
5790   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5791                        /*AllowInlineNamespace*/false);
5792   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5793   if (!Previous.empty()) {
5794     Redeclaration = true;
5795     MergeTypedefNameDecl(S, NewTD, Previous);
5796   }
5797 
5798   if (ShadowedDecl && !Redeclaration)
5799     CheckShadow(NewTD, ShadowedDecl, Previous);
5800 
5801   // If this is the C FILE type, notify the AST context.
5802   if (IdentifierInfo *II = NewTD->getIdentifier())
5803     if (!NewTD->isInvalidDecl() &&
5804         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5805       if (II->isStr("FILE"))
5806         Context.setFILEDecl(NewTD);
5807       else if (II->isStr("jmp_buf"))
5808         Context.setjmp_bufDecl(NewTD);
5809       else if (II->isStr("sigjmp_buf"))
5810         Context.setsigjmp_bufDecl(NewTD);
5811       else if (II->isStr("ucontext_t"))
5812         Context.setucontext_tDecl(NewTD);
5813     }
5814 
5815   return NewTD;
5816 }
5817 
5818 /// Determines whether the given declaration is an out-of-scope
5819 /// previous declaration.
5820 ///
5821 /// This routine should be invoked when name lookup has found a
5822 /// previous declaration (PrevDecl) that is not in the scope where a
5823 /// new declaration by the same name is being introduced. If the new
5824 /// declaration occurs in a local scope, previous declarations with
5825 /// linkage may still be considered previous declarations (C99
5826 /// 6.2.2p4-5, C++ [basic.link]p6).
5827 ///
5828 /// \param PrevDecl the previous declaration found by name
5829 /// lookup
5830 ///
5831 /// \param DC the context in which the new declaration is being
5832 /// declared.
5833 ///
5834 /// \returns true if PrevDecl is an out-of-scope previous declaration
5835 /// for a new delcaration with the same name.
5836 static bool
5837 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5838                                 ASTContext &Context) {
5839   if (!PrevDecl)
5840     return false;
5841 
5842   if (!PrevDecl->hasLinkage())
5843     return false;
5844 
5845   if (Context.getLangOpts().CPlusPlus) {
5846     // C++ [basic.link]p6:
5847     //   If there is a visible declaration of an entity with linkage
5848     //   having the same name and type, ignoring entities declared
5849     //   outside the innermost enclosing namespace scope, the block
5850     //   scope declaration declares that same entity and receives the
5851     //   linkage of the previous declaration.
5852     DeclContext *OuterContext = DC->getRedeclContext();
5853     if (!OuterContext->isFunctionOrMethod())
5854       // This rule only applies to block-scope declarations.
5855       return false;
5856 
5857     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5858     if (PrevOuterContext->isRecord())
5859       // We found a member function: ignore it.
5860       return false;
5861 
5862     // Find the innermost enclosing namespace for the new and
5863     // previous declarations.
5864     OuterContext = OuterContext->getEnclosingNamespaceContext();
5865     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5866 
5867     // The previous declaration is in a different namespace, so it
5868     // isn't the same function.
5869     if (!OuterContext->Equals(PrevOuterContext))
5870       return false;
5871   }
5872 
5873   return true;
5874 }
5875 
5876 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5877   CXXScopeSpec &SS = D.getCXXScopeSpec();
5878   if (!SS.isSet()) return;
5879   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5880 }
5881 
5882 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5883   QualType type = decl->getType();
5884   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5885   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5886     // Various kinds of declaration aren't allowed to be __autoreleasing.
5887     unsigned kind = -1U;
5888     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5889       if (var->hasAttr<BlocksAttr>())
5890         kind = 0; // __block
5891       else if (!var->hasLocalStorage())
5892         kind = 1; // global
5893     } else if (isa<ObjCIvarDecl>(decl)) {
5894       kind = 3; // ivar
5895     } else if (isa<FieldDecl>(decl)) {
5896       kind = 2; // field
5897     }
5898 
5899     if (kind != -1U) {
5900       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5901         << kind;
5902     }
5903   } else if (lifetime == Qualifiers::OCL_None) {
5904     // Try to infer lifetime.
5905     if (!type->isObjCLifetimeType())
5906       return false;
5907 
5908     lifetime = type->getObjCARCImplicitLifetime();
5909     type = Context.getLifetimeQualifiedType(type, lifetime);
5910     decl->setType(type);
5911   }
5912 
5913   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5914     // Thread-local variables cannot have lifetime.
5915     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5916         var->getTLSKind()) {
5917       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5918         << var->getType();
5919       return true;
5920     }
5921   }
5922 
5923   return false;
5924 }
5925 
5926 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5927   // Ensure that an auto decl is deduced otherwise the checks below might cache
5928   // the wrong linkage.
5929   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5930 
5931   // 'weak' only applies to declarations with external linkage.
5932   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5933     if (!ND.isExternallyVisible()) {
5934       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5935       ND.dropAttr<WeakAttr>();
5936     }
5937   }
5938   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5939     if (ND.isExternallyVisible()) {
5940       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5941       ND.dropAttr<WeakRefAttr>();
5942       ND.dropAttr<AliasAttr>();
5943     }
5944   }
5945 
5946   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5947     if (VD->hasInit()) {
5948       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5949         assert(VD->isThisDeclarationADefinition() &&
5950                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5951         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5952         VD->dropAttr<AliasAttr>();
5953       }
5954     }
5955   }
5956 
5957   // 'selectany' only applies to externally visible variable declarations.
5958   // It does not apply to functions.
5959   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5960     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5961       S.Diag(Attr->getLocation(),
5962              diag::err_attribute_selectany_non_extern_data);
5963       ND.dropAttr<SelectAnyAttr>();
5964     }
5965   }
5966 
5967   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5968     auto *VD = dyn_cast<VarDecl>(&ND);
5969     bool IsAnonymousNS = false;
5970     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5971     if (VD) {
5972       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
5973       while (NS && !IsAnonymousNS) {
5974         IsAnonymousNS = NS->isAnonymousNamespace();
5975         NS = dyn_cast<NamespaceDecl>(NS->getParent());
5976       }
5977     }
5978     // dll attributes require external linkage. Static locals may have external
5979     // linkage but still cannot be explicitly imported or exported.
5980     // In Microsoft mode, a variable defined in anonymous namespace must have
5981     // external linkage in order to be exported.
5982     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
5983     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
5984         (!AnonNSInMicrosoftMode &&
5985          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
5986       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5987         << &ND << Attr;
5988       ND.setInvalidDecl();
5989     }
5990   }
5991 
5992   // Virtual functions cannot be marked as 'notail'.
5993   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5994     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5995       if (MD->isVirtual()) {
5996         S.Diag(ND.getLocation(),
5997                diag::err_invalid_attribute_on_virtual_function)
5998             << Attr;
5999         ND.dropAttr<NotTailCalledAttr>();
6000       }
6001 
6002   // Check the attributes on the function type, if any.
6003   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6004     // Don't declare this variable in the second operand of the for-statement;
6005     // GCC miscompiles that by ending its lifetime before evaluating the
6006     // third operand. See gcc.gnu.org/PR86769.
6007     AttributedTypeLoc ATL;
6008     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6009          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6010          TL = ATL.getModifiedLoc()) {
6011       // The [[lifetimebound]] attribute can be applied to the implicit object
6012       // parameter of a non-static member function (other than a ctor or dtor)
6013       // by applying it to the function type.
6014       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6015         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6016         if (!MD || MD->isStatic()) {
6017           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6018               << !MD << A->getRange();
6019         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6020           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6021               << isa<CXXDestructorDecl>(MD) << A->getRange();
6022         }
6023       }
6024     }
6025   }
6026 }
6027 
6028 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6029                                            NamedDecl *NewDecl,
6030                                            bool IsSpecialization,
6031                                            bool IsDefinition) {
6032   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6033     return;
6034 
6035   bool IsTemplate = false;
6036   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6037     OldDecl = OldTD->getTemplatedDecl();
6038     IsTemplate = true;
6039     if (!IsSpecialization)
6040       IsDefinition = false;
6041   }
6042   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6043     NewDecl = NewTD->getTemplatedDecl();
6044     IsTemplate = true;
6045   }
6046 
6047   if (!OldDecl || !NewDecl)
6048     return;
6049 
6050   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6051   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6052   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6053   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6054 
6055   // dllimport and dllexport are inheritable attributes so we have to exclude
6056   // inherited attribute instances.
6057   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6058                     (NewExportAttr && !NewExportAttr->isInherited());
6059 
6060   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6061   // the only exception being explicit specializations.
6062   // Implicitly generated declarations are also excluded for now because there
6063   // is no other way to switch these to use dllimport or dllexport.
6064   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6065 
6066   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6067     // Allow with a warning for free functions and global variables.
6068     bool JustWarn = false;
6069     if (!OldDecl->isCXXClassMember()) {
6070       auto *VD = dyn_cast<VarDecl>(OldDecl);
6071       if (VD && !VD->getDescribedVarTemplate())
6072         JustWarn = true;
6073       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6074       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6075         JustWarn = true;
6076     }
6077 
6078     // We cannot change a declaration that's been used because IR has already
6079     // been emitted. Dllimported functions will still work though (modulo
6080     // address equality) as they can use the thunk.
6081     if (OldDecl->isUsed())
6082       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6083         JustWarn = false;
6084 
6085     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6086                                : diag::err_attribute_dll_redeclaration;
6087     S.Diag(NewDecl->getLocation(), DiagID)
6088         << NewDecl
6089         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6090     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6091     if (!JustWarn) {
6092       NewDecl->setInvalidDecl();
6093       return;
6094     }
6095   }
6096 
6097   // A redeclaration is not allowed to drop a dllimport attribute, the only
6098   // exceptions being inline function definitions (except for function
6099   // templates), local extern declarations, qualified friend declarations or
6100   // special MSVC extension: in the last case, the declaration is treated as if
6101   // it were marked dllexport.
6102   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6103   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6104   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6105     // Ignore static data because out-of-line definitions are diagnosed
6106     // separately.
6107     IsStaticDataMember = VD->isStaticDataMember();
6108     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6109                    VarDecl::DeclarationOnly;
6110   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6111     IsInline = FD->isInlined();
6112     IsQualifiedFriend = FD->getQualifier() &&
6113                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6114   }
6115 
6116   if (OldImportAttr && !HasNewAttr &&
6117       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6118       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6119     if (IsMicrosoft && IsDefinition) {
6120       S.Diag(NewDecl->getLocation(),
6121              diag::warn_redeclaration_without_import_attribute)
6122           << NewDecl;
6123       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6124       NewDecl->dropAttr<DLLImportAttr>();
6125       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6126           NewImportAttr->getRange(), S.Context,
6127           NewImportAttr->getSpellingListIndex()));
6128     } else {
6129       S.Diag(NewDecl->getLocation(),
6130              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6131           << NewDecl << OldImportAttr;
6132       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6133       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6134       OldDecl->dropAttr<DLLImportAttr>();
6135       NewDecl->dropAttr<DLLImportAttr>();
6136     }
6137   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6138     // In MinGW, seeing a function declared inline drops the dllimport
6139     // attribute.
6140     OldDecl->dropAttr<DLLImportAttr>();
6141     NewDecl->dropAttr<DLLImportAttr>();
6142     S.Diag(NewDecl->getLocation(),
6143            diag::warn_dllimport_dropped_from_inline_function)
6144         << NewDecl << OldImportAttr;
6145   }
6146 
6147   // A specialization of a class template member function is processed here
6148   // since it's a redeclaration. If the parent class is dllexport, the
6149   // specialization inherits that attribute. This doesn't happen automatically
6150   // since the parent class isn't instantiated until later.
6151   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6152     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6153         !NewImportAttr && !NewExportAttr) {
6154       if (const DLLExportAttr *ParentExportAttr =
6155               MD->getParent()->getAttr<DLLExportAttr>()) {
6156         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6157         NewAttr->setInherited(true);
6158         NewDecl->addAttr(NewAttr);
6159       }
6160     }
6161   }
6162 }
6163 
6164 /// Given that we are within the definition of the given function,
6165 /// will that definition behave like C99's 'inline', where the
6166 /// definition is discarded except for optimization purposes?
6167 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6168   // Try to avoid calling GetGVALinkageForFunction.
6169 
6170   // All cases of this require the 'inline' keyword.
6171   if (!FD->isInlined()) return false;
6172 
6173   // This is only possible in C++ with the gnu_inline attribute.
6174   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6175     return false;
6176 
6177   // Okay, go ahead and call the relatively-more-expensive function.
6178   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6179 }
6180 
6181 /// Determine whether a variable is extern "C" prior to attaching
6182 /// an initializer. We can't just call isExternC() here, because that
6183 /// will also compute and cache whether the declaration is externally
6184 /// visible, which might change when we attach the initializer.
6185 ///
6186 /// This can only be used if the declaration is known to not be a
6187 /// redeclaration of an internal linkage declaration.
6188 ///
6189 /// For instance:
6190 ///
6191 ///   auto x = []{};
6192 ///
6193 /// Attaching the initializer here makes this declaration not externally
6194 /// visible, because its type has internal linkage.
6195 ///
6196 /// FIXME: This is a hack.
6197 template<typename T>
6198 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6199   if (S.getLangOpts().CPlusPlus) {
6200     // In C++, the overloadable attribute negates the effects of extern "C".
6201     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6202       return false;
6203 
6204     // So do CUDA's host/device attributes.
6205     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6206                                  D->template hasAttr<CUDAHostAttr>()))
6207       return false;
6208   }
6209   return D->isExternC();
6210 }
6211 
6212 static bool shouldConsiderLinkage(const VarDecl *VD) {
6213   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6214   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6215       isa<OMPDeclareMapperDecl>(DC))
6216     return VD->hasExternalStorage();
6217   if (DC->isFileContext())
6218     return true;
6219   if (DC->isRecord())
6220     return false;
6221   llvm_unreachable("Unexpected context");
6222 }
6223 
6224 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6225   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6226   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6227       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6228     return true;
6229   if (DC->isRecord())
6230     return false;
6231   llvm_unreachable("Unexpected context");
6232 }
6233 
6234 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6235                           ParsedAttr::Kind Kind) {
6236   // Check decl attributes on the DeclSpec.
6237   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6238     return true;
6239 
6240   // Walk the declarator structure, checking decl attributes that were in a type
6241   // position to the decl itself.
6242   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6243     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6244       return true;
6245   }
6246 
6247   // Finally, check attributes on the decl itself.
6248   return PD.getAttributes().hasAttribute(Kind);
6249 }
6250 
6251 /// Adjust the \c DeclContext for a function or variable that might be a
6252 /// function-local external declaration.
6253 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6254   if (!DC->isFunctionOrMethod())
6255     return false;
6256 
6257   // If this is a local extern function or variable declared within a function
6258   // template, don't add it into the enclosing namespace scope until it is
6259   // instantiated; it might have a dependent type right now.
6260   if (DC->isDependentContext())
6261     return true;
6262 
6263   // C++11 [basic.link]p7:
6264   //   When a block scope declaration of an entity with linkage is not found to
6265   //   refer to some other declaration, then that entity is a member of the
6266   //   innermost enclosing namespace.
6267   //
6268   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6269   // semantically-enclosing namespace, not a lexically-enclosing one.
6270   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6271     DC = DC->getParent();
6272   return true;
6273 }
6274 
6275 /// Returns true if given declaration has external C language linkage.
6276 static bool isDeclExternC(const Decl *D) {
6277   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6278     return FD->isExternC();
6279   if (const auto *VD = dyn_cast<VarDecl>(D))
6280     return VD->isExternC();
6281 
6282   llvm_unreachable("Unknown type of decl!");
6283 }
6284 
6285 NamedDecl *Sema::ActOnVariableDeclarator(
6286     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6287     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6288     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6289   QualType R = TInfo->getType();
6290   DeclarationName Name = GetNameForDeclarator(D).getName();
6291 
6292   IdentifierInfo *II = Name.getAsIdentifierInfo();
6293 
6294   if (D.isDecompositionDeclarator()) {
6295     // Take the name of the first declarator as our name for diagnostic
6296     // purposes.
6297     auto &Decomp = D.getDecompositionDeclarator();
6298     if (!Decomp.bindings().empty()) {
6299       II = Decomp.bindings()[0].Name;
6300       Name = II;
6301     }
6302   } else if (!II) {
6303     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6304     return nullptr;
6305   }
6306 
6307   if (getLangOpts().OpenCL) {
6308     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6309     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6310     // argument.
6311     if (R->isImageType() || R->isPipeType()) {
6312       Diag(D.getIdentifierLoc(),
6313            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6314           << R;
6315       D.setInvalidType();
6316       return nullptr;
6317     }
6318 
6319     // OpenCL v1.2 s6.9.r:
6320     // The event type cannot be used to declare a program scope variable.
6321     // OpenCL v2.0 s6.9.q:
6322     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6323     if (NULL == S->getParent()) {
6324       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6325         Diag(D.getIdentifierLoc(),
6326              diag::err_invalid_type_for_program_scope_var) << R;
6327         D.setInvalidType();
6328         return nullptr;
6329       }
6330     }
6331 
6332     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6333     QualType NR = R;
6334     while (NR->isPointerType()) {
6335       if (NR->isFunctionPointerType()) {
6336         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6337         D.setInvalidType();
6338         break;
6339       }
6340       NR = NR->getPointeeType();
6341     }
6342 
6343     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6344       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6345       // half array type (unless the cl_khr_fp16 extension is enabled).
6346       if (Context.getBaseElementType(R)->isHalfType()) {
6347         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6348         D.setInvalidType();
6349       }
6350     }
6351 
6352     if (R->isSamplerT()) {
6353       // OpenCL v1.2 s6.9.b p4:
6354       // The sampler type cannot be used with the __local and __global address
6355       // space qualifiers.
6356       if (R.getAddressSpace() == LangAS::opencl_local ||
6357           R.getAddressSpace() == LangAS::opencl_global) {
6358         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6359       }
6360 
6361       // OpenCL v1.2 s6.12.14.1:
6362       // A global sampler must be declared with either the constant address
6363       // space qualifier or with the const qualifier.
6364       if (DC->isTranslationUnit() &&
6365           !(R.getAddressSpace() == LangAS::opencl_constant ||
6366           R.isConstQualified())) {
6367         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6368         D.setInvalidType();
6369       }
6370     }
6371 
6372     // OpenCL v1.2 s6.9.r:
6373     // The event type cannot be used with the __local, __constant and __global
6374     // address space qualifiers.
6375     if (R->isEventT()) {
6376       if (R.getAddressSpace() != LangAS::opencl_private) {
6377         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6378         D.setInvalidType();
6379       }
6380     }
6381 
6382     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6383     // supported.  OpenCL C does not support thread_local either, and
6384     // also reject all other thread storage class specifiers.
6385     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6386     if (TSC != TSCS_unspecified) {
6387       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6388       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6389            diag::err_opencl_unknown_type_specifier)
6390           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6391           << DeclSpec::getSpecifierName(TSC) << 1;
6392       D.setInvalidType();
6393       return nullptr;
6394     }
6395   }
6396 
6397   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6398   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6399 
6400   // dllimport globals without explicit storage class are treated as extern. We
6401   // have to change the storage class this early to get the right DeclContext.
6402   if (SC == SC_None && !DC->isRecord() &&
6403       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6404       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6405     SC = SC_Extern;
6406 
6407   DeclContext *OriginalDC = DC;
6408   bool IsLocalExternDecl = SC == SC_Extern &&
6409                            adjustContextForLocalExternDecl(DC);
6410 
6411   if (SCSpec == DeclSpec::SCS_mutable) {
6412     // mutable can only appear on non-static class members, so it's always
6413     // an error here
6414     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6415     D.setInvalidType();
6416     SC = SC_None;
6417   }
6418 
6419   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6420       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6421                               D.getDeclSpec().getStorageClassSpecLoc())) {
6422     // In C++11, the 'register' storage class specifier is deprecated.
6423     // Suppress the warning in system macros, it's used in macros in some
6424     // popular C system headers, such as in glibc's htonl() macro.
6425     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6426          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6427                                    : diag::warn_deprecated_register)
6428       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6429   }
6430 
6431   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6432 
6433   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6434     // C99 6.9p2: The storage-class specifiers auto and register shall not
6435     // appear in the declaration specifiers in an external declaration.
6436     // Global Register+Asm is a GNU extension we support.
6437     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6438       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6439       D.setInvalidType();
6440     }
6441   }
6442 
6443   bool IsMemberSpecialization = false;
6444   bool IsVariableTemplateSpecialization = false;
6445   bool IsPartialSpecialization = false;
6446   bool IsVariableTemplate = false;
6447   VarDecl *NewVD = nullptr;
6448   VarTemplateDecl *NewTemplate = nullptr;
6449   TemplateParameterList *TemplateParams = nullptr;
6450   if (!getLangOpts().CPlusPlus) {
6451     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6452                             II, R, TInfo, SC);
6453 
6454     if (R->getContainedDeducedType())
6455       ParsingInitForAutoVars.insert(NewVD);
6456 
6457     if (D.isInvalidType())
6458       NewVD->setInvalidDecl();
6459   } else {
6460     bool Invalid = false;
6461 
6462     if (DC->isRecord() && !CurContext->isRecord()) {
6463       // This is an out-of-line definition of a static data member.
6464       switch (SC) {
6465       case SC_None:
6466         break;
6467       case SC_Static:
6468         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6469              diag::err_static_out_of_line)
6470           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6471         break;
6472       case SC_Auto:
6473       case SC_Register:
6474       case SC_Extern:
6475         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6476         // to names of variables declared in a block or to function parameters.
6477         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6478         // of class members
6479 
6480         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6481              diag::err_storage_class_for_static_member)
6482           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6483         break;
6484       case SC_PrivateExtern:
6485         llvm_unreachable("C storage class in c++!");
6486       }
6487     }
6488 
6489     if (SC == SC_Static && CurContext->isRecord()) {
6490       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6491         if (RD->isLocalClass())
6492           Diag(D.getIdentifierLoc(),
6493                diag::err_static_data_member_not_allowed_in_local_class)
6494             << Name << RD->getDeclName();
6495 
6496         // C++98 [class.union]p1: If a union contains a static data member,
6497         // the program is ill-formed. C++11 drops this restriction.
6498         if (RD->isUnion())
6499           Diag(D.getIdentifierLoc(),
6500                getLangOpts().CPlusPlus11
6501                  ? diag::warn_cxx98_compat_static_data_member_in_union
6502                  : diag::ext_static_data_member_in_union) << Name;
6503         // We conservatively disallow static data members in anonymous structs.
6504         else if (!RD->getDeclName())
6505           Diag(D.getIdentifierLoc(),
6506                diag::err_static_data_member_not_allowed_in_anon_struct)
6507             << Name << RD->isUnion();
6508       }
6509     }
6510 
6511     // Match up the template parameter lists with the scope specifier, then
6512     // determine whether we have a template or a template specialization.
6513     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6514         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6515         D.getCXXScopeSpec(),
6516         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6517             ? D.getName().TemplateId
6518             : nullptr,
6519         TemplateParamLists,
6520         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6521 
6522     if (TemplateParams) {
6523       if (!TemplateParams->size() &&
6524           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6525         // There is an extraneous 'template<>' for this variable. Complain
6526         // about it, but allow the declaration of the variable.
6527         Diag(TemplateParams->getTemplateLoc(),
6528              diag::err_template_variable_noparams)
6529           << II
6530           << SourceRange(TemplateParams->getTemplateLoc(),
6531                          TemplateParams->getRAngleLoc());
6532         TemplateParams = nullptr;
6533       } else {
6534         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6535           // This is an explicit specialization or a partial specialization.
6536           // FIXME: Check that we can declare a specialization here.
6537           IsVariableTemplateSpecialization = true;
6538           IsPartialSpecialization = TemplateParams->size() > 0;
6539         } else { // if (TemplateParams->size() > 0)
6540           // This is a template declaration.
6541           IsVariableTemplate = true;
6542 
6543           // Check that we can declare a template here.
6544           if (CheckTemplateDeclScope(S, TemplateParams))
6545             return nullptr;
6546 
6547           // Only C++1y supports variable templates (N3651).
6548           Diag(D.getIdentifierLoc(),
6549                getLangOpts().CPlusPlus14
6550                    ? diag::warn_cxx11_compat_variable_template
6551                    : diag::ext_variable_template);
6552         }
6553       }
6554     } else {
6555       assert((Invalid ||
6556               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6557              "should have a 'template<>' for this decl");
6558     }
6559 
6560     if (IsVariableTemplateSpecialization) {
6561       SourceLocation TemplateKWLoc =
6562           TemplateParamLists.size() > 0
6563               ? TemplateParamLists[0]->getTemplateLoc()
6564               : SourceLocation();
6565       DeclResult Res = ActOnVarTemplateSpecialization(
6566           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6567           IsPartialSpecialization);
6568       if (Res.isInvalid())
6569         return nullptr;
6570       NewVD = cast<VarDecl>(Res.get());
6571       AddToScope = false;
6572     } else if (D.isDecompositionDeclarator()) {
6573       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6574                                         D.getIdentifierLoc(), R, TInfo, SC,
6575                                         Bindings);
6576     } else
6577       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6578                               D.getIdentifierLoc(), II, R, TInfo, SC);
6579 
6580     // If this is supposed to be a variable template, create it as such.
6581     if (IsVariableTemplate) {
6582       NewTemplate =
6583           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6584                                   TemplateParams, NewVD);
6585       NewVD->setDescribedVarTemplate(NewTemplate);
6586     }
6587 
6588     // If this decl has an auto type in need of deduction, make a note of the
6589     // Decl so we can diagnose uses of it in its own initializer.
6590     if (R->getContainedDeducedType())
6591       ParsingInitForAutoVars.insert(NewVD);
6592 
6593     if (D.isInvalidType() || Invalid) {
6594       NewVD->setInvalidDecl();
6595       if (NewTemplate)
6596         NewTemplate->setInvalidDecl();
6597     }
6598 
6599     SetNestedNameSpecifier(*this, NewVD, D);
6600 
6601     // If we have any template parameter lists that don't directly belong to
6602     // the variable (matching the scope specifier), store them.
6603     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6604     if (TemplateParamLists.size() > VDTemplateParamLists)
6605       NewVD->setTemplateParameterListsInfo(
6606           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6607 
6608     if (D.getDeclSpec().isConstexprSpecified()) {
6609       NewVD->setConstexpr(true);
6610       // C++1z [dcl.spec.constexpr]p1:
6611       //   A static data member declared with the constexpr specifier is
6612       //   implicitly an inline variable.
6613       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6614         NewVD->setImplicitlyInline();
6615     }
6616   }
6617 
6618   if (D.getDeclSpec().isInlineSpecified()) {
6619     if (!getLangOpts().CPlusPlus) {
6620       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6621           << 0;
6622     } else if (CurContext->isFunctionOrMethod()) {
6623       // 'inline' is not allowed on block scope variable declaration.
6624       Diag(D.getDeclSpec().getInlineSpecLoc(),
6625            diag::err_inline_declaration_block_scope) << Name
6626         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6627     } else {
6628       Diag(D.getDeclSpec().getInlineSpecLoc(),
6629            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6630                                      : diag::ext_inline_variable);
6631       NewVD->setInlineSpecified();
6632     }
6633   }
6634 
6635   // Set the lexical context. If the declarator has a C++ scope specifier, the
6636   // lexical context will be different from the semantic context.
6637   NewVD->setLexicalDeclContext(CurContext);
6638   if (NewTemplate)
6639     NewTemplate->setLexicalDeclContext(CurContext);
6640 
6641   if (IsLocalExternDecl) {
6642     if (D.isDecompositionDeclarator())
6643       for (auto *B : Bindings)
6644         B->setLocalExternDecl();
6645     else
6646       NewVD->setLocalExternDecl();
6647   }
6648 
6649   bool EmitTLSUnsupportedError = false;
6650   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6651     // C++11 [dcl.stc]p4:
6652     //   When thread_local is applied to a variable of block scope the
6653     //   storage-class-specifier static is implied if it does not appear
6654     //   explicitly.
6655     // Core issue: 'static' is not implied if the variable is declared
6656     //   'extern'.
6657     if (NewVD->hasLocalStorage() &&
6658         (SCSpec != DeclSpec::SCS_unspecified ||
6659          TSCS != DeclSpec::TSCS_thread_local ||
6660          !DC->isFunctionOrMethod()))
6661       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6662            diag::err_thread_non_global)
6663         << DeclSpec::getSpecifierName(TSCS);
6664     else if (!Context.getTargetInfo().isTLSSupported()) {
6665       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6666         // Postpone error emission until we've collected attributes required to
6667         // figure out whether it's a host or device variable and whether the
6668         // error should be ignored.
6669         EmitTLSUnsupportedError = true;
6670         // We still need to mark the variable as TLS so it shows up in AST with
6671         // proper storage class for other tools to use even if we're not going
6672         // to emit any code for it.
6673         NewVD->setTSCSpec(TSCS);
6674       } else
6675         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6676              diag::err_thread_unsupported);
6677     } else
6678       NewVD->setTSCSpec(TSCS);
6679   }
6680 
6681   // C99 6.7.4p3
6682   //   An inline definition of a function with external linkage shall
6683   //   not contain a definition of a modifiable object with static or
6684   //   thread storage duration...
6685   // We only apply this when the function is required to be defined
6686   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6687   // that a local variable with thread storage duration still has to
6688   // be marked 'static'.  Also note that it's possible to get these
6689   // semantics in C++ using __attribute__((gnu_inline)).
6690   if (SC == SC_Static && S->getFnParent() != nullptr &&
6691       !NewVD->getType().isConstQualified()) {
6692     FunctionDecl *CurFD = getCurFunctionDecl();
6693     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6694       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6695            diag::warn_static_local_in_extern_inline);
6696       MaybeSuggestAddingStaticToDecl(CurFD);
6697     }
6698   }
6699 
6700   if (D.getDeclSpec().isModulePrivateSpecified()) {
6701     if (IsVariableTemplateSpecialization)
6702       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6703           << (IsPartialSpecialization ? 1 : 0)
6704           << FixItHint::CreateRemoval(
6705                  D.getDeclSpec().getModulePrivateSpecLoc());
6706     else if (IsMemberSpecialization)
6707       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6708         << 2
6709         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6710     else if (NewVD->hasLocalStorage())
6711       Diag(NewVD->getLocation(), diag::err_module_private_local)
6712         << 0 << NewVD->getDeclName()
6713         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6714         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6715     else {
6716       NewVD->setModulePrivate();
6717       if (NewTemplate)
6718         NewTemplate->setModulePrivate();
6719       for (auto *B : Bindings)
6720         B->setModulePrivate();
6721     }
6722   }
6723 
6724   // Handle attributes prior to checking for duplicates in MergeVarDecl
6725   ProcessDeclAttributes(S, NewVD, D);
6726 
6727   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6728     if (EmitTLSUnsupportedError &&
6729         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6730          (getLangOpts().OpenMPIsDevice &&
6731           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6732       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6733            diag::err_thread_unsupported);
6734     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6735     // storage [duration]."
6736     if (SC == SC_None && S->getFnParent() != nullptr &&
6737         (NewVD->hasAttr<CUDASharedAttr>() ||
6738          NewVD->hasAttr<CUDAConstantAttr>())) {
6739       NewVD->setStorageClass(SC_Static);
6740     }
6741   }
6742 
6743   // Ensure that dllimport globals without explicit storage class are treated as
6744   // extern. The storage class is set above using parsed attributes. Now we can
6745   // check the VarDecl itself.
6746   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6747          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6748          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6749 
6750   // In auto-retain/release, infer strong retension for variables of
6751   // retainable type.
6752   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6753     NewVD->setInvalidDecl();
6754 
6755   // Handle GNU asm-label extension (encoded as an attribute).
6756   if (Expr *E = (Expr*)D.getAsmLabel()) {
6757     // The parser guarantees this is a string.
6758     StringLiteral *SE = cast<StringLiteral>(E);
6759     StringRef Label = SE->getString();
6760     if (S->getFnParent() != nullptr) {
6761       switch (SC) {
6762       case SC_None:
6763       case SC_Auto:
6764         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6765         break;
6766       case SC_Register:
6767         // Local Named register
6768         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6769             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6770           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6771         break;
6772       case SC_Static:
6773       case SC_Extern:
6774       case SC_PrivateExtern:
6775         break;
6776       }
6777     } else if (SC == SC_Register) {
6778       // Global Named register
6779       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6780         const auto &TI = Context.getTargetInfo();
6781         bool HasSizeMismatch;
6782 
6783         if (!TI.isValidGCCRegisterName(Label))
6784           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6785         else if (!TI.validateGlobalRegisterVariable(Label,
6786                                                     Context.getTypeSize(R),
6787                                                     HasSizeMismatch))
6788           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6789         else if (HasSizeMismatch)
6790           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6791       }
6792 
6793       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6794         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6795         NewVD->setInvalidDecl(true);
6796       }
6797     }
6798 
6799     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6800                                                 Context, Label, 0));
6801   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6802     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6803       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6804     if (I != ExtnameUndeclaredIdentifiers.end()) {
6805       if (isDeclExternC(NewVD)) {
6806         NewVD->addAttr(I->second);
6807         ExtnameUndeclaredIdentifiers.erase(I);
6808       } else
6809         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6810             << /*Variable*/1 << NewVD;
6811     }
6812   }
6813 
6814   // Find the shadowed declaration before filtering for scope.
6815   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6816                                 ? getShadowedDeclaration(NewVD, Previous)
6817                                 : nullptr;
6818 
6819   // Don't consider existing declarations that are in a different
6820   // scope and are out-of-semantic-context declarations (if the new
6821   // declaration has linkage).
6822   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6823                        D.getCXXScopeSpec().isNotEmpty() ||
6824                        IsMemberSpecialization ||
6825                        IsVariableTemplateSpecialization);
6826 
6827   // Check whether the previous declaration is in the same block scope. This
6828   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6829   if (getLangOpts().CPlusPlus &&
6830       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6831     NewVD->setPreviousDeclInSameBlockScope(
6832         Previous.isSingleResult() && !Previous.isShadowed() &&
6833         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6834 
6835   if (!getLangOpts().CPlusPlus) {
6836     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6837   } else {
6838     // If this is an explicit specialization of a static data member, check it.
6839     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6840         CheckMemberSpecialization(NewVD, Previous))
6841       NewVD->setInvalidDecl();
6842 
6843     // Merge the decl with the existing one if appropriate.
6844     if (!Previous.empty()) {
6845       if (Previous.isSingleResult() &&
6846           isa<FieldDecl>(Previous.getFoundDecl()) &&
6847           D.getCXXScopeSpec().isSet()) {
6848         // The user tried to define a non-static data member
6849         // out-of-line (C++ [dcl.meaning]p1).
6850         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6851           << D.getCXXScopeSpec().getRange();
6852         Previous.clear();
6853         NewVD->setInvalidDecl();
6854       }
6855     } else if (D.getCXXScopeSpec().isSet()) {
6856       // No previous declaration in the qualifying scope.
6857       Diag(D.getIdentifierLoc(), diag::err_no_member)
6858         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6859         << D.getCXXScopeSpec().getRange();
6860       NewVD->setInvalidDecl();
6861     }
6862 
6863     if (!IsVariableTemplateSpecialization)
6864       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6865 
6866     if (NewTemplate) {
6867       VarTemplateDecl *PrevVarTemplate =
6868           NewVD->getPreviousDecl()
6869               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6870               : nullptr;
6871 
6872       // Check the template parameter list of this declaration, possibly
6873       // merging in the template parameter list from the previous variable
6874       // template declaration.
6875       if (CheckTemplateParameterList(
6876               TemplateParams,
6877               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6878                               : nullptr,
6879               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6880                DC->isDependentContext())
6881                   ? TPC_ClassTemplateMember
6882                   : TPC_VarTemplate))
6883         NewVD->setInvalidDecl();
6884 
6885       // If we are providing an explicit specialization of a static variable
6886       // template, make a note of that.
6887       if (PrevVarTemplate &&
6888           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6889         PrevVarTemplate->setMemberSpecialization();
6890     }
6891   }
6892 
6893   // Diagnose shadowed variables iff this isn't a redeclaration.
6894   if (ShadowedDecl && !D.isRedeclaration())
6895     CheckShadow(NewVD, ShadowedDecl, Previous);
6896 
6897   ProcessPragmaWeak(S, NewVD);
6898 
6899   // If this is the first declaration of an extern C variable, update
6900   // the map of such variables.
6901   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6902       isIncompleteDeclExternC(*this, NewVD))
6903     RegisterLocallyScopedExternCDecl(NewVD, S);
6904 
6905   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6906     Decl *ManglingContextDecl;
6907     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6908             NewVD->getDeclContext(), ManglingContextDecl)) {
6909       Context.setManglingNumber(
6910           NewVD, MCtx->getManglingNumber(
6911                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6912       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6913     }
6914   }
6915 
6916   // Special handling of variable named 'main'.
6917   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6918       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6919       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6920 
6921     // C++ [basic.start.main]p3
6922     // A program that declares a variable main at global scope is ill-formed.
6923     if (getLangOpts().CPlusPlus)
6924       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6925 
6926     // In C, and external-linkage variable named main results in undefined
6927     // behavior.
6928     else if (NewVD->hasExternalFormalLinkage())
6929       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6930   }
6931 
6932   if (D.isRedeclaration() && !Previous.empty()) {
6933     NamedDecl *Prev = Previous.getRepresentativeDecl();
6934     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6935                                    D.isFunctionDefinition());
6936   }
6937 
6938   if (NewTemplate) {
6939     if (NewVD->isInvalidDecl())
6940       NewTemplate->setInvalidDecl();
6941     ActOnDocumentableDecl(NewTemplate);
6942     return NewTemplate;
6943   }
6944 
6945   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6946     CompleteMemberSpecialization(NewVD, Previous);
6947 
6948   return NewVD;
6949 }
6950 
6951 /// Enum describing the %select options in diag::warn_decl_shadow.
6952 enum ShadowedDeclKind {
6953   SDK_Local,
6954   SDK_Global,
6955   SDK_StaticMember,
6956   SDK_Field,
6957   SDK_Typedef,
6958   SDK_Using
6959 };
6960 
6961 /// Determine what kind of declaration we're shadowing.
6962 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6963                                                 const DeclContext *OldDC) {
6964   if (isa<TypeAliasDecl>(ShadowedDecl))
6965     return SDK_Using;
6966   else if (isa<TypedefDecl>(ShadowedDecl))
6967     return SDK_Typedef;
6968   else if (isa<RecordDecl>(OldDC))
6969     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6970 
6971   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6972 }
6973 
6974 /// Return the location of the capture if the given lambda captures the given
6975 /// variable \p VD, or an invalid source location otherwise.
6976 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6977                                          const VarDecl *VD) {
6978   for (const Capture &Capture : LSI->Captures) {
6979     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6980       return Capture.getLocation();
6981   }
6982   return SourceLocation();
6983 }
6984 
6985 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6986                                      const LookupResult &R) {
6987   // Only diagnose if we're shadowing an unambiguous field or variable.
6988   if (R.getResultKind() != LookupResult::Found)
6989     return false;
6990 
6991   // Return false if warning is ignored.
6992   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6993 }
6994 
6995 /// Return the declaration shadowed by the given variable \p D, or null
6996 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6997 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6998                                         const LookupResult &R) {
6999   if (!shouldWarnIfShadowedDecl(Diags, R))
7000     return nullptr;
7001 
7002   // Don't diagnose declarations at file scope.
7003   if (D->hasGlobalStorage())
7004     return nullptr;
7005 
7006   NamedDecl *ShadowedDecl = R.getFoundDecl();
7007   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7008              ? ShadowedDecl
7009              : nullptr;
7010 }
7011 
7012 /// Return the declaration shadowed by the given typedef \p D, or null
7013 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7014 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7015                                         const LookupResult &R) {
7016   // Don't warn if typedef declaration is part of a class
7017   if (D->getDeclContext()->isRecord())
7018     return nullptr;
7019 
7020   if (!shouldWarnIfShadowedDecl(Diags, R))
7021     return nullptr;
7022 
7023   NamedDecl *ShadowedDecl = R.getFoundDecl();
7024   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7025 }
7026 
7027 /// Diagnose variable or built-in function shadowing.  Implements
7028 /// -Wshadow.
7029 ///
7030 /// This method is called whenever a VarDecl is added to a "useful"
7031 /// scope.
7032 ///
7033 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7034 /// \param R the lookup of the name
7035 ///
7036 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7037                        const LookupResult &R) {
7038   DeclContext *NewDC = D->getDeclContext();
7039 
7040   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7041     // Fields are not shadowed by variables in C++ static methods.
7042     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7043       if (MD->isStatic())
7044         return;
7045 
7046     // Fields shadowed by constructor parameters are a special case. Usually
7047     // the constructor initializes the field with the parameter.
7048     if (isa<CXXConstructorDecl>(NewDC))
7049       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7050         // Remember that this was shadowed so we can either warn about its
7051         // modification or its existence depending on warning settings.
7052         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7053         return;
7054       }
7055   }
7056 
7057   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7058     if (shadowedVar->isExternC()) {
7059       // For shadowing external vars, make sure that we point to the global
7060       // declaration, not a locally scoped extern declaration.
7061       for (auto I : shadowedVar->redecls())
7062         if (I->isFileVarDecl()) {
7063           ShadowedDecl = I;
7064           break;
7065         }
7066     }
7067 
7068   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7069 
7070   unsigned WarningDiag = diag::warn_decl_shadow;
7071   SourceLocation CaptureLoc;
7072   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7073       isa<CXXMethodDecl>(NewDC)) {
7074     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7075       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7076         if (RD->getLambdaCaptureDefault() == LCD_None) {
7077           // Try to avoid warnings for lambdas with an explicit capture list.
7078           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7079           // Warn only when the lambda captures the shadowed decl explicitly.
7080           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7081           if (CaptureLoc.isInvalid())
7082             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7083         } else {
7084           // Remember that this was shadowed so we can avoid the warning if the
7085           // shadowed decl isn't captured and the warning settings allow it.
7086           cast<LambdaScopeInfo>(getCurFunction())
7087               ->ShadowingDecls.push_back(
7088                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7089           return;
7090         }
7091       }
7092 
7093       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7094         // A variable can't shadow a local variable in an enclosing scope, if
7095         // they are separated by a non-capturing declaration context.
7096         for (DeclContext *ParentDC = NewDC;
7097              ParentDC && !ParentDC->Equals(OldDC);
7098              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7099           // Only block literals, captured statements, and lambda expressions
7100           // can capture; other scopes don't.
7101           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7102               !isLambdaCallOperator(ParentDC)) {
7103             return;
7104           }
7105         }
7106       }
7107     }
7108   }
7109 
7110   // Only warn about certain kinds of shadowing for class members.
7111   if (NewDC && NewDC->isRecord()) {
7112     // In particular, don't warn about shadowing non-class members.
7113     if (!OldDC->isRecord())
7114       return;
7115 
7116     // TODO: should we warn about static data members shadowing
7117     // static data members from base classes?
7118 
7119     // TODO: don't diagnose for inaccessible shadowed members.
7120     // This is hard to do perfectly because we might friend the
7121     // shadowing context, but that's just a false negative.
7122   }
7123 
7124 
7125   DeclarationName Name = R.getLookupName();
7126 
7127   // Emit warning and note.
7128   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7129     return;
7130   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7131   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7132   if (!CaptureLoc.isInvalid())
7133     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7134         << Name << /*explicitly*/ 1;
7135   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7136 }
7137 
7138 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7139 /// when these variables are captured by the lambda.
7140 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7141   for (const auto &Shadow : LSI->ShadowingDecls) {
7142     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7143     // Try to avoid the warning when the shadowed decl isn't captured.
7144     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7145     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7146     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7147                                        ? diag::warn_decl_shadow_uncaptured_local
7148                                        : diag::warn_decl_shadow)
7149         << Shadow.VD->getDeclName()
7150         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7151     if (!CaptureLoc.isInvalid())
7152       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7153           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7154     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7155   }
7156 }
7157 
7158 /// Check -Wshadow without the advantage of a previous lookup.
7159 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7160   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7161     return;
7162 
7163   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7164                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7165   LookupName(R, S);
7166   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7167     CheckShadow(D, ShadowedDecl, R);
7168 }
7169 
7170 /// Check if 'E', which is an expression that is about to be modified, refers
7171 /// to a constructor parameter that shadows a field.
7172 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7173   // Quickly ignore expressions that can't be shadowing ctor parameters.
7174   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7175     return;
7176   E = E->IgnoreParenImpCasts();
7177   auto *DRE = dyn_cast<DeclRefExpr>(E);
7178   if (!DRE)
7179     return;
7180   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7181   auto I = ShadowingDecls.find(D);
7182   if (I == ShadowingDecls.end())
7183     return;
7184   const NamedDecl *ShadowedDecl = I->second;
7185   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7186   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7187   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7188   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7189 
7190   // Avoid issuing multiple warnings about the same decl.
7191   ShadowingDecls.erase(I);
7192 }
7193 
7194 /// Check for conflict between this global or extern "C" declaration and
7195 /// previous global or extern "C" declarations. This is only used in C++.
7196 template<typename T>
7197 static bool checkGlobalOrExternCConflict(
7198     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7199   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7200   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7201 
7202   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7203     // The common case: this global doesn't conflict with any extern "C"
7204     // declaration.
7205     return false;
7206   }
7207 
7208   if (Prev) {
7209     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7210       // Both the old and new declarations have C language linkage. This is a
7211       // redeclaration.
7212       Previous.clear();
7213       Previous.addDecl(Prev);
7214       return true;
7215     }
7216 
7217     // This is a global, non-extern "C" declaration, and there is a previous
7218     // non-global extern "C" declaration. Diagnose if this is a variable
7219     // declaration.
7220     if (!isa<VarDecl>(ND))
7221       return false;
7222   } else {
7223     // The declaration is extern "C". Check for any declaration in the
7224     // translation unit which might conflict.
7225     if (IsGlobal) {
7226       // We have already performed the lookup into the translation unit.
7227       IsGlobal = false;
7228       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7229            I != E; ++I) {
7230         if (isa<VarDecl>(*I)) {
7231           Prev = *I;
7232           break;
7233         }
7234       }
7235     } else {
7236       DeclContext::lookup_result R =
7237           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7238       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7239            I != E; ++I) {
7240         if (isa<VarDecl>(*I)) {
7241           Prev = *I;
7242           break;
7243         }
7244         // FIXME: If we have any other entity with this name in global scope,
7245         // the declaration is ill-formed, but that is a defect: it breaks the
7246         // 'stat' hack, for instance. Only variables can have mangled name
7247         // clashes with extern "C" declarations, so only they deserve a
7248         // diagnostic.
7249       }
7250     }
7251 
7252     if (!Prev)
7253       return false;
7254   }
7255 
7256   // Use the first declaration's location to ensure we point at something which
7257   // is lexically inside an extern "C" linkage-spec.
7258   assert(Prev && "should have found a previous declaration to diagnose");
7259   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7260     Prev = FD->getFirstDecl();
7261   else
7262     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7263 
7264   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7265     << IsGlobal << ND;
7266   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7267     << IsGlobal;
7268   return false;
7269 }
7270 
7271 /// Apply special rules for handling extern "C" declarations. Returns \c true
7272 /// if we have found that this is a redeclaration of some prior entity.
7273 ///
7274 /// Per C++ [dcl.link]p6:
7275 ///   Two declarations [for a function or variable] with C language linkage
7276 ///   with the same name that appear in different scopes refer to the same
7277 ///   [entity]. An entity with C language linkage shall not be declared with
7278 ///   the same name as an entity in global scope.
7279 template<typename T>
7280 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7281                                                   LookupResult &Previous) {
7282   if (!S.getLangOpts().CPlusPlus) {
7283     // In C, when declaring a global variable, look for a corresponding 'extern'
7284     // variable declared in function scope. We don't need this in C++, because
7285     // we find local extern decls in the surrounding file-scope DeclContext.
7286     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7287       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7288         Previous.clear();
7289         Previous.addDecl(Prev);
7290         return true;
7291       }
7292     }
7293     return false;
7294   }
7295 
7296   // A declaration in the translation unit can conflict with an extern "C"
7297   // declaration.
7298   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7299     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7300 
7301   // An extern "C" declaration can conflict with a declaration in the
7302   // translation unit or can be a redeclaration of an extern "C" declaration
7303   // in another scope.
7304   if (isIncompleteDeclExternC(S,ND))
7305     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7306 
7307   // Neither global nor extern "C": nothing to do.
7308   return false;
7309 }
7310 
7311 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7312   // If the decl is already known invalid, don't check it.
7313   if (NewVD->isInvalidDecl())
7314     return;
7315 
7316   QualType T = NewVD->getType();
7317 
7318   // Defer checking an 'auto' type until its initializer is attached.
7319   if (T->isUndeducedType())
7320     return;
7321 
7322   if (NewVD->hasAttrs())
7323     CheckAlignasUnderalignment(NewVD);
7324 
7325   if (T->isObjCObjectType()) {
7326     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7327       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7328     T = Context.getObjCObjectPointerType(T);
7329     NewVD->setType(T);
7330   }
7331 
7332   // Emit an error if an address space was applied to decl with local storage.
7333   // This includes arrays of objects with address space qualifiers, but not
7334   // automatic variables that point to other address spaces.
7335   // ISO/IEC TR 18037 S5.1.2
7336   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7337       T.getAddressSpace() != LangAS::Default) {
7338     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7339     NewVD->setInvalidDecl();
7340     return;
7341   }
7342 
7343   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7344   // scope.
7345   if (getLangOpts().OpenCLVersion == 120 &&
7346       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7347       NewVD->isStaticLocal()) {
7348     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7349     NewVD->setInvalidDecl();
7350     return;
7351   }
7352 
7353   if (getLangOpts().OpenCL) {
7354     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7355     if (NewVD->hasAttr<BlocksAttr>()) {
7356       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7357       return;
7358     }
7359 
7360     if (T->isBlockPointerType()) {
7361       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7362       // can't use 'extern' storage class.
7363       if (!T.isConstQualified()) {
7364         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7365             << 0 /*const*/;
7366         NewVD->setInvalidDecl();
7367         return;
7368       }
7369       if (NewVD->hasExternalStorage()) {
7370         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7371         NewVD->setInvalidDecl();
7372         return;
7373       }
7374     }
7375     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7376     // __constant address space.
7377     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7378     // variables inside a function can also be declared in the global
7379     // address space.
7380     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7381     // address space additionally.
7382     // FIXME: Add local AS for OpenCL C++.
7383     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7384         NewVD->hasExternalStorage()) {
7385       if (!T->isSamplerT() &&
7386           !(T.getAddressSpace() == LangAS::opencl_constant ||
7387             (T.getAddressSpace() == LangAS::opencl_global &&
7388              (getLangOpts().OpenCLVersion == 200 ||
7389               getLangOpts().OpenCLCPlusPlus)))) {
7390         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7391         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7392           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7393               << Scope << "global or constant";
7394         else
7395           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7396               << Scope << "constant";
7397         NewVD->setInvalidDecl();
7398         return;
7399       }
7400     } else {
7401       if (T.getAddressSpace() == LangAS::opencl_global) {
7402         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7403             << 1 /*is any function*/ << "global";
7404         NewVD->setInvalidDecl();
7405         return;
7406       }
7407       if (T.getAddressSpace() == LangAS::opencl_constant ||
7408           T.getAddressSpace() == LangAS::opencl_local) {
7409         FunctionDecl *FD = getCurFunctionDecl();
7410         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7411         // in functions.
7412         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7413           if (T.getAddressSpace() == LangAS::opencl_constant)
7414             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7415                 << 0 /*non-kernel only*/ << "constant";
7416           else
7417             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7418                 << 0 /*non-kernel only*/ << "local";
7419           NewVD->setInvalidDecl();
7420           return;
7421         }
7422         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7423         // in the outermost scope of a kernel function.
7424         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7425           if (!getCurScope()->isFunctionScope()) {
7426             if (T.getAddressSpace() == LangAS::opencl_constant)
7427               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7428                   << "constant";
7429             else
7430               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7431                   << "local";
7432             NewVD->setInvalidDecl();
7433             return;
7434           }
7435         }
7436       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7437         // Do not allow other address spaces on automatic variable.
7438         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7439         NewVD->setInvalidDecl();
7440         return;
7441       }
7442     }
7443   }
7444 
7445   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7446       && !NewVD->hasAttr<BlocksAttr>()) {
7447     if (getLangOpts().getGC() != LangOptions::NonGC)
7448       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7449     else {
7450       assert(!getLangOpts().ObjCAutoRefCount);
7451       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7452     }
7453   }
7454 
7455   bool isVM = T->isVariablyModifiedType();
7456   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7457       NewVD->hasAttr<BlocksAttr>())
7458     setFunctionHasBranchProtectedScope();
7459 
7460   if ((isVM && NewVD->hasLinkage()) ||
7461       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7462     bool SizeIsNegative;
7463     llvm::APSInt Oversized;
7464     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7465         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7466     QualType FixedT;
7467     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7468       FixedT = FixedTInfo->getType();
7469     else if (FixedTInfo) {
7470       // Type and type-as-written are canonically different. We need to fix up
7471       // both types separately.
7472       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7473                                                    Oversized);
7474     }
7475     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7476       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7477       // FIXME: This won't give the correct result for
7478       // int a[10][n];
7479       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7480 
7481       if (NewVD->isFileVarDecl())
7482         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7483         << SizeRange;
7484       else if (NewVD->isStaticLocal())
7485         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7486         << SizeRange;
7487       else
7488         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7489         << SizeRange;
7490       NewVD->setInvalidDecl();
7491       return;
7492     }
7493 
7494     if (!FixedTInfo) {
7495       if (NewVD->isFileVarDecl())
7496         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7497       else
7498         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7499       NewVD->setInvalidDecl();
7500       return;
7501     }
7502 
7503     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7504     NewVD->setType(FixedT);
7505     NewVD->setTypeSourceInfo(FixedTInfo);
7506   }
7507 
7508   if (T->isVoidType()) {
7509     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7510     //                    of objects and functions.
7511     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7512       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7513         << T;
7514       NewVD->setInvalidDecl();
7515       return;
7516     }
7517   }
7518 
7519   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7520     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7521     NewVD->setInvalidDecl();
7522     return;
7523   }
7524 
7525   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7526     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7527     NewVD->setInvalidDecl();
7528     return;
7529   }
7530 
7531   if (NewVD->isConstexpr() && !T->isDependentType() &&
7532       RequireLiteralType(NewVD->getLocation(), T,
7533                          diag::err_constexpr_var_non_literal)) {
7534     NewVD->setInvalidDecl();
7535     return;
7536   }
7537 }
7538 
7539 /// Perform semantic checking on a newly-created variable
7540 /// declaration.
7541 ///
7542 /// This routine performs all of the type-checking required for a
7543 /// variable declaration once it has been built. It is used both to
7544 /// check variables after they have been parsed and their declarators
7545 /// have been translated into a declaration, and to check variables
7546 /// that have been instantiated from a template.
7547 ///
7548 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7549 ///
7550 /// Returns true if the variable declaration is a redeclaration.
7551 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7552   CheckVariableDeclarationType(NewVD);
7553 
7554   // If the decl is already known invalid, don't check it.
7555   if (NewVD->isInvalidDecl())
7556     return false;
7557 
7558   // If we did not find anything by this name, look for a non-visible
7559   // extern "C" declaration with the same name.
7560   if (Previous.empty() &&
7561       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7562     Previous.setShadowed();
7563 
7564   if (!Previous.empty()) {
7565     MergeVarDecl(NewVD, Previous);
7566     return true;
7567   }
7568   return false;
7569 }
7570 
7571 namespace {
7572 struct FindOverriddenMethod {
7573   Sema *S;
7574   CXXMethodDecl *Method;
7575 
7576   /// Member lookup function that determines whether a given C++
7577   /// method overrides a method in a base class, to be used with
7578   /// CXXRecordDecl::lookupInBases().
7579   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7580     RecordDecl *BaseRecord =
7581         Specifier->getType()->getAs<RecordType>()->getDecl();
7582 
7583     DeclarationName Name = Method->getDeclName();
7584 
7585     // FIXME: Do we care about other names here too?
7586     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7587       // We really want to find the base class destructor here.
7588       QualType T = S->Context.getTypeDeclType(BaseRecord);
7589       CanQualType CT = S->Context.getCanonicalType(T);
7590 
7591       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7592     }
7593 
7594     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7595          Path.Decls = Path.Decls.slice(1)) {
7596       NamedDecl *D = Path.Decls.front();
7597       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7598         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7599           return true;
7600       }
7601     }
7602 
7603     return false;
7604   }
7605 };
7606 
7607 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7608 } // end anonymous namespace
7609 
7610 /// Report an error regarding overriding, along with any relevant
7611 /// overridden methods.
7612 ///
7613 /// \param DiagID the primary error to report.
7614 /// \param MD the overriding method.
7615 /// \param OEK which overrides to include as notes.
7616 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7617                             OverrideErrorKind OEK = OEK_All) {
7618   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7619   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7620     // This check (& the OEK parameter) could be replaced by a predicate, but
7621     // without lambdas that would be overkill. This is still nicer than writing
7622     // out the diag loop 3 times.
7623     if ((OEK == OEK_All) ||
7624         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7625         (OEK == OEK_Deleted && O->isDeleted()))
7626       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7627   }
7628 }
7629 
7630 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7631 /// and if so, check that it's a valid override and remember it.
7632 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7633   // Look for methods in base classes that this method might override.
7634   CXXBasePaths Paths;
7635   FindOverriddenMethod FOM;
7636   FOM.Method = MD;
7637   FOM.S = this;
7638   bool hasDeletedOverridenMethods = false;
7639   bool hasNonDeletedOverridenMethods = false;
7640   bool AddedAny = false;
7641   if (DC->lookupInBases(FOM, Paths)) {
7642     for (auto *I : Paths.found_decls()) {
7643       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7644         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7645         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7646             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7647             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7648             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7649           hasDeletedOverridenMethods |= OldMD->isDeleted();
7650           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7651           AddedAny = true;
7652         }
7653       }
7654     }
7655   }
7656 
7657   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7658     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7659   }
7660   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7661     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7662   }
7663 
7664   return AddedAny;
7665 }
7666 
7667 namespace {
7668   // Struct for holding all of the extra arguments needed by
7669   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7670   struct ActOnFDArgs {
7671     Scope *S;
7672     Declarator &D;
7673     MultiTemplateParamsArg TemplateParamLists;
7674     bool AddToScope;
7675   };
7676 } // end anonymous namespace
7677 
7678 namespace {
7679 
7680 // Callback to only accept typo corrections that have a non-zero edit distance.
7681 // Also only accept corrections that have the same parent decl.
7682 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7683  public:
7684   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7685                             CXXRecordDecl *Parent)
7686       : Context(Context), OriginalFD(TypoFD),
7687         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7688 
7689   bool ValidateCandidate(const TypoCorrection &candidate) override {
7690     if (candidate.getEditDistance() == 0)
7691       return false;
7692 
7693     SmallVector<unsigned, 1> MismatchedParams;
7694     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7695                                           CDeclEnd = candidate.end();
7696          CDecl != CDeclEnd; ++CDecl) {
7697       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7698 
7699       if (FD && !FD->hasBody() &&
7700           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7701         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7702           CXXRecordDecl *Parent = MD->getParent();
7703           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7704             return true;
7705         } else if (!ExpectedParent) {
7706           return true;
7707         }
7708       }
7709     }
7710 
7711     return false;
7712   }
7713 
7714  private:
7715   ASTContext &Context;
7716   FunctionDecl *OriginalFD;
7717   CXXRecordDecl *ExpectedParent;
7718 };
7719 
7720 } // end anonymous namespace
7721 
7722 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7723   TypoCorrectedFunctionDefinitions.insert(F);
7724 }
7725 
7726 /// Generate diagnostics for an invalid function redeclaration.
7727 ///
7728 /// This routine handles generating the diagnostic messages for an invalid
7729 /// function redeclaration, including finding possible similar declarations
7730 /// or performing typo correction if there are no previous declarations with
7731 /// the same name.
7732 ///
7733 /// Returns a NamedDecl iff typo correction was performed and substituting in
7734 /// the new declaration name does not cause new errors.
7735 static NamedDecl *DiagnoseInvalidRedeclaration(
7736     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7737     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7738   DeclarationName Name = NewFD->getDeclName();
7739   DeclContext *NewDC = NewFD->getDeclContext();
7740   SmallVector<unsigned, 1> MismatchedParams;
7741   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7742   TypoCorrection Correction;
7743   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7744   unsigned DiagMsg =
7745     IsLocalFriend ? diag::err_no_matching_local_friend :
7746     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7747     diag::err_member_decl_does_not_match;
7748   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7749                     IsLocalFriend ? Sema::LookupLocalFriendName
7750                                   : Sema::LookupOrdinaryName,
7751                     Sema::ForVisibleRedeclaration);
7752 
7753   NewFD->setInvalidDecl();
7754   if (IsLocalFriend)
7755     SemaRef.LookupName(Prev, S);
7756   else
7757     SemaRef.LookupQualifiedName(Prev, NewDC);
7758   assert(!Prev.isAmbiguous() &&
7759          "Cannot have an ambiguity in previous-declaration lookup");
7760   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7761   if (!Prev.empty()) {
7762     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7763          Func != FuncEnd; ++Func) {
7764       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7765       if (FD &&
7766           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7767         // Add 1 to the index so that 0 can mean the mismatch didn't
7768         // involve a parameter
7769         unsigned ParamNum =
7770             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7771         NearMatches.push_back(std::make_pair(FD, ParamNum));
7772       }
7773     }
7774   // If the qualified name lookup yielded nothing, try typo correction
7775   } else if ((Correction = SemaRef.CorrectTypo(
7776                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7777                   &ExtraArgs.D.getCXXScopeSpec(),
7778                   llvm::make_unique<DifferentNameValidatorCCC>(
7779                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7780                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7781     // Set up everything for the call to ActOnFunctionDeclarator
7782     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7783                               ExtraArgs.D.getIdentifierLoc());
7784     Previous.clear();
7785     Previous.setLookupName(Correction.getCorrection());
7786     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7787                                     CDeclEnd = Correction.end();
7788          CDecl != CDeclEnd; ++CDecl) {
7789       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7790       if (FD && !FD->hasBody() &&
7791           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7792         Previous.addDecl(FD);
7793       }
7794     }
7795     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7796 
7797     NamedDecl *Result;
7798     // Retry building the function declaration with the new previous
7799     // declarations, and with errors suppressed.
7800     {
7801       // Trap errors.
7802       Sema::SFINAETrap Trap(SemaRef);
7803 
7804       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7805       // pieces need to verify the typo-corrected C++ declaration and hopefully
7806       // eliminate the need for the parameter pack ExtraArgs.
7807       Result = SemaRef.ActOnFunctionDeclarator(
7808           ExtraArgs.S, ExtraArgs.D,
7809           Correction.getCorrectionDecl()->getDeclContext(),
7810           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7811           ExtraArgs.AddToScope);
7812 
7813       if (Trap.hasErrorOccurred())
7814         Result = nullptr;
7815     }
7816 
7817     if (Result) {
7818       // Determine which correction we picked.
7819       Decl *Canonical = Result->getCanonicalDecl();
7820       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7821            I != E; ++I)
7822         if ((*I)->getCanonicalDecl() == Canonical)
7823           Correction.setCorrectionDecl(*I);
7824 
7825       // Let Sema know about the correction.
7826       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7827       SemaRef.diagnoseTypo(
7828           Correction,
7829           SemaRef.PDiag(IsLocalFriend
7830                           ? diag::err_no_matching_local_friend_suggest
7831                           : diag::err_member_decl_does_not_match_suggest)
7832             << Name << NewDC << IsDefinition);
7833       return Result;
7834     }
7835 
7836     // Pretend the typo correction never occurred
7837     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7838                               ExtraArgs.D.getIdentifierLoc());
7839     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7840     Previous.clear();
7841     Previous.setLookupName(Name);
7842   }
7843 
7844   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7845       << Name << NewDC << IsDefinition << NewFD->getLocation();
7846 
7847   bool NewFDisConst = false;
7848   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7849     NewFDisConst = NewMD->isConst();
7850 
7851   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7852        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7853        NearMatch != NearMatchEnd; ++NearMatch) {
7854     FunctionDecl *FD = NearMatch->first;
7855     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7856     bool FDisConst = MD && MD->isConst();
7857     bool IsMember = MD || !IsLocalFriend;
7858 
7859     // FIXME: These notes are poorly worded for the local friend case.
7860     if (unsigned Idx = NearMatch->second) {
7861       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7862       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7863       if (Loc.isInvalid()) Loc = FD->getLocation();
7864       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7865                                  : diag::note_local_decl_close_param_match)
7866         << Idx << FDParam->getType()
7867         << NewFD->getParamDecl(Idx - 1)->getType();
7868     } else if (FDisConst != NewFDisConst) {
7869       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7870           << NewFDisConst << FD->getSourceRange().getEnd();
7871     } else
7872       SemaRef.Diag(FD->getLocation(),
7873                    IsMember ? diag::note_member_def_close_match
7874                             : diag::note_local_decl_close_match);
7875   }
7876   return nullptr;
7877 }
7878 
7879 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7880   switch (D.getDeclSpec().getStorageClassSpec()) {
7881   default: llvm_unreachable("Unknown storage class!");
7882   case DeclSpec::SCS_auto:
7883   case DeclSpec::SCS_register:
7884   case DeclSpec::SCS_mutable:
7885     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7886                  diag::err_typecheck_sclass_func);
7887     D.getMutableDeclSpec().ClearStorageClassSpecs();
7888     D.setInvalidType();
7889     break;
7890   case DeclSpec::SCS_unspecified: break;
7891   case DeclSpec::SCS_extern:
7892     if (D.getDeclSpec().isExternInLinkageSpec())
7893       return SC_None;
7894     return SC_Extern;
7895   case DeclSpec::SCS_static: {
7896     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7897       // C99 6.7.1p5:
7898       //   The declaration of an identifier for a function that has
7899       //   block scope shall have no explicit storage-class specifier
7900       //   other than extern
7901       // See also (C++ [dcl.stc]p4).
7902       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7903                    diag::err_static_block_func);
7904       break;
7905     } else
7906       return SC_Static;
7907   }
7908   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7909   }
7910 
7911   // No explicit storage class has already been returned
7912   return SC_None;
7913 }
7914 
7915 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7916                                            DeclContext *DC, QualType &R,
7917                                            TypeSourceInfo *TInfo,
7918                                            StorageClass SC,
7919                                            bool &IsVirtualOkay) {
7920   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7921   DeclarationName Name = NameInfo.getName();
7922 
7923   FunctionDecl *NewFD = nullptr;
7924   bool isInline = D.getDeclSpec().isInlineSpecified();
7925 
7926   if (!SemaRef.getLangOpts().CPlusPlus) {
7927     // Determine whether the function was written with a
7928     // prototype. This true when:
7929     //   - there is a prototype in the declarator, or
7930     //   - the type R of the function is some kind of typedef or other non-
7931     //     attributed reference to a type name (which eventually refers to a
7932     //     function type).
7933     bool HasPrototype =
7934       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7935       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7936 
7937     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7938                                  R, TInfo, SC, isInline, HasPrototype, false);
7939     if (D.isInvalidType())
7940       NewFD->setInvalidDecl();
7941 
7942     return NewFD;
7943   }
7944 
7945   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7946   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7947 
7948   // Check that the return type is not an abstract class type.
7949   // For record types, this is done by the AbstractClassUsageDiagnoser once
7950   // the class has been completely parsed.
7951   if (!DC->isRecord() &&
7952       SemaRef.RequireNonAbstractType(
7953           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7954           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7955     D.setInvalidType();
7956 
7957   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7958     // This is a C++ constructor declaration.
7959     assert(DC->isRecord() &&
7960            "Constructors can only be declared in a member context");
7961 
7962     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7963     return CXXConstructorDecl::Create(
7964         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7965         TInfo, isExplicit, isInline,
7966         /*isImplicitlyDeclared=*/false, isConstexpr);
7967 
7968   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7969     // This is a C++ destructor declaration.
7970     if (DC->isRecord()) {
7971       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7972       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7973       CXXDestructorDecl *NewDD =
7974           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7975                                     NameInfo, R, TInfo, isInline,
7976                                     /*isImplicitlyDeclared=*/false);
7977 
7978       // If the destructor needs an implicit exception specification, set it
7979       // now. FIXME: It'd be nice to be able to create the right type to start
7980       // with, but the type needs to reference the destructor declaration.
7981       if (SemaRef.getLangOpts().CPlusPlus11)
7982         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7983 
7984       IsVirtualOkay = true;
7985       return NewDD;
7986 
7987     } else {
7988       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7989       D.setInvalidType();
7990 
7991       // Create a FunctionDecl to satisfy the function definition parsing
7992       // code path.
7993       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7994                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
7995                                   isInline,
7996                                   /*hasPrototype=*/true, isConstexpr);
7997     }
7998 
7999   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8000     if (!DC->isRecord()) {
8001       SemaRef.Diag(D.getIdentifierLoc(),
8002            diag::err_conv_function_not_member);
8003       return nullptr;
8004     }
8005 
8006     SemaRef.CheckConversionDeclarator(D, R, SC);
8007     IsVirtualOkay = true;
8008     return CXXConversionDecl::Create(
8009         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8010         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
8011 
8012   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8013     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8014 
8015     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8016                                          isExplicit, NameInfo, R, TInfo,
8017                                          D.getEndLoc());
8018   } else if (DC->isRecord()) {
8019     // If the name of the function is the same as the name of the record,
8020     // then this must be an invalid constructor that has a return type.
8021     // (The parser checks for a return type and makes the declarator a
8022     // constructor if it has no return type).
8023     if (Name.getAsIdentifierInfo() &&
8024         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8025       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8026         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8027         << SourceRange(D.getIdentifierLoc());
8028       return nullptr;
8029     }
8030 
8031     // This is a C++ method declaration.
8032     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8033         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8034         TInfo, SC, isInline, isConstexpr, SourceLocation());
8035     IsVirtualOkay = !Ret->isStatic();
8036     return Ret;
8037   } else {
8038     bool isFriend =
8039         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8040     if (!isFriend && SemaRef.CurContext->isRecord())
8041       return nullptr;
8042 
8043     // Determine whether the function was written with a
8044     // prototype. This true when:
8045     //   - we're in C++ (where every function has a prototype),
8046     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8047                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8048                                 isConstexpr);
8049   }
8050 }
8051 
8052 enum OpenCLParamType {
8053   ValidKernelParam,
8054   PtrPtrKernelParam,
8055   PtrKernelParam,
8056   InvalidAddrSpacePtrKernelParam,
8057   InvalidKernelParam,
8058   RecordKernelParam
8059 };
8060 
8061 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8062   // Size dependent types are just typedefs to normal integer types
8063   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8064   // integers other than by their names.
8065   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8066 
8067   // Remove typedefs one by one until we reach a typedef
8068   // for a size dependent type.
8069   QualType DesugaredTy = Ty;
8070   do {
8071     ArrayRef<StringRef> Names(SizeTypeNames);
8072     auto Match =
8073         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8074     if (Names.end() != Match)
8075       return true;
8076 
8077     Ty = DesugaredTy;
8078     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8079   } while (DesugaredTy != Ty);
8080 
8081   return false;
8082 }
8083 
8084 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8085   if (PT->isPointerType()) {
8086     QualType PointeeType = PT->getPointeeType();
8087     if (PointeeType->isPointerType())
8088       return PtrPtrKernelParam;
8089     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8090         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8091         PointeeType.getAddressSpace() == LangAS::Default)
8092       return InvalidAddrSpacePtrKernelParam;
8093     return PtrKernelParam;
8094   }
8095 
8096   // OpenCL v1.2 s6.9.k:
8097   // Arguments to kernel functions in a program cannot be declared with the
8098   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8099   // uintptr_t or a struct and/or union that contain fields declared to be one
8100   // of these built-in scalar types.
8101   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8102     return InvalidKernelParam;
8103 
8104   if (PT->isImageType())
8105     return PtrKernelParam;
8106 
8107   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8108     return InvalidKernelParam;
8109 
8110   // OpenCL extension spec v1.2 s9.5:
8111   // This extension adds support for half scalar and vector types as built-in
8112   // types that can be used for arithmetic operations, conversions etc.
8113   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8114     return InvalidKernelParam;
8115 
8116   if (PT->isRecordType())
8117     return RecordKernelParam;
8118 
8119   // Look into an array argument to check if it has a forbidden type.
8120   if (PT->isArrayType()) {
8121     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8122     // Call ourself to check an underlying type of an array. Since the
8123     // getPointeeOrArrayElementType returns an innermost type which is not an
8124     // array, this recursive call only happens once.
8125     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8126   }
8127 
8128   return ValidKernelParam;
8129 }
8130 
8131 static void checkIsValidOpenCLKernelParameter(
8132   Sema &S,
8133   Declarator &D,
8134   ParmVarDecl *Param,
8135   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8136   QualType PT = Param->getType();
8137 
8138   // Cache the valid types we encounter to avoid rechecking structs that are
8139   // used again
8140   if (ValidTypes.count(PT.getTypePtr()))
8141     return;
8142 
8143   switch (getOpenCLKernelParameterType(S, PT)) {
8144   case PtrPtrKernelParam:
8145     // OpenCL v1.2 s6.9.a:
8146     // A kernel function argument cannot be declared as a
8147     // pointer to a pointer type.
8148     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8149     D.setInvalidType();
8150     return;
8151 
8152   case InvalidAddrSpacePtrKernelParam:
8153     // OpenCL v1.0 s6.5:
8154     // __kernel function arguments declared to be a pointer of a type can point
8155     // to one of the following address spaces only : __global, __local or
8156     // __constant.
8157     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8158     D.setInvalidType();
8159     return;
8160 
8161     // OpenCL v1.2 s6.9.k:
8162     // Arguments to kernel functions in a program cannot be declared with the
8163     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8164     // uintptr_t or a struct and/or union that contain fields declared to be
8165     // one of these built-in scalar types.
8166 
8167   case InvalidKernelParam:
8168     // OpenCL v1.2 s6.8 n:
8169     // A kernel function argument cannot be declared
8170     // of event_t type.
8171     // Do not diagnose half type since it is diagnosed as invalid argument
8172     // type for any function elsewhere.
8173     if (!PT->isHalfType()) {
8174       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8175 
8176       // Explain what typedefs are involved.
8177       const TypedefType *Typedef = nullptr;
8178       while ((Typedef = PT->getAs<TypedefType>())) {
8179         SourceLocation Loc = Typedef->getDecl()->getLocation();
8180         // SourceLocation may be invalid for a built-in type.
8181         if (Loc.isValid())
8182           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8183         PT = Typedef->desugar();
8184       }
8185     }
8186 
8187     D.setInvalidType();
8188     return;
8189 
8190   case PtrKernelParam:
8191   case ValidKernelParam:
8192     ValidTypes.insert(PT.getTypePtr());
8193     return;
8194 
8195   case RecordKernelParam:
8196     break;
8197   }
8198 
8199   // Track nested structs we will inspect
8200   SmallVector<const Decl *, 4> VisitStack;
8201 
8202   // Track where we are in the nested structs. Items will migrate from
8203   // VisitStack to HistoryStack as we do the DFS for bad field.
8204   SmallVector<const FieldDecl *, 4> HistoryStack;
8205   HistoryStack.push_back(nullptr);
8206 
8207   // At this point we already handled everything except of a RecordType or
8208   // an ArrayType of a RecordType.
8209   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8210   const RecordType *RecTy =
8211       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8212   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8213 
8214   VisitStack.push_back(RecTy->getDecl());
8215   assert(VisitStack.back() && "First decl null?");
8216 
8217   do {
8218     const Decl *Next = VisitStack.pop_back_val();
8219     if (!Next) {
8220       assert(!HistoryStack.empty());
8221       // Found a marker, we have gone up a level
8222       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8223         ValidTypes.insert(Hist->getType().getTypePtr());
8224 
8225       continue;
8226     }
8227 
8228     // Adds everything except the original parameter declaration (which is not a
8229     // field itself) to the history stack.
8230     const RecordDecl *RD;
8231     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8232       HistoryStack.push_back(Field);
8233 
8234       QualType FieldTy = Field->getType();
8235       // Other field types (known to be valid or invalid) are handled while we
8236       // walk around RecordDecl::fields().
8237       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8238              "Unexpected type.");
8239       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8240 
8241       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8242     } else {
8243       RD = cast<RecordDecl>(Next);
8244     }
8245 
8246     // Add a null marker so we know when we've gone back up a level
8247     VisitStack.push_back(nullptr);
8248 
8249     for (const auto *FD : RD->fields()) {
8250       QualType QT = FD->getType();
8251 
8252       if (ValidTypes.count(QT.getTypePtr()))
8253         continue;
8254 
8255       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8256       if (ParamType == ValidKernelParam)
8257         continue;
8258 
8259       if (ParamType == RecordKernelParam) {
8260         VisitStack.push_back(FD);
8261         continue;
8262       }
8263 
8264       // OpenCL v1.2 s6.9.p:
8265       // Arguments to kernel functions that are declared to be a struct or union
8266       // do not allow OpenCL objects to be passed as elements of the struct or
8267       // union.
8268       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8269           ParamType == InvalidAddrSpacePtrKernelParam) {
8270         S.Diag(Param->getLocation(),
8271                diag::err_record_with_pointers_kernel_param)
8272           << PT->isUnionType()
8273           << PT;
8274       } else {
8275         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8276       }
8277 
8278       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8279           << OrigRecDecl->getDeclName();
8280 
8281       // We have an error, now let's go back up through history and show where
8282       // the offending field came from
8283       for (ArrayRef<const FieldDecl *>::const_iterator
8284                I = HistoryStack.begin() + 1,
8285                E = HistoryStack.end();
8286            I != E; ++I) {
8287         const FieldDecl *OuterField = *I;
8288         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8289           << OuterField->getType();
8290       }
8291 
8292       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8293         << QT->isPointerType()
8294         << QT;
8295       D.setInvalidType();
8296       return;
8297     }
8298   } while (!VisitStack.empty());
8299 }
8300 
8301 /// Find the DeclContext in which a tag is implicitly declared if we see an
8302 /// elaborated type specifier in the specified context, and lookup finds
8303 /// nothing.
8304 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8305   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8306     DC = DC->getParent();
8307   return DC;
8308 }
8309 
8310 /// Find the Scope in which a tag is implicitly declared if we see an
8311 /// elaborated type specifier in the specified context, and lookup finds
8312 /// nothing.
8313 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8314   while (S->isClassScope() ||
8315          (LangOpts.CPlusPlus &&
8316           S->isFunctionPrototypeScope()) ||
8317          ((S->getFlags() & Scope::DeclScope) == 0) ||
8318          (S->getEntity() && S->getEntity()->isTransparentContext()))
8319     S = S->getParent();
8320   return S;
8321 }
8322 
8323 NamedDecl*
8324 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8325                               TypeSourceInfo *TInfo, LookupResult &Previous,
8326                               MultiTemplateParamsArg TemplateParamLists,
8327                               bool &AddToScope) {
8328   QualType R = TInfo->getType();
8329 
8330   assert(R->isFunctionType());
8331 
8332   // TODO: consider using NameInfo for diagnostic.
8333   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8334   DeclarationName Name = NameInfo.getName();
8335   StorageClass SC = getFunctionStorageClass(*this, D);
8336 
8337   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8338     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8339          diag::err_invalid_thread)
8340       << DeclSpec::getSpecifierName(TSCS);
8341 
8342   if (D.isFirstDeclarationOfMember())
8343     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8344                            D.getIdentifierLoc());
8345 
8346   bool isFriend = false;
8347   FunctionTemplateDecl *FunctionTemplate = nullptr;
8348   bool isMemberSpecialization = false;
8349   bool isFunctionTemplateSpecialization = false;
8350 
8351   bool isDependentClassScopeExplicitSpecialization = false;
8352   bool HasExplicitTemplateArgs = false;
8353   TemplateArgumentListInfo TemplateArgs;
8354 
8355   bool isVirtualOkay = false;
8356 
8357   DeclContext *OriginalDC = DC;
8358   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8359 
8360   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8361                                               isVirtualOkay);
8362   if (!NewFD) return nullptr;
8363 
8364   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8365     NewFD->setTopLevelDeclInObjCContainer();
8366 
8367   // Set the lexical context. If this is a function-scope declaration, or has a
8368   // C++ scope specifier, or is the object of a friend declaration, the lexical
8369   // context will be different from the semantic context.
8370   NewFD->setLexicalDeclContext(CurContext);
8371 
8372   if (IsLocalExternDecl)
8373     NewFD->setLocalExternDecl();
8374 
8375   if (getLangOpts().CPlusPlus) {
8376     bool isInline = D.getDeclSpec().isInlineSpecified();
8377     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8378     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8379     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8380     isFriend = D.getDeclSpec().isFriendSpecified();
8381     if (isFriend && !isInline && D.isFunctionDefinition()) {
8382       // C++ [class.friend]p5
8383       //   A function can be defined in a friend declaration of a
8384       //   class . . . . Such a function is implicitly inline.
8385       NewFD->setImplicitlyInline();
8386     }
8387 
8388     // If this is a method defined in an __interface, and is not a constructor
8389     // or an overloaded operator, then set the pure flag (isVirtual will already
8390     // return true).
8391     if (const CXXRecordDecl *Parent =
8392           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8393       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8394         NewFD->setPure(true);
8395 
8396       // C++ [class.union]p2
8397       //   A union can have member functions, but not virtual functions.
8398       if (isVirtual && Parent->isUnion())
8399         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8400     }
8401 
8402     SetNestedNameSpecifier(*this, NewFD, D);
8403     isMemberSpecialization = false;
8404     isFunctionTemplateSpecialization = false;
8405     if (D.isInvalidType())
8406       NewFD->setInvalidDecl();
8407 
8408     // Match up the template parameter lists with the scope specifier, then
8409     // determine whether we have a template or a template specialization.
8410     bool Invalid = false;
8411     if (TemplateParameterList *TemplateParams =
8412             MatchTemplateParametersToScopeSpecifier(
8413                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8414                 D.getCXXScopeSpec(),
8415                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8416                     ? D.getName().TemplateId
8417                     : nullptr,
8418                 TemplateParamLists, isFriend, isMemberSpecialization,
8419                 Invalid)) {
8420       if (TemplateParams->size() > 0) {
8421         // This is a function template
8422 
8423         // Check that we can declare a template here.
8424         if (CheckTemplateDeclScope(S, TemplateParams))
8425           NewFD->setInvalidDecl();
8426 
8427         // A destructor cannot be a template.
8428         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8429           Diag(NewFD->getLocation(), diag::err_destructor_template);
8430           NewFD->setInvalidDecl();
8431         }
8432 
8433         // If we're adding a template to a dependent context, we may need to
8434         // rebuilding some of the types used within the template parameter list,
8435         // now that we know what the current instantiation is.
8436         if (DC->isDependentContext()) {
8437           ContextRAII SavedContext(*this, DC);
8438           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8439             Invalid = true;
8440         }
8441 
8442         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8443                                                         NewFD->getLocation(),
8444                                                         Name, TemplateParams,
8445                                                         NewFD);
8446         FunctionTemplate->setLexicalDeclContext(CurContext);
8447         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8448 
8449         // For source fidelity, store the other template param lists.
8450         if (TemplateParamLists.size() > 1) {
8451           NewFD->setTemplateParameterListsInfo(Context,
8452                                                TemplateParamLists.drop_back(1));
8453         }
8454       } else {
8455         // This is a function template specialization.
8456         isFunctionTemplateSpecialization = true;
8457         // For source fidelity, store all the template param lists.
8458         if (TemplateParamLists.size() > 0)
8459           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8460 
8461         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8462         if (isFriend) {
8463           // We want to remove the "template<>", found here.
8464           SourceRange RemoveRange = TemplateParams->getSourceRange();
8465 
8466           // If we remove the template<> and the name is not a
8467           // template-id, we're actually silently creating a problem:
8468           // the friend declaration will refer to an untemplated decl,
8469           // and clearly the user wants a template specialization.  So
8470           // we need to insert '<>' after the name.
8471           SourceLocation InsertLoc;
8472           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8473             InsertLoc = D.getName().getSourceRange().getEnd();
8474             InsertLoc = getLocForEndOfToken(InsertLoc);
8475           }
8476 
8477           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8478             << Name << RemoveRange
8479             << FixItHint::CreateRemoval(RemoveRange)
8480             << FixItHint::CreateInsertion(InsertLoc, "<>");
8481         }
8482       }
8483     } else {
8484       // All template param lists were matched against the scope specifier:
8485       // this is NOT (an explicit specialization of) a template.
8486       if (TemplateParamLists.size() > 0)
8487         // For source fidelity, store all the template param lists.
8488         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8489     }
8490 
8491     if (Invalid) {
8492       NewFD->setInvalidDecl();
8493       if (FunctionTemplate)
8494         FunctionTemplate->setInvalidDecl();
8495     }
8496 
8497     // C++ [dcl.fct.spec]p5:
8498     //   The virtual specifier shall only be used in declarations of
8499     //   nonstatic class member functions that appear within a
8500     //   member-specification of a class declaration; see 10.3.
8501     //
8502     if (isVirtual && !NewFD->isInvalidDecl()) {
8503       if (!isVirtualOkay) {
8504         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8505              diag::err_virtual_non_function);
8506       } else if (!CurContext->isRecord()) {
8507         // 'virtual' was specified outside of the class.
8508         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8509              diag::err_virtual_out_of_class)
8510           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8511       } else if (NewFD->getDescribedFunctionTemplate()) {
8512         // C++ [temp.mem]p3:
8513         //  A member function template shall not be virtual.
8514         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8515              diag::err_virtual_member_function_template)
8516           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8517       } else {
8518         // Okay: Add virtual to the method.
8519         NewFD->setVirtualAsWritten(true);
8520       }
8521 
8522       if (getLangOpts().CPlusPlus14 &&
8523           NewFD->getReturnType()->isUndeducedType())
8524         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8525     }
8526 
8527     if (getLangOpts().CPlusPlus14 &&
8528         (NewFD->isDependentContext() ||
8529          (isFriend && CurContext->isDependentContext())) &&
8530         NewFD->getReturnType()->isUndeducedType()) {
8531       // If the function template is referenced directly (for instance, as a
8532       // member of the current instantiation), pretend it has a dependent type.
8533       // This is not really justified by the standard, but is the only sane
8534       // thing to do.
8535       // FIXME: For a friend function, we have not marked the function as being
8536       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8537       const FunctionProtoType *FPT =
8538           NewFD->getType()->castAs<FunctionProtoType>();
8539       QualType Result =
8540           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8541       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8542                                              FPT->getExtProtoInfo()));
8543     }
8544 
8545     // C++ [dcl.fct.spec]p3:
8546     //  The inline specifier shall not appear on a block scope function
8547     //  declaration.
8548     if (isInline && !NewFD->isInvalidDecl()) {
8549       if (CurContext->isFunctionOrMethod()) {
8550         // 'inline' is not allowed on block scope function declaration.
8551         Diag(D.getDeclSpec().getInlineSpecLoc(),
8552              diag::err_inline_declaration_block_scope) << Name
8553           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8554       }
8555     }
8556 
8557     // C++ [dcl.fct.spec]p6:
8558     //  The explicit specifier shall be used only in the declaration of a
8559     //  constructor or conversion function within its class definition;
8560     //  see 12.3.1 and 12.3.2.
8561     if (isExplicit && !NewFD->isInvalidDecl() &&
8562         !isa<CXXDeductionGuideDecl>(NewFD)) {
8563       if (!CurContext->isRecord()) {
8564         // 'explicit' was specified outside of the class.
8565         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8566              diag::err_explicit_out_of_class)
8567           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8568       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8569                  !isa<CXXConversionDecl>(NewFD)) {
8570         // 'explicit' was specified on a function that wasn't a constructor
8571         // or conversion function.
8572         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8573              diag::err_explicit_non_ctor_or_conv_function)
8574           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8575       }
8576     }
8577 
8578     if (isConstexpr) {
8579       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8580       // are implicitly inline.
8581       NewFD->setImplicitlyInline();
8582 
8583       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8584       // be either constructors or to return a literal type. Therefore,
8585       // destructors cannot be declared constexpr.
8586       if (isa<CXXDestructorDecl>(NewFD))
8587         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8588     }
8589 
8590     // If __module_private__ was specified, mark the function accordingly.
8591     if (D.getDeclSpec().isModulePrivateSpecified()) {
8592       if (isFunctionTemplateSpecialization) {
8593         SourceLocation ModulePrivateLoc
8594           = D.getDeclSpec().getModulePrivateSpecLoc();
8595         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8596           << 0
8597           << FixItHint::CreateRemoval(ModulePrivateLoc);
8598       } else {
8599         NewFD->setModulePrivate();
8600         if (FunctionTemplate)
8601           FunctionTemplate->setModulePrivate();
8602       }
8603     }
8604 
8605     if (isFriend) {
8606       if (FunctionTemplate) {
8607         FunctionTemplate->setObjectOfFriendDecl();
8608         FunctionTemplate->setAccess(AS_public);
8609       }
8610       NewFD->setObjectOfFriendDecl();
8611       NewFD->setAccess(AS_public);
8612     }
8613 
8614     // If a function is defined as defaulted or deleted, mark it as such now.
8615     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8616     // definition kind to FDK_Definition.
8617     switch (D.getFunctionDefinitionKind()) {
8618       case FDK_Declaration:
8619       case FDK_Definition:
8620         break;
8621 
8622       case FDK_Defaulted:
8623         NewFD->setDefaulted();
8624         break;
8625 
8626       case FDK_Deleted:
8627         NewFD->setDeletedAsWritten();
8628         break;
8629     }
8630 
8631     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8632         D.isFunctionDefinition()) {
8633       // C++ [class.mfct]p2:
8634       //   A member function may be defined (8.4) in its class definition, in
8635       //   which case it is an inline member function (7.1.2)
8636       NewFD->setImplicitlyInline();
8637     }
8638 
8639     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8640         !CurContext->isRecord()) {
8641       // C++ [class.static]p1:
8642       //   A data or function member of a class may be declared static
8643       //   in a class definition, in which case it is a static member of
8644       //   the class.
8645 
8646       // Complain about the 'static' specifier if it's on an out-of-line
8647       // member function definition.
8648 
8649       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8650       // member function template declaration, warn about this.
8651       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8652            NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8653            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8654         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8655     }
8656 
8657     // C++11 [except.spec]p15:
8658     //   A deallocation function with no exception-specification is treated
8659     //   as if it were specified with noexcept(true).
8660     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8661     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8662          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8663         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8664       NewFD->setType(Context.getFunctionType(
8665           FPT->getReturnType(), FPT->getParamTypes(),
8666           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8667   }
8668 
8669   // Filter out previous declarations that don't match the scope.
8670   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8671                        D.getCXXScopeSpec().isNotEmpty() ||
8672                        isMemberSpecialization ||
8673                        isFunctionTemplateSpecialization);
8674 
8675   // Handle GNU asm-label extension (encoded as an attribute).
8676   if (Expr *E = (Expr*) D.getAsmLabel()) {
8677     // The parser guarantees this is a string.
8678     StringLiteral *SE = cast<StringLiteral>(E);
8679     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8680                                                 SE->getString(), 0));
8681   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8682     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8683       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8684     if (I != ExtnameUndeclaredIdentifiers.end()) {
8685       if (isDeclExternC(NewFD)) {
8686         NewFD->addAttr(I->second);
8687         ExtnameUndeclaredIdentifiers.erase(I);
8688       } else
8689         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8690             << /*Variable*/0 << NewFD;
8691     }
8692   }
8693 
8694   // Copy the parameter declarations from the declarator D to the function
8695   // declaration NewFD, if they are available.  First scavenge them into Params.
8696   SmallVector<ParmVarDecl*, 16> Params;
8697   unsigned FTIIdx;
8698   if (D.isFunctionDeclarator(FTIIdx)) {
8699     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8700 
8701     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8702     // function that takes no arguments, not a function that takes a
8703     // single void argument.
8704     // We let through "const void" here because Sema::GetTypeForDeclarator
8705     // already checks for that case.
8706     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8707       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8708         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8709         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8710         Param->setDeclContext(NewFD);
8711         Params.push_back(Param);
8712 
8713         if (Param->isInvalidDecl())
8714           NewFD->setInvalidDecl();
8715       }
8716     }
8717 
8718     if (!getLangOpts().CPlusPlus) {
8719       // In C, find all the tag declarations from the prototype and move them
8720       // into the function DeclContext. Remove them from the surrounding tag
8721       // injection context of the function, which is typically but not always
8722       // the TU.
8723       DeclContext *PrototypeTagContext =
8724           getTagInjectionContext(NewFD->getLexicalDeclContext());
8725       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8726         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8727 
8728         // We don't want to reparent enumerators. Look at their parent enum
8729         // instead.
8730         if (!TD) {
8731           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8732             TD = cast<EnumDecl>(ECD->getDeclContext());
8733         }
8734         if (!TD)
8735           continue;
8736         DeclContext *TagDC = TD->getLexicalDeclContext();
8737         if (!TagDC->containsDecl(TD))
8738           continue;
8739         TagDC->removeDecl(TD);
8740         TD->setDeclContext(NewFD);
8741         NewFD->addDecl(TD);
8742 
8743         // Preserve the lexical DeclContext if it is not the surrounding tag
8744         // injection context of the FD. In this example, the semantic context of
8745         // E will be f and the lexical context will be S, while both the
8746         // semantic and lexical contexts of S will be f:
8747         //   void f(struct S { enum E { a } f; } s);
8748         if (TagDC != PrototypeTagContext)
8749           TD->setLexicalDeclContext(TagDC);
8750       }
8751     }
8752   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8753     // When we're declaring a function with a typedef, typeof, etc as in the
8754     // following example, we'll need to synthesize (unnamed)
8755     // parameters for use in the declaration.
8756     //
8757     // @code
8758     // typedef void fn(int);
8759     // fn f;
8760     // @endcode
8761 
8762     // Synthesize a parameter for each argument type.
8763     for (const auto &AI : FT->param_types()) {
8764       ParmVarDecl *Param =
8765           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8766       Param->setScopeInfo(0, Params.size());
8767       Params.push_back(Param);
8768     }
8769   } else {
8770     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8771            "Should not need args for typedef of non-prototype fn");
8772   }
8773 
8774   // Finally, we know we have the right number of parameters, install them.
8775   NewFD->setParams(Params);
8776 
8777   if (D.getDeclSpec().isNoreturnSpecified())
8778     NewFD->addAttr(
8779         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8780                                        Context, 0));
8781 
8782   // Functions returning a variably modified type violate C99 6.7.5.2p2
8783   // because all functions have linkage.
8784   if (!NewFD->isInvalidDecl() &&
8785       NewFD->getReturnType()->isVariablyModifiedType()) {
8786     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8787     NewFD->setInvalidDecl();
8788   }
8789 
8790   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8791   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8792       !NewFD->hasAttr<SectionAttr>()) {
8793     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8794                                                  PragmaClangTextSection.SectionName,
8795                                                  PragmaClangTextSection.PragmaLocation));
8796   }
8797 
8798   // Apply an implicit SectionAttr if #pragma code_seg is active.
8799   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8800       !NewFD->hasAttr<SectionAttr>()) {
8801     NewFD->addAttr(
8802         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8803                                     CodeSegStack.CurrentValue->getString(),
8804                                     CodeSegStack.CurrentPragmaLocation));
8805     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8806                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8807                          ASTContext::PSF_Read,
8808                      NewFD))
8809       NewFD->dropAttr<SectionAttr>();
8810   }
8811 
8812   // Apply an implicit CodeSegAttr from class declspec or
8813   // apply an implicit SectionAttr from #pragma code_seg if active.
8814   if (!NewFD->hasAttr<CodeSegAttr>()) {
8815     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8816                                                                  D.isFunctionDefinition())) {
8817       NewFD->addAttr(SAttr);
8818     }
8819   }
8820 
8821   // Handle attributes.
8822   ProcessDeclAttributes(S, NewFD, D);
8823 
8824   if (getLangOpts().OpenCL) {
8825     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8826     // type declaration will generate a compilation error.
8827     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8828     if (AddressSpace != LangAS::Default) {
8829       Diag(NewFD->getLocation(),
8830            diag::err_opencl_return_value_with_address_space);
8831       NewFD->setInvalidDecl();
8832     }
8833   }
8834 
8835   if (!getLangOpts().CPlusPlus) {
8836     // Perform semantic checking on the function declaration.
8837     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8838       CheckMain(NewFD, D.getDeclSpec());
8839 
8840     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8841       CheckMSVCRTEntryPoint(NewFD);
8842 
8843     if (!NewFD->isInvalidDecl())
8844       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8845                                                   isMemberSpecialization));
8846     else if (!Previous.empty())
8847       // Recover gracefully from an invalid redeclaration.
8848       D.setRedeclaration(true);
8849     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8850             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8851            "previous declaration set still overloaded");
8852 
8853     // Diagnose no-prototype function declarations with calling conventions that
8854     // don't support variadic calls. Only do this in C and do it after merging
8855     // possibly prototyped redeclarations.
8856     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8857     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8858       CallingConv CC = FT->getExtInfo().getCC();
8859       if (!supportsVariadicCall(CC)) {
8860         // Windows system headers sometimes accidentally use stdcall without
8861         // (void) parameters, so we relax this to a warning.
8862         int DiagID =
8863             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8864         Diag(NewFD->getLocation(), DiagID)
8865             << FunctionType::getNameForCallConv(CC);
8866       }
8867     }
8868   } else {
8869     // C++11 [replacement.functions]p3:
8870     //  The program's definitions shall not be specified as inline.
8871     //
8872     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8873     //
8874     // Suppress the diagnostic if the function is __attribute__((used)), since
8875     // that forces an external definition to be emitted.
8876     if (D.getDeclSpec().isInlineSpecified() &&
8877         NewFD->isReplaceableGlobalAllocationFunction() &&
8878         !NewFD->hasAttr<UsedAttr>())
8879       Diag(D.getDeclSpec().getInlineSpecLoc(),
8880            diag::ext_operator_new_delete_declared_inline)
8881         << NewFD->getDeclName();
8882 
8883     // If the declarator is a template-id, translate the parser's template
8884     // argument list into our AST format.
8885     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8886       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8887       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8888       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8889       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8890                                          TemplateId->NumArgs);
8891       translateTemplateArguments(TemplateArgsPtr,
8892                                  TemplateArgs);
8893 
8894       HasExplicitTemplateArgs = true;
8895 
8896       if (NewFD->isInvalidDecl()) {
8897         HasExplicitTemplateArgs = false;
8898       } else if (FunctionTemplate) {
8899         // Function template with explicit template arguments.
8900         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8901           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8902 
8903         HasExplicitTemplateArgs = false;
8904       } else {
8905         assert((isFunctionTemplateSpecialization ||
8906                 D.getDeclSpec().isFriendSpecified()) &&
8907                "should have a 'template<>' for this decl");
8908         // "friend void foo<>(int);" is an implicit specialization decl.
8909         isFunctionTemplateSpecialization = true;
8910       }
8911     } else if (isFriend && isFunctionTemplateSpecialization) {
8912       // This combination is only possible in a recovery case;  the user
8913       // wrote something like:
8914       //   template <> friend void foo(int);
8915       // which we're recovering from as if the user had written:
8916       //   friend void foo<>(int);
8917       // Go ahead and fake up a template id.
8918       HasExplicitTemplateArgs = true;
8919       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8920       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8921     }
8922 
8923     // We do not add HD attributes to specializations here because
8924     // they may have different constexpr-ness compared to their
8925     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8926     // may end up with different effective targets. Instead, a
8927     // specialization inherits its target attributes from its template
8928     // in the CheckFunctionTemplateSpecialization() call below.
8929     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8930       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8931 
8932     // If it's a friend (and only if it's a friend), it's possible
8933     // that either the specialized function type or the specialized
8934     // template is dependent, and therefore matching will fail.  In
8935     // this case, don't check the specialization yet.
8936     bool InstantiationDependent = false;
8937     if (isFunctionTemplateSpecialization && isFriend &&
8938         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8939          TemplateSpecializationType::anyDependentTemplateArguments(
8940             TemplateArgs,
8941             InstantiationDependent))) {
8942       assert(HasExplicitTemplateArgs &&
8943              "friend function specialization without template args");
8944       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8945                                                        Previous))
8946         NewFD->setInvalidDecl();
8947     } else if (isFunctionTemplateSpecialization) {
8948       if (CurContext->isDependentContext() && CurContext->isRecord()
8949           && !isFriend) {
8950         isDependentClassScopeExplicitSpecialization = true;
8951       } else if (!NewFD->isInvalidDecl() &&
8952                  CheckFunctionTemplateSpecialization(
8953                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8954                      Previous))
8955         NewFD->setInvalidDecl();
8956 
8957       // C++ [dcl.stc]p1:
8958       //   A storage-class-specifier shall not be specified in an explicit
8959       //   specialization (14.7.3)
8960       FunctionTemplateSpecializationInfo *Info =
8961           NewFD->getTemplateSpecializationInfo();
8962       if (Info && SC != SC_None) {
8963         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8964           Diag(NewFD->getLocation(),
8965                diag::err_explicit_specialization_inconsistent_storage_class)
8966             << SC
8967             << FixItHint::CreateRemoval(
8968                                       D.getDeclSpec().getStorageClassSpecLoc());
8969 
8970         else
8971           Diag(NewFD->getLocation(),
8972                diag::ext_explicit_specialization_storage_class)
8973             << FixItHint::CreateRemoval(
8974                                       D.getDeclSpec().getStorageClassSpecLoc());
8975       }
8976     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8977       if (CheckMemberSpecialization(NewFD, Previous))
8978           NewFD->setInvalidDecl();
8979     }
8980 
8981     // Perform semantic checking on the function declaration.
8982     if (!isDependentClassScopeExplicitSpecialization) {
8983       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8984         CheckMain(NewFD, D.getDeclSpec());
8985 
8986       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8987         CheckMSVCRTEntryPoint(NewFD);
8988 
8989       if (!NewFD->isInvalidDecl())
8990         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8991                                                     isMemberSpecialization));
8992       else if (!Previous.empty())
8993         // Recover gracefully from an invalid redeclaration.
8994         D.setRedeclaration(true);
8995     }
8996 
8997     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8998             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8999            "previous declaration set still overloaded");
9000 
9001     NamedDecl *PrincipalDecl = (FunctionTemplate
9002                                 ? cast<NamedDecl>(FunctionTemplate)
9003                                 : NewFD);
9004 
9005     if (isFriend && NewFD->getPreviousDecl()) {
9006       AccessSpecifier Access = AS_public;
9007       if (!NewFD->isInvalidDecl())
9008         Access = NewFD->getPreviousDecl()->getAccess();
9009 
9010       NewFD->setAccess(Access);
9011       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9012     }
9013 
9014     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9015         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9016       PrincipalDecl->setNonMemberOperator();
9017 
9018     // If we have a function template, check the template parameter
9019     // list. This will check and merge default template arguments.
9020     if (FunctionTemplate) {
9021       FunctionTemplateDecl *PrevTemplate =
9022                                      FunctionTemplate->getPreviousDecl();
9023       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9024                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9025                                     : nullptr,
9026                             D.getDeclSpec().isFriendSpecified()
9027                               ? (D.isFunctionDefinition()
9028                                    ? TPC_FriendFunctionTemplateDefinition
9029                                    : TPC_FriendFunctionTemplate)
9030                               : (D.getCXXScopeSpec().isSet() &&
9031                                  DC && DC->isRecord() &&
9032                                  DC->isDependentContext())
9033                                   ? TPC_ClassTemplateMember
9034                                   : TPC_FunctionTemplate);
9035     }
9036 
9037     if (NewFD->isInvalidDecl()) {
9038       // Ignore all the rest of this.
9039     } else if (!D.isRedeclaration()) {
9040       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9041                                        AddToScope };
9042       // Fake up an access specifier if it's supposed to be a class member.
9043       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9044         NewFD->setAccess(AS_public);
9045 
9046       // Qualified decls generally require a previous declaration.
9047       if (D.getCXXScopeSpec().isSet()) {
9048         // ...with the major exception of templated-scope or
9049         // dependent-scope friend declarations.
9050 
9051         // TODO: we currently also suppress this check in dependent
9052         // contexts because (1) the parameter depth will be off when
9053         // matching friend templates and (2) we might actually be
9054         // selecting a friend based on a dependent factor.  But there
9055         // are situations where these conditions don't apply and we
9056         // can actually do this check immediately.
9057         //
9058         // Unless the scope is dependent, it's always an error if qualified
9059         // redeclaration lookup found nothing at all. Diagnose that now;
9060         // nothing will diagnose that error later.
9061         if (isFriend &&
9062             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9063              (!Previous.empty() && (TemplateParamLists.size() ||
9064                                     CurContext->isDependentContext())))) {
9065           // ignore these
9066         } else {
9067           // The user tried to provide an out-of-line definition for a
9068           // function that is a member of a class or namespace, but there
9069           // was no such member function declared (C++ [class.mfct]p2,
9070           // C++ [namespace.memdef]p2). For example:
9071           //
9072           // class X {
9073           //   void f() const;
9074           // };
9075           //
9076           // void X::f() { } // ill-formed
9077           //
9078           // Complain about this problem, and attempt to suggest close
9079           // matches (e.g., those that differ only in cv-qualifiers and
9080           // whether the parameter types are references).
9081 
9082           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9083                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9084             AddToScope = ExtraArgs.AddToScope;
9085             return Result;
9086           }
9087         }
9088 
9089         // Unqualified local friend declarations are required to resolve
9090         // to something.
9091       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9092         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9093                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9094           AddToScope = ExtraArgs.AddToScope;
9095           return Result;
9096         }
9097       }
9098     } else if (!D.isFunctionDefinition() &&
9099                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9100                !isFriend && !isFunctionTemplateSpecialization &&
9101                !isMemberSpecialization) {
9102       // An out-of-line member function declaration must also be a
9103       // definition (C++ [class.mfct]p2).
9104       // Note that this is not the case for explicit specializations of
9105       // function templates or member functions of class templates, per
9106       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9107       // extension for compatibility with old SWIG code which likes to
9108       // generate them.
9109       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9110         << D.getCXXScopeSpec().getRange();
9111     }
9112   }
9113 
9114   ProcessPragmaWeak(S, NewFD);
9115   checkAttributesAfterMerging(*this, *NewFD);
9116 
9117   AddKnownFunctionAttributes(NewFD);
9118 
9119   if (NewFD->hasAttr<OverloadableAttr>() &&
9120       !NewFD->getType()->getAs<FunctionProtoType>()) {
9121     Diag(NewFD->getLocation(),
9122          diag::err_attribute_overloadable_no_prototype)
9123       << NewFD;
9124 
9125     // Turn this into a variadic function with no parameters.
9126     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9127     FunctionProtoType::ExtProtoInfo EPI(
9128         Context.getDefaultCallingConvention(true, false));
9129     EPI.Variadic = true;
9130     EPI.ExtInfo = FT->getExtInfo();
9131 
9132     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9133     NewFD->setType(R);
9134   }
9135 
9136   // If there's a #pragma GCC visibility in scope, and this isn't a class
9137   // member, set the visibility of this function.
9138   if (!DC->isRecord() && NewFD->isExternallyVisible())
9139     AddPushedVisibilityAttribute(NewFD);
9140 
9141   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9142   // marking the function.
9143   AddCFAuditedAttribute(NewFD);
9144 
9145   // If this is a function definition, check if we have to apply optnone due to
9146   // a pragma.
9147   if(D.isFunctionDefinition())
9148     AddRangeBasedOptnone(NewFD);
9149 
9150   // If this is the first declaration of an extern C variable, update
9151   // the map of such variables.
9152   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9153       isIncompleteDeclExternC(*this, NewFD))
9154     RegisterLocallyScopedExternCDecl(NewFD, S);
9155 
9156   // Set this FunctionDecl's range up to the right paren.
9157   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9158 
9159   if (D.isRedeclaration() && !Previous.empty()) {
9160     NamedDecl *Prev = Previous.getRepresentativeDecl();
9161     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9162                                    isMemberSpecialization ||
9163                                        isFunctionTemplateSpecialization,
9164                                    D.isFunctionDefinition());
9165   }
9166 
9167   if (getLangOpts().CUDA) {
9168     IdentifierInfo *II = NewFD->getIdentifier();
9169     if (II && II->isStr(getCudaConfigureFuncName()) &&
9170         !NewFD->isInvalidDecl() &&
9171         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9172       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9173         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9174             << getCudaConfigureFuncName();
9175       Context.setcudaConfigureCallDecl(NewFD);
9176     }
9177 
9178     // Variadic functions, other than a *declaration* of printf, are not allowed
9179     // in device-side CUDA code, unless someone passed
9180     // -fcuda-allow-variadic-functions.
9181     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9182         (NewFD->hasAttr<CUDADeviceAttr>() ||
9183          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9184         !(II && II->isStr("printf") && NewFD->isExternC() &&
9185           !D.isFunctionDefinition())) {
9186       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9187     }
9188   }
9189 
9190   MarkUnusedFileScopedDecl(NewFD);
9191 
9192   if (getLangOpts().CPlusPlus) {
9193     if (FunctionTemplate) {
9194       if (NewFD->isInvalidDecl())
9195         FunctionTemplate->setInvalidDecl();
9196       return FunctionTemplate;
9197     }
9198 
9199     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9200       CompleteMemberSpecialization(NewFD, Previous);
9201   }
9202 
9203   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9204     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9205     if ((getLangOpts().OpenCLVersion >= 120)
9206         && (SC == SC_Static)) {
9207       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9208       D.setInvalidType();
9209     }
9210 
9211     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9212     if (!NewFD->getReturnType()->isVoidType()) {
9213       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9214       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9215           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9216                                 : FixItHint());
9217       D.setInvalidType();
9218     }
9219 
9220     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9221     for (auto Param : NewFD->parameters())
9222       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9223   }
9224   for (const ParmVarDecl *Param : NewFD->parameters()) {
9225     QualType PT = Param->getType();
9226 
9227     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9228     // types.
9229     if (getLangOpts().OpenCLVersion >= 200) {
9230       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9231         QualType ElemTy = PipeTy->getElementType();
9232           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9233             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9234             D.setInvalidType();
9235           }
9236       }
9237     }
9238   }
9239 
9240   // Here we have an function template explicit specialization at class scope.
9241   // The actual specialization will be postponed to template instatiation
9242   // time via the ClassScopeFunctionSpecializationDecl node.
9243   if (isDependentClassScopeExplicitSpecialization) {
9244     ClassScopeFunctionSpecializationDecl *NewSpec =
9245                          ClassScopeFunctionSpecializationDecl::Create(
9246                                 Context, CurContext, NewFD->getLocation(),
9247                                 cast<CXXMethodDecl>(NewFD),
9248                                 HasExplicitTemplateArgs, TemplateArgs);
9249     CurContext->addDecl(NewSpec);
9250     AddToScope = false;
9251   }
9252 
9253   // Diagnose availability attributes. Availability cannot be used on functions
9254   // that are run during load/unload.
9255   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9256     if (NewFD->hasAttr<ConstructorAttr>()) {
9257       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9258           << 1;
9259       NewFD->dropAttr<AvailabilityAttr>();
9260     }
9261     if (NewFD->hasAttr<DestructorAttr>()) {
9262       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9263           << 2;
9264       NewFD->dropAttr<AvailabilityAttr>();
9265     }
9266   }
9267 
9268   return NewFD;
9269 }
9270 
9271 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9272 /// when __declspec(code_seg) "is applied to a class, all member functions of
9273 /// the class and nested classes -- this includes compiler-generated special
9274 /// member functions -- are put in the specified segment."
9275 /// The actual behavior is a little more complicated. The Microsoft compiler
9276 /// won't check outer classes if there is an active value from #pragma code_seg.
9277 /// The CodeSeg is always applied from the direct parent but only from outer
9278 /// classes when the #pragma code_seg stack is empty. See:
9279 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9280 /// available since MS has removed the page.
9281 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9282   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9283   if (!Method)
9284     return nullptr;
9285   const CXXRecordDecl *Parent = Method->getParent();
9286   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9287     Attr *NewAttr = SAttr->clone(S.getASTContext());
9288     NewAttr->setImplicit(true);
9289     return NewAttr;
9290   }
9291 
9292   // The Microsoft compiler won't check outer classes for the CodeSeg
9293   // when the #pragma code_seg stack is active.
9294   if (S.CodeSegStack.CurrentValue)
9295    return nullptr;
9296 
9297   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9298     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9299       Attr *NewAttr = SAttr->clone(S.getASTContext());
9300       NewAttr->setImplicit(true);
9301       return NewAttr;
9302     }
9303   }
9304   return nullptr;
9305 }
9306 
9307 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9308 /// containing class. Otherwise it will return implicit SectionAttr if the
9309 /// function is a definition and there is an active value on CodeSegStack
9310 /// (from the current #pragma code-seg value).
9311 ///
9312 /// \param FD Function being declared.
9313 /// \param IsDefinition Whether it is a definition or just a declarartion.
9314 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9315 ///          nullptr if no attribute should be added.
9316 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9317                                                        bool IsDefinition) {
9318   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9319     return A;
9320   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9321       CodeSegStack.CurrentValue) {
9322     return SectionAttr::CreateImplicit(getASTContext(),
9323                                        SectionAttr::Declspec_allocate,
9324                                        CodeSegStack.CurrentValue->getString(),
9325                                        CodeSegStack.CurrentPragmaLocation);
9326   }
9327   return nullptr;
9328 }
9329 
9330 /// Determines if we can perform a correct type check for \p D as a
9331 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9332 /// best-effort check.
9333 ///
9334 /// \param NewD The new declaration.
9335 /// \param OldD The old declaration.
9336 /// \param NewT The portion of the type of the new declaration to check.
9337 /// \param OldT The portion of the type of the old declaration to check.
9338 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9339                                           QualType NewT, QualType OldT) {
9340   if (!NewD->getLexicalDeclContext()->isDependentContext())
9341     return true;
9342 
9343   // For dependently-typed local extern declarations and friends, we can't
9344   // perform a correct type check in general until instantiation:
9345   //
9346   //   int f();
9347   //   template<typename T> void g() { T f(); }
9348   //
9349   // (valid if g() is only instantiated with T = int).
9350   if (NewT->isDependentType() &&
9351       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9352     return false;
9353 
9354   // Similarly, if the previous declaration was a dependent local extern
9355   // declaration, we don't really know its type yet.
9356   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9357     return false;
9358 
9359   return true;
9360 }
9361 
9362 /// Checks if the new declaration declared in dependent context must be
9363 /// put in the same redeclaration chain as the specified declaration.
9364 ///
9365 /// \param D Declaration that is checked.
9366 /// \param PrevDecl Previous declaration found with proper lookup method for the
9367 ///                 same declaration name.
9368 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9369 ///          belongs to.
9370 ///
9371 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9372   if (!D->getLexicalDeclContext()->isDependentContext())
9373     return true;
9374 
9375   // Don't chain dependent friend function definitions until instantiation, to
9376   // permit cases like
9377   //
9378   //   void func();
9379   //   template<typename T> class C1 { friend void func() {} };
9380   //   template<typename T> class C2 { friend void func() {} };
9381   //
9382   // ... which is valid if only one of C1 and C2 is ever instantiated.
9383   //
9384   // FIXME: This need only apply to function definitions. For now, we proxy
9385   // this by checking for a file-scope function. We do not want this to apply
9386   // to friend declarations nominating member functions, because that gets in
9387   // the way of access checks.
9388   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9389     return false;
9390 
9391   auto *VD = dyn_cast<ValueDecl>(D);
9392   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9393   return !VD || !PrevVD ||
9394          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9395                                         PrevVD->getType());
9396 }
9397 
9398 /// Check the target attribute of the function for MultiVersion
9399 /// validity.
9400 ///
9401 /// Returns true if there was an error, false otherwise.
9402 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9403   const auto *TA = FD->getAttr<TargetAttr>();
9404   assert(TA && "MultiVersion Candidate requires a target attribute");
9405   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9406   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9407   enum ErrType { Feature = 0, Architecture = 1 };
9408 
9409   if (!ParseInfo.Architecture.empty() &&
9410       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9411     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9412         << Architecture << ParseInfo.Architecture;
9413     return true;
9414   }
9415 
9416   for (const auto &Feat : ParseInfo.Features) {
9417     auto BareFeat = StringRef{Feat}.substr(1);
9418     if (Feat[0] == '-') {
9419       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9420           << Feature << ("no-" + BareFeat).str();
9421       return true;
9422     }
9423 
9424     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9425         !TargetInfo.isValidFeatureName(BareFeat)) {
9426       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9427           << Feature << BareFeat;
9428       return true;
9429     }
9430   }
9431   return false;
9432 }
9433 
9434 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9435                                          MultiVersionKind MVType) {
9436   for (const Attr *A : FD->attrs()) {
9437     switch (A->getKind()) {
9438     case attr::CPUDispatch:
9439     case attr::CPUSpecific:
9440       if (MVType != MultiVersionKind::CPUDispatch &&
9441           MVType != MultiVersionKind::CPUSpecific)
9442         return true;
9443       break;
9444     case attr::Target:
9445       if (MVType != MultiVersionKind::Target)
9446         return true;
9447       break;
9448     default:
9449       return true;
9450     }
9451   }
9452   return false;
9453 }
9454 
9455 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9456                                              const FunctionDecl *NewFD,
9457                                              bool CausesMV,
9458                                              MultiVersionKind MVType) {
9459   enum DoesntSupport {
9460     FuncTemplates = 0,
9461     VirtFuncs = 1,
9462     DeducedReturn = 2,
9463     Constructors = 3,
9464     Destructors = 4,
9465     DeletedFuncs = 5,
9466     DefaultedFuncs = 6,
9467     ConstexprFuncs = 7,
9468   };
9469   enum Different {
9470     CallingConv = 0,
9471     ReturnType = 1,
9472     ConstexprSpec = 2,
9473     InlineSpec = 3,
9474     StorageClass = 4,
9475     Linkage = 5
9476   };
9477 
9478   bool IsCPUSpecificCPUDispatchMVType =
9479       MVType == MultiVersionKind::CPUDispatch ||
9480       MVType == MultiVersionKind::CPUSpecific;
9481 
9482   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9483     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9484     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9485     return true;
9486   }
9487 
9488   if (!NewFD->getType()->getAs<FunctionProtoType>())
9489     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9490 
9491   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9492     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9493     if (OldFD)
9494       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9495     return true;
9496   }
9497 
9498   // For now, disallow all other attributes.  These should be opt-in, but
9499   // an analysis of all of them is a future FIXME.
9500   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9501     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9502         << IsCPUSpecificCPUDispatchMVType;
9503     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9504     return true;
9505   }
9506 
9507   if (HasNonMultiVersionAttributes(NewFD, MVType))
9508     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9509            << IsCPUSpecificCPUDispatchMVType;
9510 
9511   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9512     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9513            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9514 
9515   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9516     if (NewCXXFD->isVirtual())
9517       return S.Diag(NewCXXFD->getLocation(),
9518                     diag::err_multiversion_doesnt_support)
9519              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9520 
9521     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9522       return S.Diag(NewCXXCtor->getLocation(),
9523                     diag::err_multiversion_doesnt_support)
9524              << IsCPUSpecificCPUDispatchMVType << Constructors;
9525 
9526     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9527       return S.Diag(NewCXXDtor->getLocation(),
9528                     diag::err_multiversion_doesnt_support)
9529              << IsCPUSpecificCPUDispatchMVType << Destructors;
9530   }
9531 
9532   if (NewFD->isDeleted())
9533     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9534            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9535 
9536   if (NewFD->isDefaulted())
9537     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9538            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9539 
9540   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9541                                MVType == MultiVersionKind::CPUSpecific))
9542     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9543            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9544 
9545   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9546   const auto *NewType = cast<FunctionType>(NewQType);
9547   QualType NewReturnType = NewType->getReturnType();
9548 
9549   if (NewReturnType->isUndeducedType())
9550     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9551            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9552 
9553   // Only allow transition to MultiVersion if it hasn't been used.
9554   if (OldFD && CausesMV && OldFD->isUsed(false))
9555     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9556 
9557   // Ensure the return type is identical.
9558   if (OldFD) {
9559     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9560     const auto *OldType = cast<FunctionType>(OldQType);
9561     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9562     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9563 
9564     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9565       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9566              << CallingConv;
9567 
9568     QualType OldReturnType = OldType->getReturnType();
9569 
9570     if (OldReturnType != NewReturnType)
9571       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9572              << ReturnType;
9573 
9574     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9575       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9576              << ConstexprSpec;
9577 
9578     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9579       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9580              << InlineSpec;
9581 
9582     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9583       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9584              << StorageClass;
9585 
9586     if (OldFD->isExternC() != NewFD->isExternC())
9587       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9588              << Linkage;
9589 
9590     if (S.CheckEquivalentExceptionSpec(
9591             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9592             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9593       return true;
9594   }
9595   return false;
9596 }
9597 
9598 /// Check the validity of a multiversion function declaration that is the
9599 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9600 ///
9601 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9602 ///
9603 /// Returns true if there was an error, false otherwise.
9604 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9605                                            MultiVersionKind MVType,
9606                                            const TargetAttr *TA,
9607                                            const CPUDispatchAttr *CPUDisp,
9608                                            const CPUSpecificAttr *CPUSpec) {
9609   assert(MVType != MultiVersionKind::None &&
9610          "Function lacks multiversion attribute");
9611 
9612   // Target only causes MV if it is default, otherwise this is a normal
9613   // function.
9614   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9615     return false;
9616 
9617   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9618     FD->setInvalidDecl();
9619     return true;
9620   }
9621 
9622   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9623     FD->setInvalidDecl();
9624     return true;
9625   }
9626 
9627   FD->setIsMultiVersion();
9628   return false;
9629 }
9630 
9631 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9632   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9633     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9634       return true;
9635   }
9636 
9637   return false;
9638 }
9639 
9640 static bool CheckTargetCausesMultiVersioning(
9641     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9642     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9643     LookupResult &Previous) {
9644   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9645   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9646   // Sort order doesn't matter, it just needs to be consistent.
9647   llvm::sort(NewParsed.Features);
9648 
9649   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9650   // to change, this is a simple redeclaration.
9651   if (!NewTA->isDefaultVersion() &&
9652       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9653     return false;
9654 
9655   // Otherwise, this decl causes MultiVersioning.
9656   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9657     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9658     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9659     NewFD->setInvalidDecl();
9660     return true;
9661   }
9662 
9663   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9664                                        MultiVersionKind::Target)) {
9665     NewFD->setInvalidDecl();
9666     return true;
9667   }
9668 
9669   if (CheckMultiVersionValue(S, NewFD)) {
9670     NewFD->setInvalidDecl();
9671     return true;
9672   }
9673 
9674   // If this is 'default', permit the forward declaration.
9675   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9676     Redeclaration = true;
9677     OldDecl = OldFD;
9678     OldFD->setIsMultiVersion();
9679     NewFD->setIsMultiVersion();
9680     return false;
9681   }
9682 
9683   if (CheckMultiVersionValue(S, OldFD)) {
9684     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9685     NewFD->setInvalidDecl();
9686     return true;
9687   }
9688 
9689   TargetAttr::ParsedTargetAttr OldParsed =
9690       OldTA->parse(std::less<std::string>());
9691 
9692   if (OldParsed == NewParsed) {
9693     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9694     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9695     NewFD->setInvalidDecl();
9696     return true;
9697   }
9698 
9699   for (const auto *FD : OldFD->redecls()) {
9700     const auto *CurTA = FD->getAttr<TargetAttr>();
9701     // We allow forward declarations before ANY multiversioning attributes, but
9702     // nothing after the fact.
9703     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9704         (!CurTA || CurTA->isInherited())) {
9705       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9706           << 0;
9707       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9708       NewFD->setInvalidDecl();
9709       return true;
9710     }
9711   }
9712 
9713   OldFD->setIsMultiVersion();
9714   NewFD->setIsMultiVersion();
9715   Redeclaration = false;
9716   MergeTypeWithPrevious = false;
9717   OldDecl = nullptr;
9718   Previous.clear();
9719   return false;
9720 }
9721 
9722 /// Check the validity of a new function declaration being added to an existing
9723 /// multiversioned declaration collection.
9724 static bool CheckMultiVersionAdditionalDecl(
9725     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9726     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9727     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9728     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9729     LookupResult &Previous) {
9730 
9731   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9732   // Disallow mixing of multiversioning types.
9733   if ((OldMVType == MultiVersionKind::Target &&
9734        NewMVType != MultiVersionKind::Target) ||
9735       (NewMVType == MultiVersionKind::Target &&
9736        OldMVType != MultiVersionKind::Target)) {
9737     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9738     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9739     NewFD->setInvalidDecl();
9740     return true;
9741   }
9742 
9743   TargetAttr::ParsedTargetAttr NewParsed;
9744   if (NewTA) {
9745     NewParsed = NewTA->parse();
9746     llvm::sort(NewParsed.Features);
9747   }
9748 
9749   bool UseMemberUsingDeclRules =
9750       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9751 
9752   // Next, check ALL non-overloads to see if this is a redeclaration of a
9753   // previous member of the MultiVersion set.
9754   for (NamedDecl *ND : Previous) {
9755     FunctionDecl *CurFD = ND->getAsFunction();
9756     if (!CurFD)
9757       continue;
9758     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9759       continue;
9760 
9761     if (NewMVType == MultiVersionKind::Target) {
9762       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9763       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9764         NewFD->setIsMultiVersion();
9765         Redeclaration = true;
9766         OldDecl = ND;
9767         return false;
9768       }
9769 
9770       TargetAttr::ParsedTargetAttr CurParsed =
9771           CurTA->parse(std::less<std::string>());
9772       if (CurParsed == NewParsed) {
9773         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9774         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9775         NewFD->setInvalidDecl();
9776         return true;
9777       }
9778     } else {
9779       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9780       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9781       // Handle CPUDispatch/CPUSpecific versions.
9782       // Only 1 CPUDispatch function is allowed, this will make it go through
9783       // the redeclaration errors.
9784       if (NewMVType == MultiVersionKind::CPUDispatch &&
9785           CurFD->hasAttr<CPUDispatchAttr>()) {
9786         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9787             std::equal(
9788                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9789                 NewCPUDisp->cpus_begin(),
9790                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9791                   return Cur->getName() == New->getName();
9792                 })) {
9793           NewFD->setIsMultiVersion();
9794           Redeclaration = true;
9795           OldDecl = ND;
9796           return false;
9797         }
9798 
9799         // If the declarations don't match, this is an error condition.
9800         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9801         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9802         NewFD->setInvalidDecl();
9803         return true;
9804       }
9805       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9806 
9807         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9808             std::equal(
9809                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9810                 NewCPUSpec->cpus_begin(),
9811                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9812                   return Cur->getName() == New->getName();
9813                 })) {
9814           NewFD->setIsMultiVersion();
9815           Redeclaration = true;
9816           OldDecl = ND;
9817           return false;
9818         }
9819 
9820         // Only 1 version of CPUSpecific is allowed for each CPU.
9821         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9822           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9823             if (CurII == NewII) {
9824               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9825                   << NewII;
9826               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9827               NewFD->setInvalidDecl();
9828               return true;
9829             }
9830           }
9831         }
9832       }
9833       // If the two decls aren't the same MVType, there is no possible error
9834       // condition.
9835     }
9836   }
9837 
9838   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9839   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9840   // handled in the attribute adding step.
9841   if (NewMVType == MultiVersionKind::Target &&
9842       CheckMultiVersionValue(S, NewFD)) {
9843     NewFD->setInvalidDecl();
9844     return true;
9845   }
9846 
9847   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9848                                        !OldFD->isMultiVersion(), NewMVType)) {
9849     NewFD->setInvalidDecl();
9850     return true;
9851   }
9852 
9853   // Permit forward declarations in the case where these two are compatible.
9854   if (!OldFD->isMultiVersion()) {
9855     OldFD->setIsMultiVersion();
9856     NewFD->setIsMultiVersion();
9857     Redeclaration = true;
9858     OldDecl = OldFD;
9859     return false;
9860   }
9861 
9862   NewFD->setIsMultiVersion();
9863   Redeclaration = false;
9864   MergeTypeWithPrevious = false;
9865   OldDecl = nullptr;
9866   Previous.clear();
9867   return false;
9868 }
9869 
9870 
9871 /// Check the validity of a mulitversion function declaration.
9872 /// Also sets the multiversion'ness' of the function itself.
9873 ///
9874 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9875 ///
9876 /// Returns true if there was an error, false otherwise.
9877 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9878                                       bool &Redeclaration, NamedDecl *&OldDecl,
9879                                       bool &MergeTypeWithPrevious,
9880                                       LookupResult &Previous) {
9881   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9882   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9883   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9884 
9885   // Mixing Multiversioning types is prohibited.
9886   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9887       (NewCPUDisp && NewCPUSpec)) {
9888     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9889     NewFD->setInvalidDecl();
9890     return true;
9891   }
9892 
9893   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9894 
9895   // Main isn't allowed to become a multiversion function, however it IS
9896   // permitted to have 'main' be marked with the 'target' optimization hint.
9897   if (NewFD->isMain()) {
9898     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9899         MVType == MultiVersionKind::CPUDispatch ||
9900         MVType == MultiVersionKind::CPUSpecific) {
9901       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9902       NewFD->setInvalidDecl();
9903       return true;
9904     }
9905     return false;
9906   }
9907 
9908   if (!OldDecl || !OldDecl->getAsFunction() ||
9909       OldDecl->getDeclContext()->getRedeclContext() !=
9910           NewFD->getDeclContext()->getRedeclContext()) {
9911     // If there's no previous declaration, AND this isn't attempting to cause
9912     // multiversioning, this isn't an error condition.
9913     if (MVType == MultiVersionKind::None)
9914       return false;
9915     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9916                                           NewCPUSpec);
9917   }
9918 
9919   FunctionDecl *OldFD = OldDecl->getAsFunction();
9920 
9921   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9922     return false;
9923 
9924   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9925     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9926         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9927     NewFD->setInvalidDecl();
9928     return true;
9929   }
9930 
9931   // Handle the target potentially causes multiversioning case.
9932   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9933     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9934                                             Redeclaration, OldDecl,
9935                                             MergeTypeWithPrevious, Previous);
9936 
9937   // At this point, we have a multiversion function decl (in OldFD) AND an
9938   // appropriate attribute in the current function decl.  Resolve that these are
9939   // still compatible with previous declarations.
9940   return CheckMultiVersionAdditionalDecl(
9941       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9942       OldDecl, MergeTypeWithPrevious, Previous);
9943 }
9944 
9945 /// Perform semantic checking of a new function declaration.
9946 ///
9947 /// Performs semantic analysis of the new function declaration
9948 /// NewFD. This routine performs all semantic checking that does not
9949 /// require the actual declarator involved in the declaration, and is
9950 /// used both for the declaration of functions as they are parsed
9951 /// (called via ActOnDeclarator) and for the declaration of functions
9952 /// that have been instantiated via C++ template instantiation (called
9953 /// via InstantiateDecl).
9954 ///
9955 /// \param IsMemberSpecialization whether this new function declaration is
9956 /// a member specialization (that replaces any definition provided by the
9957 /// previous declaration).
9958 ///
9959 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9960 ///
9961 /// \returns true if the function declaration is a redeclaration.
9962 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9963                                     LookupResult &Previous,
9964                                     bool IsMemberSpecialization) {
9965   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9966          "Variably modified return types are not handled here");
9967 
9968   // Determine whether the type of this function should be merged with
9969   // a previous visible declaration. This never happens for functions in C++,
9970   // and always happens in C if the previous declaration was visible.
9971   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9972                                !Previous.isShadowed();
9973 
9974   bool Redeclaration = false;
9975   NamedDecl *OldDecl = nullptr;
9976   bool MayNeedOverloadableChecks = false;
9977 
9978   // Merge or overload the declaration with an existing declaration of
9979   // the same name, if appropriate.
9980   if (!Previous.empty()) {
9981     // Determine whether NewFD is an overload of PrevDecl or
9982     // a declaration that requires merging. If it's an overload,
9983     // there's no more work to do here; we'll just add the new
9984     // function to the scope.
9985     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9986       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9987       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9988         Redeclaration = true;
9989         OldDecl = Candidate;
9990       }
9991     } else {
9992       MayNeedOverloadableChecks = true;
9993       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9994                             /*NewIsUsingDecl*/ false)) {
9995       case Ovl_Match:
9996         Redeclaration = true;
9997         break;
9998 
9999       case Ovl_NonFunction:
10000         Redeclaration = true;
10001         break;
10002 
10003       case Ovl_Overload:
10004         Redeclaration = false;
10005         break;
10006       }
10007     }
10008   }
10009 
10010   // Check for a previous extern "C" declaration with this name.
10011   if (!Redeclaration &&
10012       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10013     if (!Previous.empty()) {
10014       // This is an extern "C" declaration with the same name as a previous
10015       // declaration, and thus redeclares that entity...
10016       Redeclaration = true;
10017       OldDecl = Previous.getFoundDecl();
10018       MergeTypeWithPrevious = false;
10019 
10020       // ... except in the presence of __attribute__((overloadable)).
10021       if (OldDecl->hasAttr<OverloadableAttr>() ||
10022           NewFD->hasAttr<OverloadableAttr>()) {
10023         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10024           MayNeedOverloadableChecks = true;
10025           Redeclaration = false;
10026           OldDecl = nullptr;
10027         }
10028       }
10029     }
10030   }
10031 
10032   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10033                                 MergeTypeWithPrevious, Previous))
10034     return Redeclaration;
10035 
10036   // C++11 [dcl.constexpr]p8:
10037   //   A constexpr specifier for a non-static member function that is not
10038   //   a constructor declares that member function to be const.
10039   //
10040   // This needs to be delayed until we know whether this is an out-of-line
10041   // definition of a static member function.
10042   //
10043   // This rule is not present in C++1y, so we produce a backwards
10044   // compatibility warning whenever it happens in C++11.
10045   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10046   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10047       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10048       !MD->getMethodQualifiers().hasConst()) {
10049     CXXMethodDecl *OldMD = nullptr;
10050     if (OldDecl)
10051       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10052     if (!OldMD || !OldMD->isStatic()) {
10053       const FunctionProtoType *FPT =
10054         MD->getType()->castAs<FunctionProtoType>();
10055       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10056       EPI.TypeQuals.addConst();
10057       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10058                                           FPT->getParamTypes(), EPI));
10059 
10060       // Warn that we did this, if we're not performing template instantiation.
10061       // In that case, we'll have warned already when the template was defined.
10062       if (!inTemplateInstantiation()) {
10063         SourceLocation AddConstLoc;
10064         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10065                 .IgnoreParens().getAs<FunctionTypeLoc>())
10066           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10067 
10068         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10069           << FixItHint::CreateInsertion(AddConstLoc, " const");
10070       }
10071     }
10072   }
10073 
10074   if (Redeclaration) {
10075     // NewFD and OldDecl represent declarations that need to be
10076     // merged.
10077     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10078       NewFD->setInvalidDecl();
10079       return Redeclaration;
10080     }
10081 
10082     Previous.clear();
10083     Previous.addDecl(OldDecl);
10084 
10085     if (FunctionTemplateDecl *OldTemplateDecl =
10086             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10087       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10088       FunctionTemplateDecl *NewTemplateDecl
10089         = NewFD->getDescribedFunctionTemplate();
10090       assert(NewTemplateDecl && "Template/non-template mismatch");
10091 
10092       // The call to MergeFunctionDecl above may have created some state in
10093       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10094       // can add it as a redeclaration.
10095       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10096 
10097       NewFD->setPreviousDeclaration(OldFD);
10098       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10099       if (NewFD->isCXXClassMember()) {
10100         NewFD->setAccess(OldTemplateDecl->getAccess());
10101         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10102       }
10103 
10104       // If this is an explicit specialization of a member that is a function
10105       // template, mark it as a member specialization.
10106       if (IsMemberSpecialization &&
10107           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10108         NewTemplateDecl->setMemberSpecialization();
10109         assert(OldTemplateDecl->isMemberSpecialization());
10110         // Explicit specializations of a member template do not inherit deleted
10111         // status from the parent member template that they are specializing.
10112         if (OldFD->isDeleted()) {
10113           // FIXME: This assert will not hold in the presence of modules.
10114           assert(OldFD->getCanonicalDecl() == OldFD);
10115           // FIXME: We need an update record for this AST mutation.
10116           OldFD->setDeletedAsWritten(false);
10117         }
10118       }
10119 
10120     } else {
10121       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10122         auto *OldFD = cast<FunctionDecl>(OldDecl);
10123         // This needs to happen first so that 'inline' propagates.
10124         NewFD->setPreviousDeclaration(OldFD);
10125         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10126         if (NewFD->isCXXClassMember())
10127           NewFD->setAccess(OldFD->getAccess());
10128       }
10129     }
10130   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10131              !NewFD->getAttr<OverloadableAttr>()) {
10132     assert((Previous.empty() ||
10133             llvm::any_of(Previous,
10134                          [](const NamedDecl *ND) {
10135                            return ND->hasAttr<OverloadableAttr>();
10136                          })) &&
10137            "Non-redecls shouldn't happen without overloadable present");
10138 
10139     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10140       const auto *FD = dyn_cast<FunctionDecl>(ND);
10141       return FD && !FD->hasAttr<OverloadableAttr>();
10142     });
10143 
10144     if (OtherUnmarkedIter != Previous.end()) {
10145       Diag(NewFD->getLocation(),
10146            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10147       Diag((*OtherUnmarkedIter)->getLocation(),
10148            diag::note_attribute_overloadable_prev_overload)
10149           << false;
10150 
10151       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10152     }
10153   }
10154 
10155   // Semantic checking for this function declaration (in isolation).
10156 
10157   if (getLangOpts().CPlusPlus) {
10158     // C++-specific checks.
10159     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10160       CheckConstructor(Constructor);
10161     } else if (CXXDestructorDecl *Destructor =
10162                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10163       CXXRecordDecl *Record = Destructor->getParent();
10164       QualType ClassType = Context.getTypeDeclType(Record);
10165 
10166       // FIXME: Shouldn't we be able to perform this check even when the class
10167       // type is dependent? Both gcc and edg can handle that.
10168       if (!ClassType->isDependentType()) {
10169         DeclarationName Name
10170           = Context.DeclarationNames.getCXXDestructorName(
10171                                         Context.getCanonicalType(ClassType));
10172         if (NewFD->getDeclName() != Name) {
10173           Diag(NewFD->getLocation(), diag::err_destructor_name);
10174           NewFD->setInvalidDecl();
10175           return Redeclaration;
10176         }
10177       }
10178     } else if (CXXConversionDecl *Conversion
10179                = dyn_cast<CXXConversionDecl>(NewFD)) {
10180       ActOnConversionDeclarator(Conversion);
10181     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10182       if (auto *TD = Guide->getDescribedFunctionTemplate())
10183         CheckDeductionGuideTemplate(TD);
10184 
10185       // A deduction guide is not on the list of entities that can be
10186       // explicitly specialized.
10187       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10188         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10189             << /*explicit specialization*/ 1;
10190     }
10191 
10192     // Find any virtual functions that this function overrides.
10193     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10194       if (!Method->isFunctionTemplateSpecialization() &&
10195           !Method->getDescribedFunctionTemplate() &&
10196           Method->isCanonicalDecl()) {
10197         if (AddOverriddenMethods(Method->getParent(), Method)) {
10198           // If the function was marked as "static", we have a problem.
10199           if (NewFD->getStorageClass() == SC_Static) {
10200             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10201           }
10202         }
10203       }
10204 
10205       if (Method->isStatic())
10206         checkThisInStaticMemberFunctionType(Method);
10207     }
10208 
10209     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10210     if (NewFD->isOverloadedOperator() &&
10211         CheckOverloadedOperatorDeclaration(NewFD)) {
10212       NewFD->setInvalidDecl();
10213       return Redeclaration;
10214     }
10215 
10216     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10217     if (NewFD->getLiteralIdentifier() &&
10218         CheckLiteralOperatorDeclaration(NewFD)) {
10219       NewFD->setInvalidDecl();
10220       return Redeclaration;
10221     }
10222 
10223     // In C++, check default arguments now that we have merged decls. Unless
10224     // the lexical context is the class, because in this case this is done
10225     // during delayed parsing anyway.
10226     if (!CurContext->isRecord())
10227       CheckCXXDefaultArguments(NewFD);
10228 
10229     // If this function declares a builtin function, check the type of this
10230     // declaration against the expected type for the builtin.
10231     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10232       ASTContext::GetBuiltinTypeError Error;
10233       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10234       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10235       // If the type of the builtin differs only in its exception
10236       // specification, that's OK.
10237       // FIXME: If the types do differ in this way, it would be better to
10238       // retain the 'noexcept' form of the type.
10239       if (!T.isNull() &&
10240           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10241                                                             NewFD->getType()))
10242         // The type of this function differs from the type of the builtin,
10243         // so forget about the builtin entirely.
10244         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10245     }
10246 
10247     // If this function is declared as being extern "C", then check to see if
10248     // the function returns a UDT (class, struct, or union type) that is not C
10249     // compatible, and if it does, warn the user.
10250     // But, issue any diagnostic on the first declaration only.
10251     if (Previous.empty() && NewFD->isExternC()) {
10252       QualType R = NewFD->getReturnType();
10253       if (R->isIncompleteType() && !R->isVoidType())
10254         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10255             << NewFD << R;
10256       else if (!R.isPODType(Context) && !R->isVoidType() &&
10257                !R->isObjCObjectPointerType())
10258         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10259     }
10260 
10261     // C++1z [dcl.fct]p6:
10262     //   [...] whether the function has a non-throwing exception-specification
10263     //   [is] part of the function type
10264     //
10265     // This results in an ABI break between C++14 and C++17 for functions whose
10266     // declared type includes an exception-specification in a parameter or
10267     // return type. (Exception specifications on the function itself are OK in
10268     // most cases, and exception specifications are not permitted in most other
10269     // contexts where they could make it into a mangling.)
10270     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10271       auto HasNoexcept = [&](QualType T) -> bool {
10272         // Strip off declarator chunks that could be between us and a function
10273         // type. We don't need to look far, exception specifications are very
10274         // restricted prior to C++17.
10275         if (auto *RT = T->getAs<ReferenceType>())
10276           T = RT->getPointeeType();
10277         else if (T->isAnyPointerType())
10278           T = T->getPointeeType();
10279         else if (auto *MPT = T->getAs<MemberPointerType>())
10280           T = MPT->getPointeeType();
10281         if (auto *FPT = T->getAs<FunctionProtoType>())
10282           if (FPT->isNothrow())
10283             return true;
10284         return false;
10285       };
10286 
10287       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10288       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10289       for (QualType T : FPT->param_types())
10290         AnyNoexcept |= HasNoexcept(T);
10291       if (AnyNoexcept)
10292         Diag(NewFD->getLocation(),
10293              diag::warn_cxx17_compat_exception_spec_in_signature)
10294             << NewFD;
10295     }
10296 
10297     if (!Redeclaration && LangOpts.CUDA)
10298       checkCUDATargetOverload(NewFD, Previous);
10299   }
10300   return Redeclaration;
10301 }
10302 
10303 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10304   // C++11 [basic.start.main]p3:
10305   //   A program that [...] declares main to be inline, static or
10306   //   constexpr is ill-formed.
10307   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10308   //   appear in a declaration of main.
10309   // static main is not an error under C99, but we should warn about it.
10310   // We accept _Noreturn main as an extension.
10311   if (FD->getStorageClass() == SC_Static)
10312     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10313          ? diag::err_static_main : diag::warn_static_main)
10314       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10315   if (FD->isInlineSpecified())
10316     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10317       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10318   if (DS.isNoreturnSpecified()) {
10319     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10320     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10321     Diag(NoreturnLoc, diag::ext_noreturn_main);
10322     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10323       << FixItHint::CreateRemoval(NoreturnRange);
10324   }
10325   if (FD->isConstexpr()) {
10326     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10327       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10328     FD->setConstexpr(false);
10329   }
10330 
10331   if (getLangOpts().OpenCL) {
10332     Diag(FD->getLocation(), diag::err_opencl_no_main)
10333         << FD->hasAttr<OpenCLKernelAttr>();
10334     FD->setInvalidDecl();
10335     return;
10336   }
10337 
10338   QualType T = FD->getType();
10339   assert(T->isFunctionType() && "function decl is not of function type");
10340   const FunctionType* FT = T->castAs<FunctionType>();
10341 
10342   // Set default calling convention for main()
10343   if (FT->getCallConv() != CC_C) {
10344     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10345     FD->setType(QualType(FT, 0));
10346     T = Context.getCanonicalType(FD->getType());
10347   }
10348 
10349   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10350     // In C with GNU extensions we allow main() to have non-integer return
10351     // type, but we should warn about the extension, and we disable the
10352     // implicit-return-zero rule.
10353 
10354     // GCC in C mode accepts qualified 'int'.
10355     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10356       FD->setHasImplicitReturnZero(true);
10357     else {
10358       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10359       SourceRange RTRange = FD->getReturnTypeSourceRange();
10360       if (RTRange.isValid())
10361         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10362             << FixItHint::CreateReplacement(RTRange, "int");
10363     }
10364   } else {
10365     // In C and C++, main magically returns 0 if you fall off the end;
10366     // set the flag which tells us that.
10367     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10368 
10369     // All the standards say that main() should return 'int'.
10370     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10371       FD->setHasImplicitReturnZero(true);
10372     else {
10373       // Otherwise, this is just a flat-out error.
10374       SourceRange RTRange = FD->getReturnTypeSourceRange();
10375       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10376           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10377                                 : FixItHint());
10378       FD->setInvalidDecl(true);
10379     }
10380   }
10381 
10382   // Treat protoless main() as nullary.
10383   if (isa<FunctionNoProtoType>(FT)) return;
10384 
10385   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10386   unsigned nparams = FTP->getNumParams();
10387   assert(FD->getNumParams() == nparams);
10388 
10389   bool HasExtraParameters = (nparams > 3);
10390 
10391   if (FTP->isVariadic()) {
10392     Diag(FD->getLocation(), diag::ext_variadic_main);
10393     // FIXME: if we had information about the location of the ellipsis, we
10394     // could add a FixIt hint to remove it as a parameter.
10395   }
10396 
10397   // Darwin passes an undocumented fourth argument of type char**.  If
10398   // other platforms start sprouting these, the logic below will start
10399   // getting shifty.
10400   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10401     HasExtraParameters = false;
10402 
10403   if (HasExtraParameters) {
10404     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10405     FD->setInvalidDecl(true);
10406     nparams = 3;
10407   }
10408 
10409   // FIXME: a lot of the following diagnostics would be improved
10410   // if we had some location information about types.
10411 
10412   QualType CharPP =
10413     Context.getPointerType(Context.getPointerType(Context.CharTy));
10414   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10415 
10416   for (unsigned i = 0; i < nparams; ++i) {
10417     QualType AT = FTP->getParamType(i);
10418 
10419     bool mismatch = true;
10420 
10421     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10422       mismatch = false;
10423     else if (Expected[i] == CharPP) {
10424       // As an extension, the following forms are okay:
10425       //   char const **
10426       //   char const * const *
10427       //   char * const *
10428 
10429       QualifierCollector qs;
10430       const PointerType* PT;
10431       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10432           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10433           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10434                               Context.CharTy)) {
10435         qs.removeConst();
10436         mismatch = !qs.empty();
10437       }
10438     }
10439 
10440     if (mismatch) {
10441       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10442       // TODO: suggest replacing given type with expected type
10443       FD->setInvalidDecl(true);
10444     }
10445   }
10446 
10447   if (nparams == 1 && !FD->isInvalidDecl()) {
10448     Diag(FD->getLocation(), diag::warn_main_one_arg);
10449   }
10450 
10451   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10452     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10453     FD->setInvalidDecl();
10454   }
10455 }
10456 
10457 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10458   QualType T = FD->getType();
10459   assert(T->isFunctionType() && "function decl is not of function type");
10460   const FunctionType *FT = T->castAs<FunctionType>();
10461 
10462   // Set an implicit return of 'zero' if the function can return some integral,
10463   // enumeration, pointer or nullptr type.
10464   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10465       FT->getReturnType()->isAnyPointerType() ||
10466       FT->getReturnType()->isNullPtrType())
10467     // DllMain is exempt because a return value of zero means it failed.
10468     if (FD->getName() != "DllMain")
10469       FD->setHasImplicitReturnZero(true);
10470 
10471   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10472     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10473     FD->setInvalidDecl();
10474   }
10475 }
10476 
10477 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10478   // FIXME: Need strict checking.  In C89, we need to check for
10479   // any assignment, increment, decrement, function-calls, or
10480   // commas outside of a sizeof.  In C99, it's the same list,
10481   // except that the aforementioned are allowed in unevaluated
10482   // expressions.  Everything else falls under the
10483   // "may accept other forms of constant expressions" exception.
10484   // (We never end up here for C++, so the constant expression
10485   // rules there don't matter.)
10486   const Expr *Culprit;
10487   if (Init->isConstantInitializer(Context, false, &Culprit))
10488     return false;
10489   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10490     << Culprit->getSourceRange();
10491   return true;
10492 }
10493 
10494 namespace {
10495   // Visits an initialization expression to see if OrigDecl is evaluated in
10496   // its own initialization and throws a warning if it does.
10497   class SelfReferenceChecker
10498       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10499     Sema &S;
10500     Decl *OrigDecl;
10501     bool isRecordType;
10502     bool isPODType;
10503     bool isReferenceType;
10504 
10505     bool isInitList;
10506     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10507 
10508   public:
10509     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10510 
10511     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10512                                                     S(S), OrigDecl(OrigDecl) {
10513       isPODType = false;
10514       isRecordType = false;
10515       isReferenceType = false;
10516       isInitList = false;
10517       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10518         isPODType = VD->getType().isPODType(S.Context);
10519         isRecordType = VD->getType()->isRecordType();
10520         isReferenceType = VD->getType()->isReferenceType();
10521       }
10522     }
10523 
10524     // For most expressions, just call the visitor.  For initializer lists,
10525     // track the index of the field being initialized since fields are
10526     // initialized in order allowing use of previously initialized fields.
10527     void CheckExpr(Expr *E) {
10528       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10529       if (!InitList) {
10530         Visit(E);
10531         return;
10532       }
10533 
10534       // Track and increment the index here.
10535       isInitList = true;
10536       InitFieldIndex.push_back(0);
10537       for (auto Child : InitList->children()) {
10538         CheckExpr(cast<Expr>(Child));
10539         ++InitFieldIndex.back();
10540       }
10541       InitFieldIndex.pop_back();
10542     }
10543 
10544     // Returns true if MemberExpr is checked and no further checking is needed.
10545     // Returns false if additional checking is required.
10546     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10547       llvm::SmallVector<FieldDecl*, 4> Fields;
10548       Expr *Base = E;
10549       bool ReferenceField = false;
10550 
10551       // Get the field members used.
10552       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10553         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10554         if (!FD)
10555           return false;
10556         Fields.push_back(FD);
10557         if (FD->getType()->isReferenceType())
10558           ReferenceField = true;
10559         Base = ME->getBase()->IgnoreParenImpCasts();
10560       }
10561 
10562       // Keep checking only if the base Decl is the same.
10563       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10564       if (!DRE || DRE->getDecl() != OrigDecl)
10565         return false;
10566 
10567       // A reference field can be bound to an unininitialized field.
10568       if (CheckReference && !ReferenceField)
10569         return true;
10570 
10571       // Convert FieldDecls to their index number.
10572       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10573       for (const FieldDecl *I : llvm::reverse(Fields))
10574         UsedFieldIndex.push_back(I->getFieldIndex());
10575 
10576       // See if a warning is needed by checking the first difference in index
10577       // numbers.  If field being used has index less than the field being
10578       // initialized, then the use is safe.
10579       for (auto UsedIter = UsedFieldIndex.begin(),
10580                 UsedEnd = UsedFieldIndex.end(),
10581                 OrigIter = InitFieldIndex.begin(),
10582                 OrigEnd = InitFieldIndex.end();
10583            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10584         if (*UsedIter < *OrigIter)
10585           return true;
10586         if (*UsedIter > *OrigIter)
10587           break;
10588       }
10589 
10590       // TODO: Add a different warning which will print the field names.
10591       HandleDeclRefExpr(DRE);
10592       return true;
10593     }
10594 
10595     // For most expressions, the cast is directly above the DeclRefExpr.
10596     // For conditional operators, the cast can be outside the conditional
10597     // operator if both expressions are DeclRefExpr's.
10598     void HandleValue(Expr *E) {
10599       E = E->IgnoreParens();
10600       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10601         HandleDeclRefExpr(DRE);
10602         return;
10603       }
10604 
10605       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10606         Visit(CO->getCond());
10607         HandleValue(CO->getTrueExpr());
10608         HandleValue(CO->getFalseExpr());
10609         return;
10610       }
10611 
10612       if (BinaryConditionalOperator *BCO =
10613               dyn_cast<BinaryConditionalOperator>(E)) {
10614         Visit(BCO->getCond());
10615         HandleValue(BCO->getFalseExpr());
10616         return;
10617       }
10618 
10619       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10620         HandleValue(OVE->getSourceExpr());
10621         return;
10622       }
10623 
10624       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10625         if (BO->getOpcode() == BO_Comma) {
10626           Visit(BO->getLHS());
10627           HandleValue(BO->getRHS());
10628           return;
10629         }
10630       }
10631 
10632       if (isa<MemberExpr>(E)) {
10633         if (isInitList) {
10634           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10635                                       false /*CheckReference*/))
10636             return;
10637         }
10638 
10639         Expr *Base = E->IgnoreParenImpCasts();
10640         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10641           // Check for static member variables and don't warn on them.
10642           if (!isa<FieldDecl>(ME->getMemberDecl()))
10643             return;
10644           Base = ME->getBase()->IgnoreParenImpCasts();
10645         }
10646         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10647           HandleDeclRefExpr(DRE);
10648         return;
10649       }
10650 
10651       Visit(E);
10652     }
10653 
10654     // Reference types not handled in HandleValue are handled here since all
10655     // uses of references are bad, not just r-value uses.
10656     void VisitDeclRefExpr(DeclRefExpr *E) {
10657       if (isReferenceType)
10658         HandleDeclRefExpr(E);
10659     }
10660 
10661     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10662       if (E->getCastKind() == CK_LValueToRValue) {
10663         HandleValue(E->getSubExpr());
10664         return;
10665       }
10666 
10667       Inherited::VisitImplicitCastExpr(E);
10668     }
10669 
10670     void VisitMemberExpr(MemberExpr *E) {
10671       if (isInitList) {
10672         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10673           return;
10674       }
10675 
10676       // Don't warn on arrays since they can be treated as pointers.
10677       if (E->getType()->canDecayToPointerType()) return;
10678 
10679       // Warn when a non-static method call is followed by non-static member
10680       // field accesses, which is followed by a DeclRefExpr.
10681       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10682       bool Warn = (MD && !MD->isStatic());
10683       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10684       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10685         if (!isa<FieldDecl>(ME->getMemberDecl()))
10686           Warn = false;
10687         Base = ME->getBase()->IgnoreParenImpCasts();
10688       }
10689 
10690       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10691         if (Warn)
10692           HandleDeclRefExpr(DRE);
10693         return;
10694       }
10695 
10696       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10697       // Visit that expression.
10698       Visit(Base);
10699     }
10700 
10701     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10702       Expr *Callee = E->getCallee();
10703 
10704       if (isa<UnresolvedLookupExpr>(Callee))
10705         return Inherited::VisitCXXOperatorCallExpr(E);
10706 
10707       Visit(Callee);
10708       for (auto Arg: E->arguments())
10709         HandleValue(Arg->IgnoreParenImpCasts());
10710     }
10711 
10712     void VisitUnaryOperator(UnaryOperator *E) {
10713       // For POD record types, addresses of its own members are well-defined.
10714       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10715           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10716         if (!isPODType)
10717           HandleValue(E->getSubExpr());
10718         return;
10719       }
10720 
10721       if (E->isIncrementDecrementOp()) {
10722         HandleValue(E->getSubExpr());
10723         return;
10724       }
10725 
10726       Inherited::VisitUnaryOperator(E);
10727     }
10728 
10729     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10730 
10731     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10732       if (E->getConstructor()->isCopyConstructor()) {
10733         Expr *ArgExpr = E->getArg(0);
10734         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10735           if (ILE->getNumInits() == 1)
10736             ArgExpr = ILE->getInit(0);
10737         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10738           if (ICE->getCastKind() == CK_NoOp)
10739             ArgExpr = ICE->getSubExpr();
10740         HandleValue(ArgExpr);
10741         return;
10742       }
10743       Inherited::VisitCXXConstructExpr(E);
10744     }
10745 
10746     void VisitCallExpr(CallExpr *E) {
10747       // Treat std::move as a use.
10748       if (E->isCallToStdMove()) {
10749         HandleValue(E->getArg(0));
10750         return;
10751       }
10752 
10753       Inherited::VisitCallExpr(E);
10754     }
10755 
10756     void VisitBinaryOperator(BinaryOperator *E) {
10757       if (E->isCompoundAssignmentOp()) {
10758         HandleValue(E->getLHS());
10759         Visit(E->getRHS());
10760         return;
10761       }
10762 
10763       Inherited::VisitBinaryOperator(E);
10764     }
10765 
10766     // A custom visitor for BinaryConditionalOperator is needed because the
10767     // regular visitor would check the condition and true expression separately
10768     // but both point to the same place giving duplicate diagnostics.
10769     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10770       Visit(E->getCond());
10771       Visit(E->getFalseExpr());
10772     }
10773 
10774     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10775       Decl* ReferenceDecl = DRE->getDecl();
10776       if (OrigDecl != ReferenceDecl) return;
10777       unsigned diag;
10778       if (isReferenceType) {
10779         diag = diag::warn_uninit_self_reference_in_reference_init;
10780       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10781         diag = diag::warn_static_self_reference_in_init;
10782       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10783                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10784                  DRE->getDecl()->getType()->isRecordType()) {
10785         diag = diag::warn_uninit_self_reference_in_init;
10786       } else {
10787         // Local variables will be handled by the CFG analysis.
10788         return;
10789       }
10790 
10791       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10792                             S.PDiag(diag)
10793                                 << DRE->getDecl() << OrigDecl->getLocation()
10794                                 << DRE->getSourceRange());
10795     }
10796   };
10797 
10798   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10799   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10800                                  bool DirectInit) {
10801     // Parameters arguments are occassionially constructed with itself,
10802     // for instance, in recursive functions.  Skip them.
10803     if (isa<ParmVarDecl>(OrigDecl))
10804       return;
10805 
10806     E = E->IgnoreParens();
10807 
10808     // Skip checking T a = a where T is not a record or reference type.
10809     // Doing so is a way to silence uninitialized warnings.
10810     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10811       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10812         if (ICE->getCastKind() == CK_LValueToRValue)
10813           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10814             if (DRE->getDecl() == OrigDecl)
10815               return;
10816 
10817     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10818   }
10819 } // end anonymous namespace
10820 
10821 namespace {
10822   // Simple wrapper to add the name of a variable or (if no variable is
10823   // available) a DeclarationName into a diagnostic.
10824   struct VarDeclOrName {
10825     VarDecl *VDecl;
10826     DeclarationName Name;
10827 
10828     friend const Sema::SemaDiagnosticBuilder &
10829     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10830       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10831     }
10832   };
10833 } // end anonymous namespace
10834 
10835 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10836                                             DeclarationName Name, QualType Type,
10837                                             TypeSourceInfo *TSI,
10838                                             SourceRange Range, bool DirectInit,
10839                                             Expr *&Init) {
10840   bool IsInitCapture = !VDecl;
10841   assert((!VDecl || !VDecl->isInitCapture()) &&
10842          "init captures are expected to be deduced prior to initialization");
10843 
10844   VarDeclOrName VN{VDecl, Name};
10845 
10846   DeducedType *Deduced = Type->getContainedDeducedType();
10847   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10848 
10849   // C++11 [dcl.spec.auto]p3
10850   if (!Init) {
10851     assert(VDecl && "no init for init capture deduction?");
10852 
10853     // Except for class argument deduction, and then for an initializing
10854     // declaration only, i.e. no static at class scope or extern.
10855     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10856         VDecl->hasExternalStorage() ||
10857         VDecl->isStaticDataMember()) {
10858       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10859         << VDecl->getDeclName() << Type;
10860       return QualType();
10861     }
10862   }
10863 
10864   ArrayRef<Expr*> DeduceInits;
10865   if (Init)
10866     DeduceInits = Init;
10867 
10868   if (DirectInit) {
10869     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10870       DeduceInits = PL->exprs();
10871   }
10872 
10873   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10874     assert(VDecl && "non-auto type for init capture deduction?");
10875     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10876     InitializationKind Kind = InitializationKind::CreateForInit(
10877         VDecl->getLocation(), DirectInit, Init);
10878     // FIXME: Initialization should not be taking a mutable list of inits.
10879     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10880     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10881                                                        InitsCopy);
10882   }
10883 
10884   if (DirectInit) {
10885     if (auto *IL = dyn_cast<InitListExpr>(Init))
10886       DeduceInits = IL->inits();
10887   }
10888 
10889   // Deduction only works if we have exactly one source expression.
10890   if (DeduceInits.empty()) {
10891     // It isn't possible to write this directly, but it is possible to
10892     // end up in this situation with "auto x(some_pack...);"
10893     Diag(Init->getBeginLoc(), IsInitCapture
10894                                   ? diag::err_init_capture_no_expression
10895                                   : diag::err_auto_var_init_no_expression)
10896         << VN << Type << Range;
10897     return QualType();
10898   }
10899 
10900   if (DeduceInits.size() > 1) {
10901     Diag(DeduceInits[1]->getBeginLoc(),
10902          IsInitCapture ? diag::err_init_capture_multiple_expressions
10903                        : diag::err_auto_var_init_multiple_expressions)
10904         << VN << Type << Range;
10905     return QualType();
10906   }
10907 
10908   Expr *DeduceInit = DeduceInits[0];
10909   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10910     Diag(Init->getBeginLoc(), IsInitCapture
10911                                   ? diag::err_init_capture_paren_braces
10912                                   : diag::err_auto_var_init_paren_braces)
10913         << isa<InitListExpr>(Init) << VN << Type << Range;
10914     return QualType();
10915   }
10916 
10917   // Expressions default to 'id' when we're in a debugger.
10918   bool DefaultedAnyToId = false;
10919   if (getLangOpts().DebuggerCastResultToId &&
10920       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10921     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10922     if (Result.isInvalid()) {
10923       return QualType();
10924     }
10925     Init = Result.get();
10926     DefaultedAnyToId = true;
10927   }
10928 
10929   // C++ [dcl.decomp]p1:
10930   //   If the assignment-expression [...] has array type A and no ref-qualifier
10931   //   is present, e has type cv A
10932   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10933       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10934       DeduceInit->getType()->isConstantArrayType())
10935     return Context.getQualifiedType(DeduceInit->getType(),
10936                                     Type.getQualifiers());
10937 
10938   QualType DeducedType;
10939   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10940     if (!IsInitCapture)
10941       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10942     else if (isa<InitListExpr>(Init))
10943       Diag(Range.getBegin(),
10944            diag::err_init_capture_deduction_failure_from_init_list)
10945           << VN
10946           << (DeduceInit->getType().isNull() ? TSI->getType()
10947                                              : DeduceInit->getType())
10948           << DeduceInit->getSourceRange();
10949     else
10950       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10951           << VN << TSI->getType()
10952           << (DeduceInit->getType().isNull() ? TSI->getType()
10953                                              : DeduceInit->getType())
10954           << DeduceInit->getSourceRange();
10955   } else
10956     Init = DeduceInit;
10957 
10958   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10959   // 'id' instead of a specific object type prevents most of our usual
10960   // checks.
10961   // We only want to warn outside of template instantiations, though:
10962   // inside a template, the 'id' could have come from a parameter.
10963   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10964       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10965     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10966     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10967   }
10968 
10969   return DeducedType;
10970 }
10971 
10972 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10973                                          Expr *&Init) {
10974   QualType DeducedType = deduceVarTypeFromInitializer(
10975       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10976       VDecl->getSourceRange(), DirectInit, Init);
10977   if (DeducedType.isNull()) {
10978     VDecl->setInvalidDecl();
10979     return true;
10980   }
10981 
10982   VDecl->setType(DeducedType);
10983   assert(VDecl->isLinkageValid());
10984 
10985   // In ARC, infer lifetime.
10986   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10987     VDecl->setInvalidDecl();
10988 
10989   // If this is a redeclaration, check that the type we just deduced matches
10990   // the previously declared type.
10991   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10992     // We never need to merge the type, because we cannot form an incomplete
10993     // array of auto, nor deduce such a type.
10994     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10995   }
10996 
10997   // Check the deduced type is valid for a variable declaration.
10998   CheckVariableDeclarationType(VDecl);
10999   return VDecl->isInvalidDecl();
11000 }
11001 
11002 /// AddInitializerToDecl - Adds the initializer Init to the
11003 /// declaration dcl. If DirectInit is true, this is C++ direct
11004 /// initialization rather than copy initialization.
11005 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11006   // If there is no declaration, there was an error parsing it.  Just ignore
11007   // the initializer.
11008   if (!RealDecl || RealDecl->isInvalidDecl()) {
11009     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11010     return;
11011   }
11012 
11013   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11014     // Pure-specifiers are handled in ActOnPureSpecifier.
11015     Diag(Method->getLocation(), diag::err_member_function_initialization)
11016       << Method->getDeclName() << Init->getSourceRange();
11017     Method->setInvalidDecl();
11018     return;
11019   }
11020 
11021   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11022   if (!VDecl) {
11023     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11024     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11025     RealDecl->setInvalidDecl();
11026     return;
11027   }
11028 
11029   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11030   if (VDecl->getType()->isUndeducedType()) {
11031     // Attempt typo correction early so that the type of the init expression can
11032     // be deduced based on the chosen correction if the original init contains a
11033     // TypoExpr.
11034     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11035     if (!Res.isUsable()) {
11036       RealDecl->setInvalidDecl();
11037       return;
11038     }
11039     Init = Res.get();
11040 
11041     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11042       return;
11043   }
11044 
11045   // dllimport cannot be used on variable definitions.
11046   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11047     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11048     VDecl->setInvalidDecl();
11049     return;
11050   }
11051 
11052   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11053     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11054     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11055     VDecl->setInvalidDecl();
11056     return;
11057   }
11058 
11059   if (!VDecl->getType()->isDependentType()) {
11060     // A definition must end up with a complete type, which means it must be
11061     // complete with the restriction that an array type might be completed by
11062     // the initializer; note that later code assumes this restriction.
11063     QualType BaseDeclType = VDecl->getType();
11064     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11065       BaseDeclType = Array->getElementType();
11066     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11067                             diag::err_typecheck_decl_incomplete_type)) {
11068       RealDecl->setInvalidDecl();
11069       return;
11070     }
11071 
11072     // The variable can not have an abstract class type.
11073     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11074                                diag::err_abstract_type_in_decl,
11075                                AbstractVariableType))
11076       VDecl->setInvalidDecl();
11077   }
11078 
11079   // If adding the initializer will turn this declaration into a definition,
11080   // and we already have a definition for this variable, diagnose or otherwise
11081   // handle the situation.
11082   VarDecl *Def;
11083   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11084       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11085       !VDecl->isThisDeclarationADemotedDefinition() &&
11086       checkVarDeclRedefinition(Def, VDecl))
11087     return;
11088 
11089   if (getLangOpts().CPlusPlus) {
11090     // C++ [class.static.data]p4
11091     //   If a static data member is of const integral or const
11092     //   enumeration type, its declaration in the class definition can
11093     //   specify a constant-initializer which shall be an integral
11094     //   constant expression (5.19). In that case, the member can appear
11095     //   in integral constant expressions. The member shall still be
11096     //   defined in a namespace scope if it is used in the program and the
11097     //   namespace scope definition shall not contain an initializer.
11098     //
11099     // We already performed a redefinition check above, but for static
11100     // data members we also need to check whether there was an in-class
11101     // declaration with an initializer.
11102     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11103       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11104           << VDecl->getDeclName();
11105       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11106            diag::note_previous_initializer)
11107           << 0;
11108       return;
11109     }
11110 
11111     if (VDecl->hasLocalStorage())
11112       setFunctionHasBranchProtectedScope();
11113 
11114     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11115       VDecl->setInvalidDecl();
11116       return;
11117     }
11118   }
11119 
11120   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11121   // a kernel function cannot be initialized."
11122   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11123     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11124     VDecl->setInvalidDecl();
11125     return;
11126   }
11127 
11128   // Get the decls type and save a reference for later, since
11129   // CheckInitializerTypes may change it.
11130   QualType DclT = VDecl->getType(), SavT = DclT;
11131 
11132   // Expressions default to 'id' when we're in a debugger
11133   // and we are assigning it to a variable of Objective-C pointer type.
11134   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11135       Init->getType() == Context.UnknownAnyTy) {
11136     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11137     if (Result.isInvalid()) {
11138       VDecl->setInvalidDecl();
11139       return;
11140     }
11141     Init = Result.get();
11142   }
11143 
11144   // Perform the initialization.
11145   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11146   if (!VDecl->isInvalidDecl()) {
11147     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11148     InitializationKind Kind = InitializationKind::CreateForInit(
11149         VDecl->getLocation(), DirectInit, Init);
11150 
11151     MultiExprArg Args = Init;
11152     if (CXXDirectInit)
11153       Args = MultiExprArg(CXXDirectInit->getExprs(),
11154                           CXXDirectInit->getNumExprs());
11155 
11156     // Try to correct any TypoExprs in the initialization arguments.
11157     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11158       ExprResult Res = CorrectDelayedTyposInExpr(
11159           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11160             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11161             return Init.Failed() ? ExprError() : E;
11162           });
11163       if (Res.isInvalid()) {
11164         VDecl->setInvalidDecl();
11165       } else if (Res.get() != Args[Idx]) {
11166         Args[Idx] = Res.get();
11167       }
11168     }
11169     if (VDecl->isInvalidDecl())
11170       return;
11171 
11172     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11173                                    /*TopLevelOfInitList=*/false,
11174                                    /*TreatUnavailableAsInvalid=*/false);
11175     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11176     if (Result.isInvalid()) {
11177       VDecl->setInvalidDecl();
11178       return;
11179     }
11180 
11181     Init = Result.getAs<Expr>();
11182   }
11183 
11184   // Check for self-references within variable initializers.
11185   // Variables declared within a function/method body (except for references)
11186   // are handled by a dataflow analysis.
11187   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11188       VDecl->getType()->isReferenceType()) {
11189     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11190   }
11191 
11192   // If the type changed, it means we had an incomplete type that was
11193   // completed by the initializer. For example:
11194   //   int ary[] = { 1, 3, 5 };
11195   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11196   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11197     VDecl->setType(DclT);
11198 
11199   if (!VDecl->isInvalidDecl()) {
11200     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11201 
11202     if (VDecl->hasAttr<BlocksAttr>())
11203       checkRetainCycles(VDecl, Init);
11204 
11205     // It is safe to assign a weak reference into a strong variable.
11206     // Although this code can still have problems:
11207     //   id x = self.weakProp;
11208     //   id y = self.weakProp;
11209     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11210     // paths through the function. This should be revisited if
11211     // -Wrepeated-use-of-weak is made flow-sensitive.
11212     if (FunctionScopeInfo *FSI = getCurFunction())
11213       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11214            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11215           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11216                            Init->getBeginLoc()))
11217         FSI->markSafeWeakUse(Init);
11218   }
11219 
11220   // The initialization is usually a full-expression.
11221   //
11222   // FIXME: If this is a braced initialization of an aggregate, it is not
11223   // an expression, and each individual field initializer is a separate
11224   // full-expression. For instance, in:
11225   //
11226   //   struct Temp { ~Temp(); };
11227   //   struct S { S(Temp); };
11228   //   struct T { S a, b; } t = { Temp(), Temp() }
11229   //
11230   // we should destroy the first Temp before constructing the second.
11231   ExprResult Result =
11232       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11233                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11234   if (Result.isInvalid()) {
11235     VDecl->setInvalidDecl();
11236     return;
11237   }
11238   Init = Result.get();
11239 
11240   // Attach the initializer to the decl.
11241   VDecl->setInit(Init);
11242 
11243   if (VDecl->isLocalVarDecl()) {
11244     // Don't check the initializer if the declaration is malformed.
11245     if (VDecl->isInvalidDecl()) {
11246       // do nothing
11247 
11248     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11249     // This is true even in OpenCL C++.
11250     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11251       CheckForConstantInitializer(Init, DclT);
11252 
11253     // Otherwise, C++ does not restrict the initializer.
11254     } else if (getLangOpts().CPlusPlus) {
11255       // do nothing
11256 
11257     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11258     // static storage duration shall be constant expressions or string literals.
11259     } else if (VDecl->getStorageClass() == SC_Static) {
11260       CheckForConstantInitializer(Init, DclT);
11261 
11262     // C89 is stricter than C99 for aggregate initializers.
11263     // C89 6.5.7p3: All the expressions [...] in an initializer list
11264     // for an object that has aggregate or union type shall be
11265     // constant expressions.
11266     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11267                isa<InitListExpr>(Init)) {
11268       const Expr *Culprit;
11269       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11270         Diag(Culprit->getExprLoc(),
11271              diag::ext_aggregate_init_not_constant)
11272           << Culprit->getSourceRange();
11273       }
11274     }
11275 
11276     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11277       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11278         if (VDecl->hasLocalStorage())
11279           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11280   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11281              VDecl->getLexicalDeclContext()->isRecord()) {
11282     // This is an in-class initialization for a static data member, e.g.,
11283     //
11284     // struct S {
11285     //   static const int value = 17;
11286     // };
11287 
11288     // C++ [class.mem]p4:
11289     //   A member-declarator can contain a constant-initializer only
11290     //   if it declares a static member (9.4) of const integral or
11291     //   const enumeration type, see 9.4.2.
11292     //
11293     // C++11 [class.static.data]p3:
11294     //   If a non-volatile non-inline const static data member is of integral
11295     //   or enumeration type, its declaration in the class definition can
11296     //   specify a brace-or-equal-initializer in which every initializer-clause
11297     //   that is an assignment-expression is a constant expression. A static
11298     //   data member of literal type can be declared in the class definition
11299     //   with the constexpr specifier; if so, its declaration shall specify a
11300     //   brace-or-equal-initializer in which every initializer-clause that is
11301     //   an assignment-expression is a constant expression.
11302 
11303     // Do nothing on dependent types.
11304     if (DclT->isDependentType()) {
11305 
11306     // Allow any 'static constexpr' members, whether or not they are of literal
11307     // type. We separately check that every constexpr variable is of literal
11308     // type.
11309     } else if (VDecl->isConstexpr()) {
11310 
11311     // Require constness.
11312     } else if (!DclT.isConstQualified()) {
11313       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11314         << Init->getSourceRange();
11315       VDecl->setInvalidDecl();
11316 
11317     // We allow integer constant expressions in all cases.
11318     } else if (DclT->isIntegralOrEnumerationType()) {
11319       // Check whether the expression is a constant expression.
11320       SourceLocation Loc;
11321       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11322         // In C++11, a non-constexpr const static data member with an
11323         // in-class initializer cannot be volatile.
11324         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11325       else if (Init->isValueDependent())
11326         ; // Nothing to check.
11327       else if (Init->isIntegerConstantExpr(Context, &Loc))
11328         ; // Ok, it's an ICE!
11329       else if (Init->getType()->isScopedEnumeralType() &&
11330                Init->isCXX11ConstantExpr(Context))
11331         ; // Ok, it is a scoped-enum constant expression.
11332       else if (Init->isEvaluatable(Context)) {
11333         // If we can constant fold the initializer through heroics, accept it,
11334         // but report this as a use of an extension for -pedantic.
11335         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11336           << Init->getSourceRange();
11337       } else {
11338         // Otherwise, this is some crazy unknown case.  Report the issue at the
11339         // location provided by the isIntegerConstantExpr failed check.
11340         Diag(Loc, diag::err_in_class_initializer_non_constant)
11341           << Init->getSourceRange();
11342         VDecl->setInvalidDecl();
11343       }
11344 
11345     // We allow foldable floating-point constants as an extension.
11346     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11347       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11348       // it anyway and provide a fixit to add the 'constexpr'.
11349       if (getLangOpts().CPlusPlus11) {
11350         Diag(VDecl->getLocation(),
11351              diag::ext_in_class_initializer_float_type_cxx11)
11352             << DclT << Init->getSourceRange();
11353         Diag(VDecl->getBeginLoc(),
11354              diag::note_in_class_initializer_float_type_cxx11)
11355             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11356       } else {
11357         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11358           << DclT << Init->getSourceRange();
11359 
11360         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11361           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11362             << Init->getSourceRange();
11363           VDecl->setInvalidDecl();
11364         }
11365       }
11366 
11367     // Suggest adding 'constexpr' in C++11 for literal types.
11368     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11369       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11370           << DclT << Init->getSourceRange()
11371           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11372       VDecl->setConstexpr(true);
11373 
11374     } else {
11375       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11376         << DclT << Init->getSourceRange();
11377       VDecl->setInvalidDecl();
11378     }
11379   } else if (VDecl->isFileVarDecl()) {
11380     // In C, extern is typically used to avoid tentative definitions when
11381     // declaring variables in headers, but adding an intializer makes it a
11382     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11383     // In C++, extern is often used to give implictly static const variables
11384     // external linkage, so don't warn in that case. If selectany is present,
11385     // this might be header code intended for C and C++ inclusion, so apply the
11386     // C++ rules.
11387     if (VDecl->getStorageClass() == SC_Extern &&
11388         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11389          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11390         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11391         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11392       Diag(VDecl->getLocation(), diag::warn_extern_init);
11393 
11394     // In Microsoft C++ mode, a const variable defined in namespace scope has
11395     // external linkage by default if the variable is declared with
11396     // __declspec(dllexport).
11397     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11398         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11399         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11400       VDecl->setStorageClass(SC_Extern);
11401 
11402     // C99 6.7.8p4. All file scoped initializers need to be constant.
11403     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11404       CheckForConstantInitializer(Init, DclT);
11405   }
11406 
11407   // We will represent direct-initialization similarly to copy-initialization:
11408   //    int x(1);  -as-> int x = 1;
11409   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11410   //
11411   // Clients that want to distinguish between the two forms, can check for
11412   // direct initializer using VarDecl::getInitStyle().
11413   // A major benefit is that clients that don't particularly care about which
11414   // exactly form was it (like the CodeGen) can handle both cases without
11415   // special case code.
11416 
11417   // C++ 8.5p11:
11418   // The form of initialization (using parentheses or '=') is generally
11419   // insignificant, but does matter when the entity being initialized has a
11420   // class type.
11421   if (CXXDirectInit) {
11422     assert(DirectInit && "Call-style initializer must be direct init.");
11423     VDecl->setInitStyle(VarDecl::CallInit);
11424   } else if (DirectInit) {
11425     // This must be list-initialization. No other way is direct-initialization.
11426     VDecl->setInitStyle(VarDecl::ListInit);
11427   }
11428 
11429   CheckCompleteVariableDeclaration(VDecl);
11430 }
11431 
11432 /// ActOnInitializerError - Given that there was an error parsing an
11433 /// initializer for the given declaration, try to return to some form
11434 /// of sanity.
11435 void Sema::ActOnInitializerError(Decl *D) {
11436   // Our main concern here is re-establishing invariants like "a
11437   // variable's type is either dependent or complete".
11438   if (!D || D->isInvalidDecl()) return;
11439 
11440   VarDecl *VD = dyn_cast<VarDecl>(D);
11441   if (!VD) return;
11442 
11443   // Bindings are not usable if we can't make sense of the initializer.
11444   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11445     for (auto *BD : DD->bindings())
11446       BD->setInvalidDecl();
11447 
11448   // Auto types are meaningless if we can't make sense of the initializer.
11449   if (ParsingInitForAutoVars.count(D)) {
11450     D->setInvalidDecl();
11451     return;
11452   }
11453 
11454   QualType Ty = VD->getType();
11455   if (Ty->isDependentType()) return;
11456 
11457   // Require a complete type.
11458   if (RequireCompleteType(VD->getLocation(),
11459                           Context.getBaseElementType(Ty),
11460                           diag::err_typecheck_decl_incomplete_type)) {
11461     VD->setInvalidDecl();
11462     return;
11463   }
11464 
11465   // Require a non-abstract type.
11466   if (RequireNonAbstractType(VD->getLocation(), Ty,
11467                              diag::err_abstract_type_in_decl,
11468                              AbstractVariableType)) {
11469     VD->setInvalidDecl();
11470     return;
11471   }
11472 
11473   // Don't bother complaining about constructors or destructors,
11474   // though.
11475 }
11476 
11477 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11478   // If there is no declaration, there was an error parsing it. Just ignore it.
11479   if (!RealDecl)
11480     return;
11481 
11482   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11483     QualType Type = Var->getType();
11484 
11485     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11486     if (isa<DecompositionDecl>(RealDecl)) {
11487       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11488       Var->setInvalidDecl();
11489       return;
11490     }
11491 
11492     Expr *TmpInit = nullptr;
11493     if (Type->isUndeducedType() &&
11494         DeduceVariableDeclarationType(Var, false, TmpInit))
11495       return;
11496 
11497     // C++11 [class.static.data]p3: A static data member can be declared with
11498     // the constexpr specifier; if so, its declaration shall specify
11499     // a brace-or-equal-initializer.
11500     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11501     // the definition of a variable [...] or the declaration of a static data
11502     // member.
11503     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11504         !Var->isThisDeclarationADemotedDefinition()) {
11505       if (Var->isStaticDataMember()) {
11506         // C++1z removes the relevant rule; the in-class declaration is always
11507         // a definition there.
11508         if (!getLangOpts().CPlusPlus17) {
11509           Diag(Var->getLocation(),
11510                diag::err_constexpr_static_mem_var_requires_init)
11511             << Var->getDeclName();
11512           Var->setInvalidDecl();
11513           return;
11514         }
11515       } else {
11516         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11517         Var->setInvalidDecl();
11518         return;
11519       }
11520     }
11521 
11522     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11523     // be initialized.
11524     if (!Var->isInvalidDecl() &&
11525         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11526         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11527       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11528       Var->setInvalidDecl();
11529       return;
11530     }
11531 
11532     switch (Var->isThisDeclarationADefinition()) {
11533     case VarDecl::Definition:
11534       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11535         break;
11536 
11537       // We have an out-of-line definition of a static data member
11538       // that has an in-class initializer, so we type-check this like
11539       // a declaration.
11540       //
11541       LLVM_FALLTHROUGH;
11542 
11543     case VarDecl::DeclarationOnly:
11544       // It's only a declaration.
11545 
11546       // Block scope. C99 6.7p7: If an identifier for an object is
11547       // declared with no linkage (C99 6.2.2p6), the type for the
11548       // object shall be complete.
11549       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11550           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11551           RequireCompleteType(Var->getLocation(), Type,
11552                               diag::err_typecheck_decl_incomplete_type))
11553         Var->setInvalidDecl();
11554 
11555       // Make sure that the type is not abstract.
11556       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11557           RequireNonAbstractType(Var->getLocation(), Type,
11558                                  diag::err_abstract_type_in_decl,
11559                                  AbstractVariableType))
11560         Var->setInvalidDecl();
11561       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11562           Var->getStorageClass() == SC_PrivateExtern) {
11563         Diag(Var->getLocation(), diag::warn_private_extern);
11564         Diag(Var->getLocation(), diag::note_private_extern);
11565       }
11566 
11567       return;
11568 
11569     case VarDecl::TentativeDefinition:
11570       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11571       // object that has file scope without an initializer, and without a
11572       // storage-class specifier or with the storage-class specifier "static",
11573       // constitutes a tentative definition. Note: A tentative definition with
11574       // external linkage is valid (C99 6.2.2p5).
11575       if (!Var->isInvalidDecl()) {
11576         if (const IncompleteArrayType *ArrayT
11577                                     = Context.getAsIncompleteArrayType(Type)) {
11578           if (RequireCompleteType(Var->getLocation(),
11579                                   ArrayT->getElementType(),
11580                                   diag::err_illegal_decl_array_incomplete_type))
11581             Var->setInvalidDecl();
11582         } else if (Var->getStorageClass() == SC_Static) {
11583           // C99 6.9.2p3: If the declaration of an identifier for an object is
11584           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11585           // declared type shall not be an incomplete type.
11586           // NOTE: code such as the following
11587           //     static struct s;
11588           //     struct s { int a; };
11589           // is accepted by gcc. Hence here we issue a warning instead of
11590           // an error and we do not invalidate the static declaration.
11591           // NOTE: to avoid multiple warnings, only check the first declaration.
11592           if (Var->isFirstDecl())
11593             RequireCompleteType(Var->getLocation(), Type,
11594                                 diag::ext_typecheck_decl_incomplete_type);
11595         }
11596       }
11597 
11598       // Record the tentative definition; we're done.
11599       if (!Var->isInvalidDecl())
11600         TentativeDefinitions.push_back(Var);
11601       return;
11602     }
11603 
11604     // Provide a specific diagnostic for uninitialized variable
11605     // definitions with incomplete array type.
11606     if (Type->isIncompleteArrayType()) {
11607       Diag(Var->getLocation(),
11608            diag::err_typecheck_incomplete_array_needs_initializer);
11609       Var->setInvalidDecl();
11610       return;
11611     }
11612 
11613     // Provide a specific diagnostic for uninitialized variable
11614     // definitions with reference type.
11615     if (Type->isReferenceType()) {
11616       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11617         << Var->getDeclName()
11618         << SourceRange(Var->getLocation(), Var->getLocation());
11619       Var->setInvalidDecl();
11620       return;
11621     }
11622 
11623     // Do not attempt to type-check the default initializer for a
11624     // variable with dependent type.
11625     if (Type->isDependentType())
11626       return;
11627 
11628     if (Var->isInvalidDecl())
11629       return;
11630 
11631     if (!Var->hasAttr<AliasAttr>()) {
11632       if (RequireCompleteType(Var->getLocation(),
11633                               Context.getBaseElementType(Type),
11634                               diag::err_typecheck_decl_incomplete_type)) {
11635         Var->setInvalidDecl();
11636         return;
11637       }
11638     } else {
11639       return;
11640     }
11641 
11642     // The variable can not have an abstract class type.
11643     if (RequireNonAbstractType(Var->getLocation(), Type,
11644                                diag::err_abstract_type_in_decl,
11645                                AbstractVariableType)) {
11646       Var->setInvalidDecl();
11647       return;
11648     }
11649 
11650     // Check for jumps past the implicit initializer.  C++0x
11651     // clarifies that this applies to a "variable with automatic
11652     // storage duration", not a "local variable".
11653     // C++11 [stmt.dcl]p3
11654     //   A program that jumps from a point where a variable with automatic
11655     //   storage duration is not in scope to a point where it is in scope is
11656     //   ill-formed unless the variable has scalar type, class type with a
11657     //   trivial default constructor and a trivial destructor, a cv-qualified
11658     //   version of one of these types, or an array of one of the preceding
11659     //   types and is declared without an initializer.
11660     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11661       if (const RecordType *Record
11662             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11663         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11664         // Mark the function (if we're in one) for further checking even if the
11665         // looser rules of C++11 do not require such checks, so that we can
11666         // diagnose incompatibilities with C++98.
11667         if (!CXXRecord->isPOD())
11668           setFunctionHasBranchProtectedScope();
11669       }
11670     }
11671 
11672     // C++03 [dcl.init]p9:
11673     //   If no initializer is specified for an object, and the
11674     //   object is of (possibly cv-qualified) non-POD class type (or
11675     //   array thereof), the object shall be default-initialized; if
11676     //   the object is of const-qualified type, the underlying class
11677     //   type shall have a user-declared default
11678     //   constructor. Otherwise, if no initializer is specified for
11679     //   a non- static object, the object and its subobjects, if
11680     //   any, have an indeterminate initial value); if the object
11681     //   or any of its subobjects are of const-qualified type, the
11682     //   program is ill-formed.
11683     // C++0x [dcl.init]p11:
11684     //   If no initializer is specified for an object, the object is
11685     //   default-initialized; [...].
11686     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11687     InitializationKind Kind
11688       = InitializationKind::CreateDefault(Var->getLocation());
11689 
11690     InitializationSequence InitSeq(*this, Entity, Kind, None);
11691     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11692     if (Init.isInvalid())
11693       Var->setInvalidDecl();
11694     else if (Init.get()) {
11695       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11696       // This is important for template substitution.
11697       Var->setInitStyle(VarDecl::CallInit);
11698     }
11699 
11700     CheckCompleteVariableDeclaration(Var);
11701   }
11702 }
11703 
11704 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11705   // If there is no declaration, there was an error parsing it. Ignore it.
11706   if (!D)
11707     return;
11708 
11709   VarDecl *VD = dyn_cast<VarDecl>(D);
11710   if (!VD) {
11711     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11712     D->setInvalidDecl();
11713     return;
11714   }
11715 
11716   VD->setCXXForRangeDecl(true);
11717 
11718   // for-range-declaration cannot be given a storage class specifier.
11719   int Error = -1;
11720   switch (VD->getStorageClass()) {
11721   case SC_None:
11722     break;
11723   case SC_Extern:
11724     Error = 0;
11725     break;
11726   case SC_Static:
11727     Error = 1;
11728     break;
11729   case SC_PrivateExtern:
11730     Error = 2;
11731     break;
11732   case SC_Auto:
11733     Error = 3;
11734     break;
11735   case SC_Register:
11736     Error = 4;
11737     break;
11738   }
11739   if (Error != -1) {
11740     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11741       << VD->getDeclName() << Error;
11742     D->setInvalidDecl();
11743   }
11744 }
11745 
11746 StmtResult
11747 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11748                                  IdentifierInfo *Ident,
11749                                  ParsedAttributes &Attrs,
11750                                  SourceLocation AttrEnd) {
11751   // C++1y [stmt.iter]p1:
11752   //   A range-based for statement of the form
11753   //      for ( for-range-identifier : for-range-initializer ) statement
11754   //   is equivalent to
11755   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11756   DeclSpec DS(Attrs.getPool().getFactory());
11757 
11758   const char *PrevSpec;
11759   unsigned DiagID;
11760   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11761                      getPrintingPolicy());
11762 
11763   Declarator D(DS, DeclaratorContext::ForContext);
11764   D.SetIdentifier(Ident, IdentLoc);
11765   D.takeAttributes(Attrs, AttrEnd);
11766 
11767   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11768   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11769                 IdentLoc);
11770   Decl *Var = ActOnDeclarator(S, D);
11771   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11772   FinalizeDeclaration(Var);
11773   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11774                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11775 }
11776 
11777 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11778   if (var->isInvalidDecl()) return;
11779 
11780   if (getLangOpts().OpenCL) {
11781     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11782     // initialiser
11783     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11784         !var->hasInit()) {
11785       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11786           << 1 /*Init*/;
11787       var->setInvalidDecl();
11788       return;
11789     }
11790   }
11791 
11792   // In Objective-C, don't allow jumps past the implicit initialization of a
11793   // local retaining variable.
11794   if (getLangOpts().ObjC &&
11795       var->hasLocalStorage()) {
11796     switch (var->getType().getObjCLifetime()) {
11797     case Qualifiers::OCL_None:
11798     case Qualifiers::OCL_ExplicitNone:
11799     case Qualifiers::OCL_Autoreleasing:
11800       break;
11801 
11802     case Qualifiers::OCL_Weak:
11803     case Qualifiers::OCL_Strong:
11804       setFunctionHasBranchProtectedScope();
11805       break;
11806     }
11807   }
11808 
11809   if (var->hasLocalStorage() &&
11810       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11811     setFunctionHasBranchProtectedScope();
11812 
11813   // Warn about externally-visible variables being defined without a
11814   // prior declaration.  We only want to do this for global
11815   // declarations, but we also specifically need to avoid doing it for
11816   // class members because the linkage of an anonymous class can
11817   // change if it's later given a typedef name.
11818   if (var->isThisDeclarationADefinition() &&
11819       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11820       var->isExternallyVisible() && var->hasLinkage() &&
11821       !var->isInline() && !var->getDescribedVarTemplate() &&
11822       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11823       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11824                                   var->getLocation())) {
11825     // Find a previous declaration that's not a definition.
11826     VarDecl *prev = var->getPreviousDecl();
11827     while (prev && prev->isThisDeclarationADefinition())
11828       prev = prev->getPreviousDecl();
11829 
11830     if (!prev)
11831       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11832   }
11833 
11834   // Cache the result of checking for constant initialization.
11835   Optional<bool> CacheHasConstInit;
11836   const Expr *CacheCulprit;
11837   auto checkConstInit = [&]() mutable {
11838     if (!CacheHasConstInit)
11839       CacheHasConstInit = var->getInit()->isConstantInitializer(
11840             Context, var->getType()->isReferenceType(), &CacheCulprit);
11841     return *CacheHasConstInit;
11842   };
11843 
11844   if (var->getTLSKind() == VarDecl::TLS_Static) {
11845     if (var->getType().isDestructedType()) {
11846       // GNU C++98 edits for __thread, [basic.start.term]p3:
11847       //   The type of an object with thread storage duration shall not
11848       //   have a non-trivial destructor.
11849       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11850       if (getLangOpts().CPlusPlus11)
11851         Diag(var->getLocation(), diag::note_use_thread_local);
11852     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11853       if (!checkConstInit()) {
11854         // GNU C++98 edits for __thread, [basic.start.init]p4:
11855         //   An object of thread storage duration shall not require dynamic
11856         //   initialization.
11857         // FIXME: Need strict checking here.
11858         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11859           << CacheCulprit->getSourceRange();
11860         if (getLangOpts().CPlusPlus11)
11861           Diag(var->getLocation(), diag::note_use_thread_local);
11862       }
11863     }
11864   }
11865 
11866   // Apply section attributes and pragmas to global variables.
11867   bool GlobalStorage = var->hasGlobalStorage();
11868   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11869       !inTemplateInstantiation()) {
11870     PragmaStack<StringLiteral *> *Stack = nullptr;
11871     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11872     if (var->getType().isConstQualified())
11873       Stack = &ConstSegStack;
11874     else if (!var->getInit()) {
11875       Stack = &BSSSegStack;
11876       SectionFlags |= ASTContext::PSF_Write;
11877     } else {
11878       Stack = &DataSegStack;
11879       SectionFlags |= ASTContext::PSF_Write;
11880     }
11881     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11882       var->addAttr(SectionAttr::CreateImplicit(
11883           Context, SectionAttr::Declspec_allocate,
11884           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11885     }
11886     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11887       if (UnifySection(SA->getName(), SectionFlags, var))
11888         var->dropAttr<SectionAttr>();
11889 
11890     // Apply the init_seg attribute if this has an initializer.  If the
11891     // initializer turns out to not be dynamic, we'll end up ignoring this
11892     // attribute.
11893     if (CurInitSeg && var->getInit())
11894       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11895                                                CurInitSegLoc));
11896   }
11897 
11898   // All the following checks are C++ only.
11899   if (!getLangOpts().CPlusPlus) {
11900       // If this variable must be emitted, add it as an initializer for the
11901       // current module.
11902      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11903        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11904      return;
11905   }
11906 
11907   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11908     CheckCompleteDecompositionDeclaration(DD);
11909 
11910   QualType type = var->getType();
11911   if (type->isDependentType()) return;
11912 
11913   if (var->hasAttr<BlocksAttr>())
11914     getCurFunction()->addByrefBlockVar(var);
11915 
11916   Expr *Init = var->getInit();
11917   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11918   QualType baseType = Context.getBaseElementType(type);
11919 
11920   if (Init && !Init->isValueDependent()) {
11921     if (var->isConstexpr()) {
11922       SmallVector<PartialDiagnosticAt, 8> Notes;
11923       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11924         SourceLocation DiagLoc = var->getLocation();
11925         // If the note doesn't add any useful information other than a source
11926         // location, fold it into the primary diagnostic.
11927         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11928               diag::note_invalid_subexpr_in_const_expr) {
11929           DiagLoc = Notes[0].first;
11930           Notes.clear();
11931         }
11932         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11933           << var << Init->getSourceRange();
11934         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11935           Diag(Notes[I].first, Notes[I].second);
11936       }
11937     } else if (var->isUsableInConstantExpressions(Context)) {
11938       // Check whether the initializer of a const variable of integral or
11939       // enumeration type is an ICE now, since we can't tell whether it was
11940       // initialized by a constant expression if we check later.
11941       var->checkInitIsICE();
11942     }
11943 
11944     // Don't emit further diagnostics about constexpr globals since they
11945     // were just diagnosed.
11946     if (!var->isConstexpr() && GlobalStorage &&
11947             var->hasAttr<RequireConstantInitAttr>()) {
11948       // FIXME: Need strict checking in C++03 here.
11949       bool DiagErr = getLangOpts().CPlusPlus11
11950           ? !var->checkInitIsICE() : !checkConstInit();
11951       if (DiagErr) {
11952         auto attr = var->getAttr<RequireConstantInitAttr>();
11953         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11954           << Init->getSourceRange();
11955         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11956           << attr->getRange();
11957         if (getLangOpts().CPlusPlus11) {
11958           APValue Value;
11959           SmallVector<PartialDiagnosticAt, 8> Notes;
11960           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11961           for (auto &it : Notes)
11962             Diag(it.first, it.second);
11963         } else {
11964           Diag(CacheCulprit->getExprLoc(),
11965                diag::note_invalid_subexpr_in_const_expr)
11966               << CacheCulprit->getSourceRange();
11967         }
11968       }
11969     }
11970     else if (!var->isConstexpr() && IsGlobal &&
11971              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11972                                     var->getLocation())) {
11973       // Warn about globals which don't have a constant initializer.  Don't
11974       // warn about globals with a non-trivial destructor because we already
11975       // warned about them.
11976       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11977       if (!(RD && !RD->hasTrivialDestructor())) {
11978         if (!checkConstInit())
11979           Diag(var->getLocation(), diag::warn_global_constructor)
11980             << Init->getSourceRange();
11981       }
11982     }
11983   }
11984 
11985   // Require the destructor.
11986   if (const RecordType *recordType = baseType->getAs<RecordType>())
11987     FinalizeVarWithDestructor(var, recordType);
11988 
11989   // If this variable must be emitted, add it as an initializer for the current
11990   // module.
11991   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11992     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11993 }
11994 
11995 /// Determines if a variable's alignment is dependent.
11996 static bool hasDependentAlignment(VarDecl *VD) {
11997   if (VD->getType()->isDependentType())
11998     return true;
11999   for (auto *I : VD->specific_attrs<AlignedAttr>())
12000     if (I->isAlignmentDependent())
12001       return true;
12002   return false;
12003 }
12004 
12005 /// Check if VD needs to be dllexport/dllimport due to being in a
12006 /// dllexport/import function.
12007 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12008   assert(VD->isStaticLocal());
12009 
12010   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12011 
12012   // Find outermost function when VD is in lambda function.
12013   while (FD && !getDLLAttr(FD) &&
12014          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12015          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12016     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12017   }
12018 
12019   if (!FD)
12020     return;
12021 
12022   // Static locals inherit dll attributes from their function.
12023   if (Attr *A = getDLLAttr(FD)) {
12024     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12025     NewAttr->setInherited(true);
12026     VD->addAttr(NewAttr);
12027   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12028     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12029                                                           getASTContext(),
12030                                                           A->getSpellingListIndex());
12031     NewAttr->setInherited(true);
12032     VD->addAttr(NewAttr);
12033 
12034     // Export this function to enforce exporting this static variable even
12035     // if it is not used in this compilation unit.
12036     if (!FD->hasAttr<DLLExportAttr>())
12037       FD->addAttr(NewAttr);
12038 
12039   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12040     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12041                                                           getASTContext(),
12042                                                           A->getSpellingListIndex());
12043     NewAttr->setInherited(true);
12044     VD->addAttr(NewAttr);
12045   }
12046 }
12047 
12048 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12049 /// any semantic actions necessary after any initializer has been attached.
12050 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12051   // Note that we are no longer parsing the initializer for this declaration.
12052   ParsingInitForAutoVars.erase(ThisDecl);
12053 
12054   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12055   if (!VD)
12056     return;
12057 
12058   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12059   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12060       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12061     if (PragmaClangBSSSection.Valid)
12062       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12063                                                             PragmaClangBSSSection.SectionName,
12064                                                             PragmaClangBSSSection.PragmaLocation));
12065     if (PragmaClangDataSection.Valid)
12066       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12067                                                              PragmaClangDataSection.SectionName,
12068                                                              PragmaClangDataSection.PragmaLocation));
12069     if (PragmaClangRodataSection.Valid)
12070       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12071                                                                PragmaClangRodataSection.SectionName,
12072                                                                PragmaClangRodataSection.PragmaLocation));
12073   }
12074 
12075   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12076     for (auto *BD : DD->bindings()) {
12077       FinalizeDeclaration(BD);
12078     }
12079   }
12080 
12081   checkAttributesAfterMerging(*this, *VD);
12082 
12083   // Perform TLS alignment check here after attributes attached to the variable
12084   // which may affect the alignment have been processed. Only perform the check
12085   // if the target has a maximum TLS alignment (zero means no constraints).
12086   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12087     // Protect the check so that it's not performed on dependent types and
12088     // dependent alignments (we can't determine the alignment in that case).
12089     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12090         !VD->isInvalidDecl()) {
12091       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12092       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12093         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12094           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12095           << (unsigned)MaxAlignChars.getQuantity();
12096       }
12097     }
12098   }
12099 
12100   if (VD->isStaticLocal()) {
12101     CheckStaticLocalForDllExport(VD);
12102 
12103     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12104       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12105       // function, only __shared__ variables or variables without any device
12106       // memory qualifiers may be declared with static storage class.
12107       // Note: It is unclear how a function-scope non-const static variable
12108       // without device memory qualifier is implemented, therefore only static
12109       // const variable without device memory qualifier is allowed.
12110       [&]() {
12111         if (!getLangOpts().CUDA)
12112           return;
12113         if (VD->hasAttr<CUDASharedAttr>())
12114           return;
12115         if (VD->getType().isConstQualified() &&
12116             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12117           return;
12118         if (CUDADiagIfDeviceCode(VD->getLocation(),
12119                                  diag::err_device_static_local_var)
12120             << CurrentCUDATarget())
12121           VD->setInvalidDecl();
12122       }();
12123     }
12124   }
12125 
12126   // Perform check for initializers of device-side global variables.
12127   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12128   // 7.5). We must also apply the same checks to all __shared__
12129   // variables whether they are local or not. CUDA also allows
12130   // constant initializers for __constant__ and __device__ variables.
12131   if (getLangOpts().CUDA)
12132     checkAllowedCUDAInitializer(VD);
12133 
12134   // Grab the dllimport or dllexport attribute off of the VarDecl.
12135   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12136 
12137   // Imported static data members cannot be defined out-of-line.
12138   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12139     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12140         VD->isThisDeclarationADefinition()) {
12141       // We allow definitions of dllimport class template static data members
12142       // with a warning.
12143       CXXRecordDecl *Context =
12144         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12145       bool IsClassTemplateMember =
12146           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12147           Context->getDescribedClassTemplate();
12148 
12149       Diag(VD->getLocation(),
12150            IsClassTemplateMember
12151                ? diag::warn_attribute_dllimport_static_field_definition
12152                : diag::err_attribute_dllimport_static_field_definition);
12153       Diag(IA->getLocation(), diag::note_attribute);
12154       if (!IsClassTemplateMember)
12155         VD->setInvalidDecl();
12156     }
12157   }
12158 
12159   // dllimport/dllexport variables cannot be thread local, their TLS index
12160   // isn't exported with the variable.
12161   if (DLLAttr && VD->getTLSKind()) {
12162     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12163     if (F && getDLLAttr(F)) {
12164       assert(VD->isStaticLocal());
12165       // But if this is a static local in a dlimport/dllexport function, the
12166       // function will never be inlined, which means the var would never be
12167       // imported, so having it marked import/export is safe.
12168     } else {
12169       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12170                                                                     << DLLAttr;
12171       VD->setInvalidDecl();
12172     }
12173   }
12174 
12175   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12176     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12177       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12178       VD->dropAttr<UsedAttr>();
12179     }
12180   }
12181 
12182   const DeclContext *DC = VD->getDeclContext();
12183   // If there's a #pragma GCC visibility in scope, and this isn't a class
12184   // member, set the visibility of this variable.
12185   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12186     AddPushedVisibilityAttribute(VD);
12187 
12188   // FIXME: Warn on unused var template partial specializations.
12189   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12190     MarkUnusedFileScopedDecl(VD);
12191 
12192   // Now we have parsed the initializer and can update the table of magic
12193   // tag values.
12194   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12195       !VD->getType()->isIntegralOrEnumerationType())
12196     return;
12197 
12198   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12199     const Expr *MagicValueExpr = VD->getInit();
12200     if (!MagicValueExpr) {
12201       continue;
12202     }
12203     llvm::APSInt MagicValueInt;
12204     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12205       Diag(I->getRange().getBegin(),
12206            diag::err_type_tag_for_datatype_not_ice)
12207         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12208       continue;
12209     }
12210     if (MagicValueInt.getActiveBits() > 64) {
12211       Diag(I->getRange().getBegin(),
12212            diag::err_type_tag_for_datatype_too_large)
12213         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12214       continue;
12215     }
12216     uint64_t MagicValue = MagicValueInt.getZExtValue();
12217     RegisterTypeTagForDatatype(I->getArgumentKind(),
12218                                MagicValue,
12219                                I->getMatchingCType(),
12220                                I->getLayoutCompatible(),
12221                                I->getMustBeNull());
12222   }
12223 }
12224 
12225 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12226   auto *VD = dyn_cast<VarDecl>(DD);
12227   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12228 }
12229 
12230 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12231                                                    ArrayRef<Decl *> Group) {
12232   SmallVector<Decl*, 8> Decls;
12233 
12234   if (DS.isTypeSpecOwned())
12235     Decls.push_back(DS.getRepAsDecl());
12236 
12237   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12238   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12239   bool DiagnosedMultipleDecomps = false;
12240   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12241   bool DiagnosedNonDeducedAuto = false;
12242 
12243   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12244     if (Decl *D = Group[i]) {
12245       // For declarators, there are some additional syntactic-ish checks we need
12246       // to perform.
12247       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12248         if (!FirstDeclaratorInGroup)
12249           FirstDeclaratorInGroup = DD;
12250         if (!FirstDecompDeclaratorInGroup)
12251           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12252         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12253             !hasDeducedAuto(DD))
12254           FirstNonDeducedAutoInGroup = DD;
12255 
12256         if (FirstDeclaratorInGroup != DD) {
12257           // A decomposition declaration cannot be combined with any other
12258           // declaration in the same group.
12259           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12260             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12261                  diag::err_decomp_decl_not_alone)
12262                 << FirstDeclaratorInGroup->getSourceRange()
12263                 << DD->getSourceRange();
12264             DiagnosedMultipleDecomps = true;
12265           }
12266 
12267           // A declarator that uses 'auto' in any way other than to declare a
12268           // variable with a deduced type cannot be combined with any other
12269           // declarator in the same group.
12270           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12271             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12272                  diag::err_auto_non_deduced_not_alone)
12273                 << FirstNonDeducedAutoInGroup->getType()
12274                        ->hasAutoForTrailingReturnType()
12275                 << FirstDeclaratorInGroup->getSourceRange()
12276                 << DD->getSourceRange();
12277             DiagnosedNonDeducedAuto = true;
12278           }
12279         }
12280       }
12281 
12282       Decls.push_back(D);
12283     }
12284   }
12285 
12286   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12287     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12288       handleTagNumbering(Tag, S);
12289       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12290           getLangOpts().CPlusPlus)
12291         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12292     }
12293   }
12294 
12295   return BuildDeclaratorGroup(Decls);
12296 }
12297 
12298 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12299 /// group, performing any necessary semantic checking.
12300 Sema::DeclGroupPtrTy
12301 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12302   // C++14 [dcl.spec.auto]p7: (DR1347)
12303   //   If the type that replaces the placeholder type is not the same in each
12304   //   deduction, the program is ill-formed.
12305   if (Group.size() > 1) {
12306     QualType Deduced;
12307     VarDecl *DeducedDecl = nullptr;
12308     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12309       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12310       if (!D || D->isInvalidDecl())
12311         break;
12312       DeducedType *DT = D->getType()->getContainedDeducedType();
12313       if (!DT || DT->getDeducedType().isNull())
12314         continue;
12315       if (Deduced.isNull()) {
12316         Deduced = DT->getDeducedType();
12317         DeducedDecl = D;
12318       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12319         auto *AT = dyn_cast<AutoType>(DT);
12320         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12321              diag::err_auto_different_deductions)
12322           << (AT ? (unsigned)AT->getKeyword() : 3)
12323           << Deduced << DeducedDecl->getDeclName()
12324           << DT->getDeducedType() << D->getDeclName()
12325           << DeducedDecl->getInit()->getSourceRange()
12326           << D->getInit()->getSourceRange();
12327         D->setInvalidDecl();
12328         break;
12329       }
12330     }
12331   }
12332 
12333   ActOnDocumentableDecls(Group);
12334 
12335   return DeclGroupPtrTy::make(
12336       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12337 }
12338 
12339 void Sema::ActOnDocumentableDecl(Decl *D) {
12340   ActOnDocumentableDecls(D);
12341 }
12342 
12343 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12344   // Don't parse the comment if Doxygen diagnostics are ignored.
12345   if (Group.empty() || !Group[0])
12346     return;
12347 
12348   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12349                       Group[0]->getLocation()) &&
12350       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12351                       Group[0]->getLocation()))
12352     return;
12353 
12354   if (Group.size() >= 2) {
12355     // This is a decl group.  Normally it will contain only declarations
12356     // produced from declarator list.  But in case we have any definitions or
12357     // additional declaration references:
12358     //   'typedef struct S {} S;'
12359     //   'typedef struct S *S;'
12360     //   'struct S *pS;'
12361     // FinalizeDeclaratorGroup adds these as separate declarations.
12362     Decl *MaybeTagDecl = Group[0];
12363     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12364       Group = Group.slice(1);
12365     }
12366   }
12367 
12368   // See if there are any new comments that are not attached to a decl.
12369   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12370   if (!Comments.empty() &&
12371       !Comments.back()->isAttached()) {
12372     // There is at least one comment that not attached to a decl.
12373     // Maybe it should be attached to one of these decls?
12374     //
12375     // Note that this way we pick up not only comments that precede the
12376     // declaration, but also comments that *follow* the declaration -- thanks to
12377     // the lookahead in the lexer: we've consumed the semicolon and looked
12378     // ahead through comments.
12379     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12380       Context.getCommentForDecl(Group[i], &PP);
12381   }
12382 }
12383 
12384 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12385 /// to introduce parameters into function prototype scope.
12386 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12387   const DeclSpec &DS = D.getDeclSpec();
12388 
12389   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12390 
12391   // C++03 [dcl.stc]p2 also permits 'auto'.
12392   StorageClass SC = SC_None;
12393   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12394     SC = SC_Register;
12395     // In C++11, the 'register' storage class specifier is deprecated.
12396     // In C++17, it is not allowed, but we tolerate it as an extension.
12397     if (getLangOpts().CPlusPlus11) {
12398       Diag(DS.getStorageClassSpecLoc(),
12399            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12400                                      : diag::warn_deprecated_register)
12401         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12402     }
12403   } else if (getLangOpts().CPlusPlus &&
12404              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12405     SC = SC_Auto;
12406   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12407     Diag(DS.getStorageClassSpecLoc(),
12408          diag::err_invalid_storage_class_in_func_decl);
12409     D.getMutableDeclSpec().ClearStorageClassSpecs();
12410   }
12411 
12412   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12413     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12414       << DeclSpec::getSpecifierName(TSCS);
12415   if (DS.isInlineSpecified())
12416     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12417         << getLangOpts().CPlusPlus17;
12418   if (DS.isConstexprSpecified())
12419     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12420       << 0;
12421 
12422   DiagnoseFunctionSpecifiers(DS);
12423 
12424   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12425   QualType parmDeclType = TInfo->getType();
12426 
12427   if (getLangOpts().CPlusPlus) {
12428     // Check that there are no default arguments inside the type of this
12429     // parameter.
12430     CheckExtraCXXDefaultArguments(D);
12431 
12432     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12433     if (D.getCXXScopeSpec().isSet()) {
12434       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12435         << D.getCXXScopeSpec().getRange();
12436       D.getCXXScopeSpec().clear();
12437     }
12438   }
12439 
12440   // Ensure we have a valid name
12441   IdentifierInfo *II = nullptr;
12442   if (D.hasName()) {
12443     II = D.getIdentifier();
12444     if (!II) {
12445       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12446         << GetNameForDeclarator(D).getName();
12447       D.setInvalidType(true);
12448     }
12449   }
12450 
12451   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12452   if (II) {
12453     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12454                    ForVisibleRedeclaration);
12455     LookupName(R, S);
12456     if (R.isSingleResult()) {
12457       NamedDecl *PrevDecl = R.getFoundDecl();
12458       if (PrevDecl->isTemplateParameter()) {
12459         // Maybe we will complain about the shadowed template parameter.
12460         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12461         // Just pretend that we didn't see the previous declaration.
12462         PrevDecl = nullptr;
12463       } else if (S->isDeclScope(PrevDecl)) {
12464         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12465         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12466 
12467         // Recover by removing the name
12468         II = nullptr;
12469         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12470         D.setInvalidType(true);
12471       }
12472     }
12473   }
12474 
12475   // Temporarily put parameter variables in the translation unit, not
12476   // the enclosing context.  This prevents them from accidentally
12477   // looking like class members in C++.
12478   ParmVarDecl *New =
12479       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12480                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12481 
12482   if (D.isInvalidType())
12483     New->setInvalidDecl();
12484 
12485   assert(S->isFunctionPrototypeScope());
12486   assert(S->getFunctionPrototypeDepth() >= 1);
12487   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12488                     S->getNextFunctionPrototypeIndex());
12489 
12490   // Add the parameter declaration into this scope.
12491   S->AddDecl(New);
12492   if (II)
12493     IdResolver.AddDecl(New);
12494 
12495   ProcessDeclAttributes(S, New, D);
12496 
12497   if (D.getDeclSpec().isModulePrivateSpecified())
12498     Diag(New->getLocation(), diag::err_module_private_local)
12499       << 1 << New->getDeclName()
12500       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12501       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12502 
12503   if (New->hasAttr<BlocksAttr>()) {
12504     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12505   }
12506   return New;
12507 }
12508 
12509 /// Synthesizes a variable for a parameter arising from a
12510 /// typedef.
12511 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12512                                               SourceLocation Loc,
12513                                               QualType T) {
12514   /* FIXME: setting StartLoc == Loc.
12515      Would it be worth to modify callers so as to provide proper source
12516      location for the unnamed parameters, embedding the parameter's type? */
12517   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12518                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12519                                            SC_None, nullptr);
12520   Param->setImplicit();
12521   return Param;
12522 }
12523 
12524 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12525   // Don't diagnose unused-parameter errors in template instantiations; we
12526   // will already have done so in the template itself.
12527   if (inTemplateInstantiation())
12528     return;
12529 
12530   for (const ParmVarDecl *Parameter : Parameters) {
12531     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12532         !Parameter->hasAttr<UnusedAttr>()) {
12533       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12534         << Parameter->getDeclName();
12535     }
12536   }
12537 }
12538 
12539 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12540     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12541   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12542     return;
12543 
12544   // Warn if the return value is pass-by-value and larger than the specified
12545   // threshold.
12546   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12547     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12548     if (Size > LangOpts.NumLargeByValueCopy)
12549       Diag(D->getLocation(), diag::warn_return_value_size)
12550           << D->getDeclName() << Size;
12551   }
12552 
12553   // Warn if any parameter is pass-by-value and larger than the specified
12554   // threshold.
12555   for (const ParmVarDecl *Parameter : Parameters) {
12556     QualType T = Parameter->getType();
12557     if (T->isDependentType() || !T.isPODType(Context))
12558       continue;
12559     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12560     if (Size > LangOpts.NumLargeByValueCopy)
12561       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12562           << Parameter->getDeclName() << Size;
12563   }
12564 }
12565 
12566 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12567                                   SourceLocation NameLoc, IdentifierInfo *Name,
12568                                   QualType T, TypeSourceInfo *TSInfo,
12569                                   StorageClass SC) {
12570   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12571   if (getLangOpts().ObjCAutoRefCount &&
12572       T.getObjCLifetime() == Qualifiers::OCL_None &&
12573       T->isObjCLifetimeType()) {
12574 
12575     Qualifiers::ObjCLifetime lifetime;
12576 
12577     // Special cases for arrays:
12578     //   - if it's const, use __unsafe_unretained
12579     //   - otherwise, it's an error
12580     if (T->isArrayType()) {
12581       if (!T.isConstQualified()) {
12582         if (DelayedDiagnostics.shouldDelayDiagnostics())
12583           DelayedDiagnostics.add(
12584               sema::DelayedDiagnostic::makeForbiddenType(
12585               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12586         else
12587           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12588               << TSInfo->getTypeLoc().getSourceRange();
12589       }
12590       lifetime = Qualifiers::OCL_ExplicitNone;
12591     } else {
12592       lifetime = T->getObjCARCImplicitLifetime();
12593     }
12594     T = Context.getLifetimeQualifiedType(T, lifetime);
12595   }
12596 
12597   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12598                                          Context.getAdjustedParameterType(T),
12599                                          TSInfo, SC, nullptr);
12600 
12601   // Parameters can not be abstract class types.
12602   // For record types, this is done by the AbstractClassUsageDiagnoser once
12603   // the class has been completely parsed.
12604   if (!CurContext->isRecord() &&
12605       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12606                              AbstractParamType))
12607     New->setInvalidDecl();
12608 
12609   // Parameter declarators cannot be interface types. All ObjC objects are
12610   // passed by reference.
12611   if (T->isObjCObjectType()) {
12612     SourceLocation TypeEndLoc =
12613         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12614     Diag(NameLoc,
12615          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12616       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12617     T = Context.getObjCObjectPointerType(T);
12618     New->setType(T);
12619   }
12620 
12621   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12622   // duration shall not be qualified by an address-space qualifier."
12623   // Since all parameters have automatic store duration, they can not have
12624   // an address space.
12625   if (T.getAddressSpace() != LangAS::Default &&
12626       // OpenCL allows function arguments declared to be an array of a type
12627       // to be qualified with an address space.
12628       !(getLangOpts().OpenCL &&
12629         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12630     Diag(NameLoc, diag::err_arg_with_address_space);
12631     New->setInvalidDecl();
12632   }
12633 
12634   return New;
12635 }
12636 
12637 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12638                                            SourceLocation LocAfterDecls) {
12639   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12640 
12641   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12642   // for a K&R function.
12643   if (!FTI.hasPrototype) {
12644     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12645       --i;
12646       if (FTI.Params[i].Param == nullptr) {
12647         SmallString<256> Code;
12648         llvm::raw_svector_ostream(Code)
12649             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12650         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12651             << FTI.Params[i].Ident
12652             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12653 
12654         // Implicitly declare the argument as type 'int' for lack of a better
12655         // type.
12656         AttributeFactory attrs;
12657         DeclSpec DS(attrs);
12658         const char* PrevSpec; // unused
12659         unsigned DiagID; // unused
12660         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12661                            DiagID, Context.getPrintingPolicy());
12662         // Use the identifier location for the type source range.
12663         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12664         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12665         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12666         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12667         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12668       }
12669     }
12670   }
12671 }
12672 
12673 Decl *
12674 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12675                               MultiTemplateParamsArg TemplateParameterLists,
12676                               SkipBodyInfo *SkipBody) {
12677   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12678   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12679   Scope *ParentScope = FnBodyScope->getParent();
12680 
12681   D.setFunctionDefinitionKind(FDK_Definition);
12682   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12683   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12684 }
12685 
12686 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12687   Consumer.HandleInlineFunctionDefinition(D);
12688 }
12689 
12690 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12691                              const FunctionDecl*& PossibleZeroParamPrototype) {
12692   // Don't warn about invalid declarations.
12693   if (FD->isInvalidDecl())
12694     return false;
12695 
12696   // Or declarations that aren't global.
12697   if (!FD->isGlobal())
12698     return false;
12699 
12700   // Don't warn about C++ member functions.
12701   if (isa<CXXMethodDecl>(FD))
12702     return false;
12703 
12704   // Don't warn about 'main'.
12705   if (FD->isMain())
12706     return false;
12707 
12708   // Don't warn about inline functions.
12709   if (FD->isInlined())
12710     return false;
12711 
12712   // Don't warn about function templates.
12713   if (FD->getDescribedFunctionTemplate())
12714     return false;
12715 
12716   // Don't warn about function template specializations.
12717   if (FD->isFunctionTemplateSpecialization())
12718     return false;
12719 
12720   // Don't warn for OpenCL kernels.
12721   if (FD->hasAttr<OpenCLKernelAttr>())
12722     return false;
12723 
12724   // Don't warn on explicitly deleted functions.
12725   if (FD->isDeleted())
12726     return false;
12727 
12728   bool MissingPrototype = true;
12729   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12730        Prev; Prev = Prev->getPreviousDecl()) {
12731     // Ignore any declarations that occur in function or method
12732     // scope, because they aren't visible from the header.
12733     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12734       continue;
12735 
12736     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12737     if (FD->getNumParams() == 0)
12738       PossibleZeroParamPrototype = Prev;
12739     break;
12740   }
12741 
12742   return MissingPrototype;
12743 }
12744 
12745 void
12746 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12747                                    const FunctionDecl *EffectiveDefinition,
12748                                    SkipBodyInfo *SkipBody) {
12749   const FunctionDecl *Definition = EffectiveDefinition;
12750   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12751     // If this is a friend function defined in a class template, it does not
12752     // have a body until it is used, nevertheless it is a definition, see
12753     // [temp.inst]p2:
12754     //
12755     // ... for the purpose of determining whether an instantiated redeclaration
12756     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12757     // corresponds to a definition in the template is considered to be a
12758     // definition.
12759     //
12760     // The following code must produce redefinition error:
12761     //
12762     //     template<typename T> struct C20 { friend void func_20() {} };
12763     //     C20<int> c20i;
12764     //     void func_20() {}
12765     //
12766     for (auto I : FD->redecls()) {
12767       if (I != FD && !I->isInvalidDecl() &&
12768           I->getFriendObjectKind() != Decl::FOK_None) {
12769         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12770           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12771             // A merged copy of the same function, instantiated as a member of
12772             // the same class, is OK.
12773             if (declaresSameEntity(OrigFD, Original) &&
12774                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12775                                    cast<Decl>(FD->getLexicalDeclContext())))
12776               continue;
12777           }
12778 
12779           if (Original->isThisDeclarationADefinition()) {
12780             Definition = I;
12781             break;
12782           }
12783         }
12784       }
12785     }
12786   }
12787 
12788   if (!Definition)
12789     // Similar to friend functions a friend function template may be a
12790     // definition and do not have a body if it is instantiated in a class
12791     // template.
12792     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12793       for (auto I : FTD->redecls()) {
12794         auto D = cast<FunctionTemplateDecl>(I);
12795         if (D != FTD) {
12796           assert(!D->isThisDeclarationADefinition() &&
12797                  "More than one definition in redeclaration chain");
12798           if (D->getFriendObjectKind() != Decl::FOK_None)
12799             if (FunctionTemplateDecl *FT =
12800                                        D->getInstantiatedFromMemberTemplate()) {
12801               if (FT->isThisDeclarationADefinition()) {
12802                 Definition = D->getTemplatedDecl();
12803                 break;
12804               }
12805             }
12806         }
12807       }
12808     }
12809 
12810   if (!Definition)
12811     return;
12812 
12813   if (canRedefineFunction(Definition, getLangOpts()))
12814     return;
12815 
12816   // Don't emit an error when this is redefinition of a typo-corrected
12817   // definition.
12818   if (TypoCorrectedFunctionDefinitions.count(Definition))
12819     return;
12820 
12821   // If we don't have a visible definition of the function, and it's inline or
12822   // a template, skip the new definition.
12823   if (SkipBody && !hasVisibleDefinition(Definition) &&
12824       (Definition->getFormalLinkage() == InternalLinkage ||
12825        Definition->isInlined() ||
12826        Definition->getDescribedFunctionTemplate() ||
12827        Definition->getNumTemplateParameterLists())) {
12828     SkipBody->ShouldSkip = true;
12829     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12830     if (auto *TD = Definition->getDescribedFunctionTemplate())
12831       makeMergedDefinitionVisible(TD);
12832     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12833     return;
12834   }
12835 
12836   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12837       Definition->getStorageClass() == SC_Extern)
12838     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12839         << FD->getDeclName() << getLangOpts().CPlusPlus;
12840   else
12841     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12842 
12843   Diag(Definition->getLocation(), diag::note_previous_definition);
12844   FD->setInvalidDecl();
12845 }
12846 
12847 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12848                                    Sema &S) {
12849   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12850 
12851   LambdaScopeInfo *LSI = S.PushLambdaScope();
12852   LSI->CallOperator = CallOperator;
12853   LSI->Lambda = LambdaClass;
12854   LSI->ReturnType = CallOperator->getReturnType();
12855   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12856 
12857   if (LCD == LCD_None)
12858     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12859   else if (LCD == LCD_ByCopy)
12860     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12861   else if (LCD == LCD_ByRef)
12862     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12863   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12864 
12865   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12866   LSI->Mutable = !CallOperator->isConst();
12867 
12868   // Add the captures to the LSI so they can be noted as already
12869   // captured within tryCaptureVar.
12870   auto I = LambdaClass->field_begin();
12871   for (const auto &C : LambdaClass->captures()) {
12872     if (C.capturesVariable()) {
12873       VarDecl *VD = C.getCapturedVar();
12874       if (VD->isInitCapture())
12875         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12876       QualType CaptureType = VD->getType();
12877       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12878       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12879           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12880           /*EllipsisLoc*/C.isPackExpansion()
12881                          ? C.getEllipsisLoc() : SourceLocation(),
12882           CaptureType, /*Expr*/ nullptr);
12883 
12884     } else if (C.capturesThis()) {
12885       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12886                               /*Expr*/ nullptr,
12887                               C.getCaptureKind() == LCK_StarThis);
12888     } else {
12889       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12890     }
12891     ++I;
12892   }
12893 }
12894 
12895 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12896                                     SkipBodyInfo *SkipBody) {
12897   if (!D) {
12898     // Parsing the function declaration failed in some way. Push on a fake scope
12899     // anyway so we can try to parse the function body.
12900     PushFunctionScope();
12901     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12902     return D;
12903   }
12904 
12905   FunctionDecl *FD = nullptr;
12906 
12907   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12908     FD = FunTmpl->getTemplatedDecl();
12909   else
12910     FD = cast<FunctionDecl>(D);
12911 
12912   // Do not push if it is a lambda because one is already pushed when building
12913   // the lambda in ActOnStartOfLambdaDefinition().
12914   if (!isLambdaCallOperator(FD))
12915     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12916 
12917   // Check for defining attributes before the check for redefinition.
12918   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12919     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12920     FD->dropAttr<AliasAttr>();
12921     FD->setInvalidDecl();
12922   }
12923   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12924     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12925     FD->dropAttr<IFuncAttr>();
12926     FD->setInvalidDecl();
12927   }
12928 
12929   // See if this is a redefinition. If 'will have body' is already set, then
12930   // these checks were already performed when it was set.
12931   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12932     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12933 
12934     // If we're skipping the body, we're done. Don't enter the scope.
12935     if (SkipBody && SkipBody->ShouldSkip)
12936       return D;
12937   }
12938 
12939   // Mark this function as "will have a body eventually".  This lets users to
12940   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12941   // this function.
12942   FD->setWillHaveBody();
12943 
12944   // If we are instantiating a generic lambda call operator, push
12945   // a LambdaScopeInfo onto the function stack.  But use the information
12946   // that's already been calculated (ActOnLambdaExpr) to prime the current
12947   // LambdaScopeInfo.
12948   // When the template operator is being specialized, the LambdaScopeInfo,
12949   // has to be properly restored so that tryCaptureVariable doesn't try
12950   // and capture any new variables. In addition when calculating potential
12951   // captures during transformation of nested lambdas, it is necessary to
12952   // have the LSI properly restored.
12953   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12954     assert(inTemplateInstantiation() &&
12955            "There should be an active template instantiation on the stack "
12956            "when instantiating a generic lambda!");
12957     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12958   } else {
12959     // Enter a new function scope
12960     PushFunctionScope();
12961   }
12962 
12963   // Builtin functions cannot be defined.
12964   if (unsigned BuiltinID = FD->getBuiltinID()) {
12965     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12966         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12967       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12968       FD->setInvalidDecl();
12969     }
12970   }
12971 
12972   // The return type of a function definition must be complete
12973   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12974   QualType ResultType = FD->getReturnType();
12975   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12976       !FD->isInvalidDecl() &&
12977       RequireCompleteType(FD->getLocation(), ResultType,
12978                           diag::err_func_def_incomplete_result))
12979     FD->setInvalidDecl();
12980 
12981   if (FnBodyScope)
12982     PushDeclContext(FnBodyScope, FD);
12983 
12984   // Check the validity of our function parameters
12985   CheckParmsForFunctionDef(FD->parameters(),
12986                            /*CheckParameterNames=*/true);
12987 
12988   // Add non-parameter declarations already in the function to the current
12989   // scope.
12990   if (FnBodyScope) {
12991     for (Decl *NPD : FD->decls()) {
12992       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12993       if (!NonParmDecl)
12994         continue;
12995       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12996              "parameters should not be in newly created FD yet");
12997 
12998       // If the decl has a name, make it accessible in the current scope.
12999       if (NonParmDecl->getDeclName())
13000         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13001 
13002       // Similarly, dive into enums and fish their constants out, making them
13003       // accessible in this scope.
13004       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13005         for (auto *EI : ED->enumerators())
13006           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13007       }
13008     }
13009   }
13010 
13011   // Introduce our parameters into the function scope
13012   for (auto Param : FD->parameters()) {
13013     Param->setOwningFunction(FD);
13014 
13015     // If this has an identifier, add it to the scope stack.
13016     if (Param->getIdentifier() && FnBodyScope) {
13017       CheckShadow(FnBodyScope, Param);
13018 
13019       PushOnScopeChains(Param, FnBodyScope);
13020     }
13021   }
13022 
13023   // Ensure that the function's exception specification is instantiated.
13024   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13025     ResolveExceptionSpec(D->getLocation(), FPT);
13026 
13027   // dllimport cannot be applied to non-inline function definitions.
13028   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13029       !FD->isTemplateInstantiation()) {
13030     assert(!FD->hasAttr<DLLExportAttr>());
13031     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13032     FD->setInvalidDecl();
13033     return D;
13034   }
13035   // We want to attach documentation to original Decl (which might be
13036   // a function template).
13037   ActOnDocumentableDecl(D);
13038   if (getCurLexicalContext()->isObjCContainer() &&
13039       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13040       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13041     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13042 
13043   return D;
13044 }
13045 
13046 /// Given the set of return statements within a function body,
13047 /// compute the variables that are subject to the named return value
13048 /// optimization.
13049 ///
13050 /// Each of the variables that is subject to the named return value
13051 /// optimization will be marked as NRVO variables in the AST, and any
13052 /// return statement that has a marked NRVO variable as its NRVO candidate can
13053 /// use the named return value optimization.
13054 ///
13055 /// This function applies a very simplistic algorithm for NRVO: if every return
13056 /// statement in the scope of a variable has the same NRVO candidate, that
13057 /// candidate is an NRVO variable.
13058 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13059   ReturnStmt **Returns = Scope->Returns.data();
13060 
13061   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13062     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13063       if (!NRVOCandidate->isNRVOVariable())
13064         Returns[I]->setNRVOCandidate(nullptr);
13065     }
13066   }
13067 }
13068 
13069 bool Sema::canDelayFunctionBody(const Declarator &D) {
13070   // We can't delay parsing the body of a constexpr function template (yet).
13071   if (D.getDeclSpec().isConstexprSpecified())
13072     return false;
13073 
13074   // We can't delay parsing the body of a function template with a deduced
13075   // return type (yet).
13076   if (D.getDeclSpec().hasAutoTypeSpec()) {
13077     // If the placeholder introduces a non-deduced trailing return type,
13078     // we can still delay parsing it.
13079     if (D.getNumTypeObjects()) {
13080       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13081       if (Outer.Kind == DeclaratorChunk::Function &&
13082           Outer.Fun.hasTrailingReturnType()) {
13083         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13084         return Ty.isNull() || !Ty->isUndeducedType();
13085       }
13086     }
13087     return false;
13088   }
13089 
13090   return true;
13091 }
13092 
13093 bool Sema::canSkipFunctionBody(Decl *D) {
13094   // We cannot skip the body of a function (or function template) which is
13095   // constexpr, since we may need to evaluate its body in order to parse the
13096   // rest of the file.
13097   // We cannot skip the body of a function with an undeduced return type,
13098   // because any callers of that function need to know the type.
13099   if (const FunctionDecl *FD = D->getAsFunction()) {
13100     if (FD->isConstexpr())
13101       return false;
13102     // We can't simply call Type::isUndeducedType here, because inside template
13103     // auto can be deduced to a dependent type, which is not considered
13104     // "undeduced".
13105     if (FD->getReturnType()->getContainedDeducedType())
13106       return false;
13107   }
13108   return Consumer.shouldSkipFunctionBody(D);
13109 }
13110 
13111 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13112   if (!Decl)
13113     return nullptr;
13114   if (FunctionDecl *FD = Decl->getAsFunction())
13115     FD->setHasSkippedBody();
13116   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13117     MD->setHasSkippedBody();
13118   return Decl;
13119 }
13120 
13121 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13122   return ActOnFinishFunctionBody(D, BodyArg, false);
13123 }
13124 
13125 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13126 /// body.
13127 class ExitFunctionBodyRAII {
13128 public:
13129   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13130   ~ExitFunctionBodyRAII() {
13131     if (!IsLambda)
13132       S.PopExpressionEvaluationContext();
13133   }
13134 
13135 private:
13136   Sema &S;
13137   bool IsLambda = false;
13138 };
13139 
13140 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13141                                     bool IsInstantiation) {
13142   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13143 
13144   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13145   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13146 
13147   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13148     CheckCompletedCoroutineBody(FD, Body);
13149 
13150   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13151   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13152   // meant to pop the context added in ActOnStartOfFunctionDef().
13153   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13154 
13155   if (FD) {
13156     FD->setBody(Body);
13157     FD->setWillHaveBody(false);
13158 
13159     if (getLangOpts().CPlusPlus14) {
13160       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13161           FD->getReturnType()->isUndeducedType()) {
13162         // If the function has a deduced result type but contains no 'return'
13163         // statements, the result type as written must be exactly 'auto', and
13164         // the deduced result type is 'void'.
13165         if (!FD->getReturnType()->getAs<AutoType>()) {
13166           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13167               << FD->getReturnType();
13168           FD->setInvalidDecl();
13169         } else {
13170           // Substitute 'void' for the 'auto' in the type.
13171           TypeLoc ResultType = getReturnTypeLoc(FD);
13172           Context.adjustDeducedFunctionResultType(
13173               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13174         }
13175       }
13176     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13177       // In C++11, we don't use 'auto' deduction rules for lambda call
13178       // operators because we don't support return type deduction.
13179       auto *LSI = getCurLambda();
13180       if (LSI->HasImplicitReturnType) {
13181         deduceClosureReturnType(*LSI);
13182 
13183         // C++11 [expr.prim.lambda]p4:
13184         //   [...] if there are no return statements in the compound-statement
13185         //   [the deduced type is] the type void
13186         QualType RetType =
13187             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13188 
13189         // Update the return type to the deduced type.
13190         const FunctionProtoType *Proto =
13191             FD->getType()->getAs<FunctionProtoType>();
13192         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13193                                             Proto->getExtProtoInfo()));
13194       }
13195     }
13196 
13197     // If the function implicitly returns zero (like 'main') or is naked,
13198     // don't complain about missing return statements.
13199     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13200       WP.disableCheckFallThrough();
13201 
13202     // MSVC permits the use of pure specifier (=0) on function definition,
13203     // defined at class scope, warn about this non-standard construct.
13204     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13205       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13206 
13207     if (!FD->isInvalidDecl()) {
13208       // Don't diagnose unused parameters of defaulted or deleted functions.
13209       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13210         DiagnoseUnusedParameters(FD->parameters());
13211       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13212                                              FD->getReturnType(), FD);
13213 
13214       // If this is a structor, we need a vtable.
13215       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13216         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13217       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13218         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13219 
13220       // Try to apply the named return value optimization. We have to check
13221       // if we can do this here because lambdas keep return statements around
13222       // to deduce an implicit return type.
13223       if (FD->getReturnType()->isRecordType() &&
13224           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13225         computeNRVO(Body, getCurFunction());
13226     }
13227 
13228     // GNU warning -Wmissing-prototypes:
13229     //   Warn if a global function is defined without a previous
13230     //   prototype declaration. This warning is issued even if the
13231     //   definition itself provides a prototype. The aim is to detect
13232     //   global functions that fail to be declared in header files.
13233     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13234     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13235       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13236 
13237       if (PossibleZeroParamPrototype) {
13238         // We found a declaration that is not a prototype,
13239         // but that could be a zero-parameter prototype
13240         if (TypeSourceInfo *TI =
13241                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13242           TypeLoc TL = TI->getTypeLoc();
13243           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13244             Diag(PossibleZeroParamPrototype->getLocation(),
13245                  diag::note_declaration_not_a_prototype)
13246                 << PossibleZeroParamPrototype
13247                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13248         }
13249       }
13250 
13251       // GNU warning -Wstrict-prototypes
13252       //   Warn if K&R function is defined without a previous declaration.
13253       //   This warning is issued only if the definition itself does not provide
13254       //   a prototype. Only K&R definitions do not provide a prototype.
13255       //   An empty list in a function declarator that is part of a definition
13256       //   of that function specifies that the function has no parameters
13257       //   (C99 6.7.5.3p14)
13258       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13259           !LangOpts.CPlusPlus) {
13260         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13261         TypeLoc TL = TI->getTypeLoc();
13262         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13263         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13264       }
13265     }
13266 
13267     // Warn on CPUDispatch with an actual body.
13268     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13269       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13270         if (!CmpndBody->body_empty())
13271           Diag(CmpndBody->body_front()->getBeginLoc(),
13272                diag::warn_dispatch_body_ignored);
13273 
13274     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13275       const CXXMethodDecl *KeyFunction;
13276       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13277           MD->isVirtual() &&
13278           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13279           MD == KeyFunction->getCanonicalDecl()) {
13280         // Update the key-function state if necessary for this ABI.
13281         if (FD->isInlined() &&
13282             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13283           Context.setNonKeyFunction(MD);
13284 
13285           // If the newly-chosen key function is already defined, then we
13286           // need to mark the vtable as used retroactively.
13287           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13288           const FunctionDecl *Definition;
13289           if (KeyFunction && KeyFunction->isDefined(Definition))
13290             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13291         } else {
13292           // We just defined they key function; mark the vtable as used.
13293           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13294         }
13295       }
13296     }
13297 
13298     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13299            "Function parsing confused");
13300   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13301     assert(MD == getCurMethodDecl() && "Method parsing confused");
13302     MD->setBody(Body);
13303     if (!MD->isInvalidDecl()) {
13304       if (!MD->hasSkippedBody())
13305         DiagnoseUnusedParameters(MD->parameters());
13306       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13307                                              MD->getReturnType(), MD);
13308 
13309       if (Body)
13310         computeNRVO(Body, getCurFunction());
13311     }
13312     if (getCurFunction()->ObjCShouldCallSuper) {
13313       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13314           << MD->getSelector().getAsString();
13315       getCurFunction()->ObjCShouldCallSuper = false;
13316     }
13317     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13318       const ObjCMethodDecl *InitMethod = nullptr;
13319       bool isDesignated =
13320           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13321       assert(isDesignated && InitMethod);
13322       (void)isDesignated;
13323 
13324       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13325         auto IFace = MD->getClassInterface();
13326         if (!IFace)
13327           return false;
13328         auto SuperD = IFace->getSuperClass();
13329         if (!SuperD)
13330           return false;
13331         return SuperD->getIdentifier() ==
13332             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13333       };
13334       // Don't issue this warning for unavailable inits or direct subclasses
13335       // of NSObject.
13336       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13337         Diag(MD->getLocation(),
13338              diag::warn_objc_designated_init_missing_super_call);
13339         Diag(InitMethod->getLocation(),
13340              diag::note_objc_designated_init_marked_here);
13341       }
13342       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13343     }
13344     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13345       // Don't issue this warning for unavaialable inits.
13346       if (!MD->isUnavailable())
13347         Diag(MD->getLocation(),
13348              diag::warn_objc_secondary_init_missing_init_call);
13349       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13350     }
13351   } else {
13352     // Parsing the function declaration failed in some way. Pop the fake scope
13353     // we pushed on.
13354     PopFunctionScopeInfo(ActivePolicy, dcl);
13355     return nullptr;
13356   }
13357 
13358   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13359     DiagnoseUnguardedAvailabilityViolations(dcl);
13360 
13361   assert(!getCurFunction()->ObjCShouldCallSuper &&
13362          "This should only be set for ObjC methods, which should have been "
13363          "handled in the block above.");
13364 
13365   // Verify and clean out per-function state.
13366   if (Body && (!FD || !FD->isDefaulted())) {
13367     // C++ constructors that have function-try-blocks can't have return
13368     // statements in the handlers of that block. (C++ [except.handle]p14)
13369     // Verify this.
13370     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13371       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13372 
13373     // Verify that gotos and switch cases don't jump into scopes illegally.
13374     if (getCurFunction()->NeedsScopeChecking() &&
13375         !PP.isCodeCompletionEnabled())
13376       DiagnoseInvalidJumps(Body);
13377 
13378     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13379       if (!Destructor->getParent()->isDependentType())
13380         CheckDestructor(Destructor);
13381 
13382       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13383                                              Destructor->getParent());
13384     }
13385 
13386     // If any errors have occurred, clear out any temporaries that may have
13387     // been leftover. This ensures that these temporaries won't be picked up for
13388     // deletion in some later function.
13389     if (getDiagnostics().hasErrorOccurred() ||
13390         getDiagnostics().getSuppressAllDiagnostics()) {
13391       DiscardCleanupsInEvaluationContext();
13392     }
13393     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13394         !isa<FunctionTemplateDecl>(dcl)) {
13395       // Since the body is valid, issue any analysis-based warnings that are
13396       // enabled.
13397       ActivePolicy = &WP;
13398     }
13399 
13400     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13401         (!CheckConstexprFunctionDecl(FD) ||
13402          !CheckConstexprFunctionBody(FD, Body)))
13403       FD->setInvalidDecl();
13404 
13405     if (FD && FD->hasAttr<NakedAttr>()) {
13406       for (const Stmt *S : Body->children()) {
13407         // Allow local register variables without initializer as they don't
13408         // require prologue.
13409         bool RegisterVariables = false;
13410         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13411           for (const auto *Decl : DS->decls()) {
13412             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13413               RegisterVariables =
13414                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13415               if (!RegisterVariables)
13416                 break;
13417             }
13418           }
13419         }
13420         if (RegisterVariables)
13421           continue;
13422         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13423           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13424           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13425           FD->setInvalidDecl();
13426           break;
13427         }
13428       }
13429     }
13430 
13431     assert(ExprCleanupObjects.size() ==
13432                ExprEvalContexts.back().NumCleanupObjects &&
13433            "Leftover temporaries in function");
13434     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13435     assert(MaybeODRUseExprs.empty() &&
13436            "Leftover expressions for odr-use checking");
13437   }
13438 
13439   if (!IsInstantiation)
13440     PopDeclContext();
13441 
13442   PopFunctionScopeInfo(ActivePolicy, dcl);
13443   // If any errors have occurred, clear out any temporaries that may have
13444   // been leftover. This ensures that these temporaries won't be picked up for
13445   // deletion in some later function.
13446   if (getDiagnostics().hasErrorOccurred()) {
13447     DiscardCleanupsInEvaluationContext();
13448   }
13449 
13450   return dcl;
13451 }
13452 
13453 /// When we finish delayed parsing of an attribute, we must attach it to the
13454 /// relevant Decl.
13455 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13456                                        ParsedAttributes &Attrs) {
13457   // Always attach attributes to the underlying decl.
13458   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13459     D = TD->getTemplatedDecl();
13460   ProcessDeclAttributeList(S, D, Attrs);
13461 
13462   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13463     if (Method->isStatic())
13464       checkThisInStaticMemberFunctionAttributes(Method);
13465 }
13466 
13467 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13468 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13469 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13470                                           IdentifierInfo &II, Scope *S) {
13471   // Find the scope in which the identifier is injected and the corresponding
13472   // DeclContext.
13473   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13474   // In that case, we inject the declaration into the translation unit scope
13475   // instead.
13476   Scope *BlockScope = S;
13477   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13478     BlockScope = BlockScope->getParent();
13479 
13480   Scope *ContextScope = BlockScope;
13481   while (!ContextScope->getEntity())
13482     ContextScope = ContextScope->getParent();
13483   ContextRAII SavedContext(*this, ContextScope->getEntity());
13484 
13485   // Before we produce a declaration for an implicitly defined
13486   // function, see whether there was a locally-scoped declaration of
13487   // this name as a function or variable. If so, use that
13488   // (non-visible) declaration, and complain about it.
13489   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13490   if (ExternCPrev) {
13491     // We still need to inject the function into the enclosing block scope so
13492     // that later (non-call) uses can see it.
13493     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13494 
13495     // C89 footnote 38:
13496     //   If in fact it is not defined as having type "function returning int",
13497     //   the behavior is undefined.
13498     if (!isa<FunctionDecl>(ExternCPrev) ||
13499         !Context.typesAreCompatible(
13500             cast<FunctionDecl>(ExternCPrev)->getType(),
13501             Context.getFunctionNoProtoType(Context.IntTy))) {
13502       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13503           << ExternCPrev << !getLangOpts().C99;
13504       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13505       return ExternCPrev;
13506     }
13507   }
13508 
13509   // Extension in C99.  Legal in C90, but warn about it.
13510   unsigned diag_id;
13511   if (II.getName().startswith("__builtin_"))
13512     diag_id = diag::warn_builtin_unknown;
13513   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13514   else if (getLangOpts().OpenCL)
13515     diag_id = diag::err_opencl_implicit_function_decl;
13516   else if (getLangOpts().C99)
13517     diag_id = diag::ext_implicit_function_decl;
13518   else
13519     diag_id = diag::warn_implicit_function_decl;
13520   Diag(Loc, diag_id) << &II;
13521 
13522   // If we found a prior declaration of this function, don't bother building
13523   // another one. We've already pushed that one into scope, so there's nothing
13524   // more to do.
13525   if (ExternCPrev)
13526     return ExternCPrev;
13527 
13528   // Because typo correction is expensive, only do it if the implicit
13529   // function declaration is going to be treated as an error.
13530   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13531     TypoCorrection Corrected;
13532     if (S &&
13533         (Corrected = CorrectTypo(
13534              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13535              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13536       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13537                    /*ErrorRecovery*/false);
13538   }
13539 
13540   // Set a Declarator for the implicit definition: int foo();
13541   const char *Dummy;
13542   AttributeFactory attrFactory;
13543   DeclSpec DS(attrFactory);
13544   unsigned DiagID;
13545   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13546                                   Context.getPrintingPolicy());
13547   (void)Error; // Silence warning.
13548   assert(!Error && "Error setting up implicit decl!");
13549   SourceLocation NoLoc;
13550   Declarator D(DS, DeclaratorContext::BlockContext);
13551   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13552                                              /*IsAmbiguous=*/false,
13553                                              /*LParenLoc=*/NoLoc,
13554                                              /*Params=*/nullptr,
13555                                              /*NumParams=*/0,
13556                                              /*EllipsisLoc=*/NoLoc,
13557                                              /*RParenLoc=*/NoLoc,
13558                                              /*RefQualifierIsLvalueRef=*/true,
13559                                              /*RefQualifierLoc=*/NoLoc,
13560                                              /*MutableLoc=*/NoLoc, EST_None,
13561                                              /*ESpecRange=*/SourceRange(),
13562                                              /*Exceptions=*/nullptr,
13563                                              /*ExceptionRanges=*/nullptr,
13564                                              /*NumExceptions=*/0,
13565                                              /*NoexceptExpr=*/nullptr,
13566                                              /*ExceptionSpecTokens=*/nullptr,
13567                                              /*DeclsInPrototype=*/None, Loc,
13568                                              Loc, D),
13569                 std::move(DS.getAttributes()), SourceLocation());
13570   D.SetIdentifier(&II, Loc);
13571 
13572   // Insert this function into the enclosing block scope.
13573   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13574   FD->setImplicit();
13575 
13576   AddKnownFunctionAttributes(FD);
13577 
13578   return FD;
13579 }
13580 
13581 /// Adds any function attributes that we know a priori based on
13582 /// the declaration of this function.
13583 ///
13584 /// These attributes can apply both to implicitly-declared builtins
13585 /// (like __builtin___printf_chk) or to library-declared functions
13586 /// like NSLog or printf.
13587 ///
13588 /// We need to check for duplicate attributes both here and where user-written
13589 /// attributes are applied to declarations.
13590 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13591   if (FD->isInvalidDecl())
13592     return;
13593 
13594   // If this is a built-in function, map its builtin attributes to
13595   // actual attributes.
13596   if (unsigned BuiltinID = FD->getBuiltinID()) {
13597     // Handle printf-formatting attributes.
13598     unsigned FormatIdx;
13599     bool HasVAListArg;
13600     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13601       if (!FD->hasAttr<FormatAttr>()) {
13602         const char *fmt = "printf";
13603         unsigned int NumParams = FD->getNumParams();
13604         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13605             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13606           fmt = "NSString";
13607         FD->addAttr(FormatAttr::CreateImplicit(Context,
13608                                                &Context.Idents.get(fmt),
13609                                                FormatIdx+1,
13610                                                HasVAListArg ? 0 : FormatIdx+2,
13611                                                FD->getLocation()));
13612       }
13613     }
13614     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13615                                              HasVAListArg)) {
13616      if (!FD->hasAttr<FormatAttr>())
13617        FD->addAttr(FormatAttr::CreateImplicit(Context,
13618                                               &Context.Idents.get("scanf"),
13619                                               FormatIdx+1,
13620                                               HasVAListArg ? 0 : FormatIdx+2,
13621                                               FD->getLocation()));
13622     }
13623 
13624     // Handle automatically recognized callbacks.
13625     SmallVector<int, 4> Encoding;
13626     if (!FD->hasAttr<CallbackAttr>() &&
13627         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13628       FD->addAttr(CallbackAttr::CreateImplicit(
13629           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13630 
13631     // Mark const if we don't care about errno and that is the only thing
13632     // preventing the function from being const. This allows IRgen to use LLVM
13633     // intrinsics for such functions.
13634     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13635         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13636       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13637 
13638     // We make "fma" on some platforms const because we know it does not set
13639     // errno in those environments even though it could set errno based on the
13640     // C standard.
13641     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13642     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13643         !FD->hasAttr<ConstAttr>()) {
13644       switch (BuiltinID) {
13645       case Builtin::BI__builtin_fma:
13646       case Builtin::BI__builtin_fmaf:
13647       case Builtin::BI__builtin_fmal:
13648       case Builtin::BIfma:
13649       case Builtin::BIfmaf:
13650       case Builtin::BIfmal:
13651         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13652         break;
13653       default:
13654         break;
13655       }
13656     }
13657 
13658     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13659         !FD->hasAttr<ReturnsTwiceAttr>())
13660       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13661                                          FD->getLocation()));
13662     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13663       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13664     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13665       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13666     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13667       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13668     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13669         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13670       // Add the appropriate attribute, depending on the CUDA compilation mode
13671       // and which target the builtin belongs to. For example, during host
13672       // compilation, aux builtins are __device__, while the rest are __host__.
13673       if (getLangOpts().CUDAIsDevice !=
13674           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13675         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13676       else
13677         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13678     }
13679   }
13680 
13681   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13682   // throw, add an implicit nothrow attribute to any extern "C" function we come
13683   // across.
13684   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13685       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13686     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13687     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13688       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13689   }
13690 
13691   IdentifierInfo *Name = FD->getIdentifier();
13692   if (!Name)
13693     return;
13694   if ((!getLangOpts().CPlusPlus &&
13695        FD->getDeclContext()->isTranslationUnit()) ||
13696       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13697        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13698        LinkageSpecDecl::lang_c)) {
13699     // Okay: this could be a libc/libm/Objective-C function we know
13700     // about.
13701   } else
13702     return;
13703 
13704   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13705     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13706     // target-specific builtins, perhaps?
13707     if (!FD->hasAttr<FormatAttr>())
13708       FD->addAttr(FormatAttr::CreateImplicit(Context,
13709                                              &Context.Idents.get("printf"), 2,
13710                                              Name->isStr("vasprintf") ? 0 : 3,
13711                                              FD->getLocation()));
13712   }
13713 
13714   if (Name->isStr("__CFStringMakeConstantString")) {
13715     // We already have a __builtin___CFStringMakeConstantString,
13716     // but builds that use -fno-constant-cfstrings don't go through that.
13717     if (!FD->hasAttr<FormatArgAttr>())
13718       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13719                                                 FD->getLocation()));
13720   }
13721 }
13722 
13723 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13724                                     TypeSourceInfo *TInfo) {
13725   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13726   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13727 
13728   if (!TInfo) {
13729     assert(D.isInvalidType() && "no declarator info for valid type");
13730     TInfo = Context.getTrivialTypeSourceInfo(T);
13731   }
13732 
13733   // Scope manipulation handled by caller.
13734   TypedefDecl *NewTD =
13735       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13736                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13737 
13738   // Bail out immediately if we have an invalid declaration.
13739   if (D.isInvalidType()) {
13740     NewTD->setInvalidDecl();
13741     return NewTD;
13742   }
13743 
13744   if (D.getDeclSpec().isModulePrivateSpecified()) {
13745     if (CurContext->isFunctionOrMethod())
13746       Diag(NewTD->getLocation(), diag::err_module_private_local)
13747         << 2 << NewTD->getDeclName()
13748         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13749         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13750     else
13751       NewTD->setModulePrivate();
13752   }
13753 
13754   // C++ [dcl.typedef]p8:
13755   //   If the typedef declaration defines an unnamed class (or
13756   //   enum), the first typedef-name declared by the declaration
13757   //   to be that class type (or enum type) is used to denote the
13758   //   class type (or enum type) for linkage purposes only.
13759   // We need to check whether the type was declared in the declaration.
13760   switch (D.getDeclSpec().getTypeSpecType()) {
13761   case TST_enum:
13762   case TST_struct:
13763   case TST_interface:
13764   case TST_union:
13765   case TST_class: {
13766     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13767     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13768     break;
13769   }
13770 
13771   default:
13772     break;
13773   }
13774 
13775   return NewTD;
13776 }
13777 
13778 /// Check that this is a valid underlying type for an enum declaration.
13779 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13780   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13781   QualType T = TI->getType();
13782 
13783   if (T->isDependentType())
13784     return false;
13785 
13786   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13787     if (BT->isInteger())
13788       return false;
13789 
13790   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13791   return true;
13792 }
13793 
13794 /// Check whether this is a valid redeclaration of a previous enumeration.
13795 /// \return true if the redeclaration was invalid.
13796 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13797                                   QualType EnumUnderlyingTy, bool IsFixed,
13798                                   const EnumDecl *Prev) {
13799   if (IsScoped != Prev->isScoped()) {
13800     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13801       << Prev->isScoped();
13802     Diag(Prev->getLocation(), diag::note_previous_declaration);
13803     return true;
13804   }
13805 
13806   if (IsFixed && Prev->isFixed()) {
13807     if (!EnumUnderlyingTy->isDependentType() &&
13808         !Prev->getIntegerType()->isDependentType() &&
13809         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13810                                         Prev->getIntegerType())) {
13811       // TODO: Highlight the underlying type of the redeclaration.
13812       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13813         << EnumUnderlyingTy << Prev->getIntegerType();
13814       Diag(Prev->getLocation(), diag::note_previous_declaration)
13815           << Prev->getIntegerTypeRange();
13816       return true;
13817     }
13818   } else if (IsFixed != Prev->isFixed()) {
13819     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13820       << Prev->isFixed();
13821     Diag(Prev->getLocation(), diag::note_previous_declaration);
13822     return true;
13823   }
13824 
13825   return false;
13826 }
13827 
13828 /// Get diagnostic %select index for tag kind for
13829 /// redeclaration diagnostic message.
13830 /// WARNING: Indexes apply to particular diagnostics only!
13831 ///
13832 /// \returns diagnostic %select index.
13833 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13834   switch (Tag) {
13835   case TTK_Struct: return 0;
13836   case TTK_Interface: return 1;
13837   case TTK_Class:  return 2;
13838   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13839   }
13840 }
13841 
13842 /// Determine if tag kind is a class-key compatible with
13843 /// class for redeclaration (class, struct, or __interface).
13844 ///
13845 /// \returns true iff the tag kind is compatible.
13846 static bool isClassCompatTagKind(TagTypeKind Tag)
13847 {
13848   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13849 }
13850 
13851 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13852                                              TagTypeKind TTK) {
13853   if (isa<TypedefDecl>(PrevDecl))
13854     return NTK_Typedef;
13855   else if (isa<TypeAliasDecl>(PrevDecl))
13856     return NTK_TypeAlias;
13857   else if (isa<ClassTemplateDecl>(PrevDecl))
13858     return NTK_Template;
13859   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13860     return NTK_TypeAliasTemplate;
13861   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13862     return NTK_TemplateTemplateArgument;
13863   switch (TTK) {
13864   case TTK_Struct:
13865   case TTK_Interface:
13866   case TTK_Class:
13867     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13868   case TTK_Union:
13869     return NTK_NonUnion;
13870   case TTK_Enum:
13871     return NTK_NonEnum;
13872   }
13873   llvm_unreachable("invalid TTK");
13874 }
13875 
13876 /// Determine whether a tag with a given kind is acceptable
13877 /// as a redeclaration of the given tag declaration.
13878 ///
13879 /// \returns true if the new tag kind is acceptable, false otherwise.
13880 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13881                                         TagTypeKind NewTag, bool isDefinition,
13882                                         SourceLocation NewTagLoc,
13883                                         const IdentifierInfo *Name) {
13884   // C++ [dcl.type.elab]p3:
13885   //   The class-key or enum keyword present in the
13886   //   elaborated-type-specifier shall agree in kind with the
13887   //   declaration to which the name in the elaborated-type-specifier
13888   //   refers. This rule also applies to the form of
13889   //   elaborated-type-specifier that declares a class-name or
13890   //   friend class since it can be construed as referring to the
13891   //   definition of the class. Thus, in any
13892   //   elaborated-type-specifier, the enum keyword shall be used to
13893   //   refer to an enumeration (7.2), the union class-key shall be
13894   //   used to refer to a union (clause 9), and either the class or
13895   //   struct class-key shall be used to refer to a class (clause 9)
13896   //   declared using the class or struct class-key.
13897   TagTypeKind OldTag = Previous->getTagKind();
13898   if (OldTag != NewTag &&
13899       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13900     return false;
13901 
13902   // Tags are compatible, but we might still want to warn on mismatched tags.
13903   // Non-class tags can't be mismatched at this point.
13904   if (!isClassCompatTagKind(NewTag))
13905     return true;
13906 
13907   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13908   // by our warning analysis. We don't want to warn about mismatches with (eg)
13909   // declarations in system headers that are designed to be specialized, but if
13910   // a user asks us to warn, we should warn if their code contains mismatched
13911   // declarations.
13912   auto IsIgnoredLoc = [&](SourceLocation Loc) {
13913     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13914                                       Loc);
13915   };
13916   if (IsIgnoredLoc(NewTagLoc))
13917     return true;
13918 
13919   auto IsIgnored = [&](const TagDecl *Tag) {
13920     return IsIgnoredLoc(Tag->getLocation());
13921   };
13922   while (IsIgnored(Previous)) {
13923     Previous = Previous->getPreviousDecl();
13924     if (!Previous)
13925       return true;
13926     OldTag = Previous->getTagKind();
13927   }
13928 
13929   bool isTemplate = false;
13930   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13931     isTemplate = Record->getDescribedClassTemplate();
13932 
13933   if (inTemplateInstantiation()) {
13934     if (OldTag != NewTag) {
13935       // In a template instantiation, do not offer fix-its for tag mismatches
13936       // since they usually mess up the template instead of fixing the problem.
13937       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13938         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13939         << getRedeclDiagFromTagKind(OldTag);
13940       // FIXME: Note previous location?
13941     }
13942     return true;
13943   }
13944 
13945   if (isDefinition) {
13946     // On definitions, check all previous tags and issue a fix-it for each
13947     // one that doesn't match the current tag.
13948     if (Previous->getDefinition()) {
13949       // Don't suggest fix-its for redefinitions.
13950       return true;
13951     }
13952 
13953     bool previousMismatch = false;
13954     for (const TagDecl *I : Previous->redecls()) {
13955       if (I->getTagKind() != NewTag) {
13956         // Ignore previous declarations for which the warning was disabled.
13957         if (IsIgnored(I))
13958           continue;
13959 
13960         if (!previousMismatch) {
13961           previousMismatch = true;
13962           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13963             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13964             << getRedeclDiagFromTagKind(I->getTagKind());
13965         }
13966         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13967           << getRedeclDiagFromTagKind(NewTag)
13968           << FixItHint::CreateReplacement(I->getInnerLocStart(),
13969                TypeWithKeyword::getTagTypeKindName(NewTag));
13970       }
13971     }
13972     return true;
13973   }
13974 
13975   // Identify the prevailing tag kind: this is the kind of the definition (if
13976   // there is a non-ignored definition), or otherwise the kind of the prior
13977   // (non-ignored) declaration.
13978   const TagDecl *PrevDef = Previous->getDefinition();
13979   if (PrevDef && IsIgnored(PrevDef))
13980     PrevDef = nullptr;
13981   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
13982   if (Redecl->getTagKind() != NewTag) {
13983     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13984       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13985       << getRedeclDiagFromTagKind(OldTag);
13986     Diag(Redecl->getLocation(), diag::note_previous_use);
13987 
13988     // If there is a previous definition, suggest a fix-it.
13989     if (PrevDef) {
13990       Diag(NewTagLoc, diag::note_struct_class_suggestion)
13991         << getRedeclDiagFromTagKind(Redecl->getTagKind())
13992         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13993              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13994     }
13995   }
13996 
13997   return true;
13998 }
13999 
14000 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14001 /// from an outer enclosing namespace or file scope inside a friend declaration.
14002 /// This should provide the commented out code in the following snippet:
14003 ///   namespace N {
14004 ///     struct X;
14005 ///     namespace M {
14006 ///       struct Y { friend struct /*N::*/ X; };
14007 ///     }
14008 ///   }
14009 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14010                                          SourceLocation NameLoc) {
14011   // While the decl is in a namespace, do repeated lookup of that name and see
14012   // if we get the same namespace back.  If we do not, continue until
14013   // translation unit scope, at which point we have a fully qualified NNS.
14014   SmallVector<IdentifierInfo *, 4> Namespaces;
14015   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14016   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14017     // This tag should be declared in a namespace, which can only be enclosed by
14018     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14019     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14020     if (!Namespace || Namespace->isAnonymousNamespace())
14021       return FixItHint();
14022     IdentifierInfo *II = Namespace->getIdentifier();
14023     Namespaces.push_back(II);
14024     NamedDecl *Lookup = SemaRef.LookupSingleName(
14025         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14026     if (Lookup == Namespace)
14027       break;
14028   }
14029 
14030   // Once we have all the namespaces, reverse them to go outermost first, and
14031   // build an NNS.
14032   SmallString<64> Insertion;
14033   llvm::raw_svector_ostream OS(Insertion);
14034   if (DC->isTranslationUnit())
14035     OS << "::";
14036   std::reverse(Namespaces.begin(), Namespaces.end());
14037   for (auto *II : Namespaces)
14038     OS << II->getName() << "::";
14039   return FixItHint::CreateInsertion(NameLoc, Insertion);
14040 }
14041 
14042 /// Determine whether a tag originally declared in context \p OldDC can
14043 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14044 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14045 /// using-declaration).
14046 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14047                                          DeclContext *NewDC) {
14048   OldDC = OldDC->getRedeclContext();
14049   NewDC = NewDC->getRedeclContext();
14050 
14051   if (OldDC->Equals(NewDC))
14052     return true;
14053 
14054   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14055   // encloses the other).
14056   if (S.getLangOpts().MSVCCompat &&
14057       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14058     return true;
14059 
14060   return false;
14061 }
14062 
14063 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14064 /// former case, Name will be non-null.  In the later case, Name will be null.
14065 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14066 /// reference/declaration/definition of a tag.
14067 ///
14068 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14069 /// trailing-type-specifier) other than one in an alias-declaration.
14070 ///
14071 /// \param SkipBody If non-null, will be set to indicate if the caller should
14072 /// skip the definition of this tag and treat it as if it were a declaration.
14073 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14074                      SourceLocation KWLoc, CXXScopeSpec &SS,
14075                      IdentifierInfo *Name, SourceLocation NameLoc,
14076                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14077                      SourceLocation ModulePrivateLoc,
14078                      MultiTemplateParamsArg TemplateParameterLists,
14079                      bool &OwnedDecl, bool &IsDependent,
14080                      SourceLocation ScopedEnumKWLoc,
14081                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14082                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14083                      SkipBodyInfo *SkipBody) {
14084   // If this is not a definition, it must have a name.
14085   IdentifierInfo *OrigName = Name;
14086   assert((Name != nullptr || TUK == TUK_Definition) &&
14087          "Nameless record must be a definition!");
14088   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14089 
14090   OwnedDecl = false;
14091   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14092   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14093 
14094   // FIXME: Check member specializations more carefully.
14095   bool isMemberSpecialization = false;
14096   bool Invalid = false;
14097 
14098   // We only need to do this matching if we have template parameters
14099   // or a scope specifier, which also conveniently avoids this work
14100   // for non-C++ cases.
14101   if (TemplateParameterLists.size() > 0 ||
14102       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14103     if (TemplateParameterList *TemplateParams =
14104             MatchTemplateParametersToScopeSpecifier(
14105                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14106                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14107       if (Kind == TTK_Enum) {
14108         Diag(KWLoc, diag::err_enum_template);
14109         return nullptr;
14110       }
14111 
14112       if (TemplateParams->size() > 0) {
14113         // This is a declaration or definition of a class template (which may
14114         // be a member of another template).
14115 
14116         if (Invalid)
14117           return nullptr;
14118 
14119         OwnedDecl = false;
14120         DeclResult Result = CheckClassTemplate(
14121             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14122             AS, ModulePrivateLoc,
14123             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14124             TemplateParameterLists.data(), SkipBody);
14125         return Result.get();
14126       } else {
14127         // The "template<>" header is extraneous.
14128         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14129           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14130         isMemberSpecialization = true;
14131       }
14132     }
14133   }
14134 
14135   // Figure out the underlying type if this a enum declaration. We need to do
14136   // this early, because it's needed to detect if this is an incompatible
14137   // redeclaration.
14138   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14139   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14140 
14141   if (Kind == TTK_Enum) {
14142     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14143       // No underlying type explicitly specified, or we failed to parse the
14144       // type, default to int.
14145       EnumUnderlying = Context.IntTy.getTypePtr();
14146     } else if (UnderlyingType.get()) {
14147       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14148       // integral type; any cv-qualification is ignored.
14149       TypeSourceInfo *TI = nullptr;
14150       GetTypeFromParser(UnderlyingType.get(), &TI);
14151       EnumUnderlying = TI;
14152 
14153       if (CheckEnumUnderlyingType(TI))
14154         // Recover by falling back to int.
14155         EnumUnderlying = Context.IntTy.getTypePtr();
14156 
14157       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14158                                           UPPC_FixedUnderlyingType))
14159         EnumUnderlying = Context.IntTy.getTypePtr();
14160 
14161     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14162       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14163       // of 'int'. However, if this is an unfixed forward declaration, don't set
14164       // the underlying type unless the user enables -fms-compatibility. This
14165       // makes unfixed forward declared enums incomplete and is more conforming.
14166       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14167         EnumUnderlying = Context.IntTy.getTypePtr();
14168     }
14169   }
14170 
14171   DeclContext *SearchDC = CurContext;
14172   DeclContext *DC = CurContext;
14173   bool isStdBadAlloc = false;
14174   bool isStdAlignValT = false;
14175 
14176   RedeclarationKind Redecl = forRedeclarationInCurContext();
14177   if (TUK == TUK_Friend || TUK == TUK_Reference)
14178     Redecl = NotForRedeclaration;
14179 
14180   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14181   /// implemented asks for structural equivalence checking, the returned decl
14182   /// here is passed back to the parser, allowing the tag body to be parsed.
14183   auto createTagFromNewDecl = [&]() -> TagDecl * {
14184     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14185     // If there is an identifier, use the location of the identifier as the
14186     // location of the decl, otherwise use the location of the struct/union
14187     // keyword.
14188     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14189     TagDecl *New = nullptr;
14190 
14191     if (Kind == TTK_Enum) {
14192       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14193                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14194       // If this is an undefined enum, bail.
14195       if (TUK != TUK_Definition && !Invalid)
14196         return nullptr;
14197       if (EnumUnderlying) {
14198         EnumDecl *ED = cast<EnumDecl>(New);
14199         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14200           ED->setIntegerTypeSourceInfo(TI);
14201         else
14202           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14203         ED->setPromotionType(ED->getIntegerType());
14204       }
14205     } else { // struct/union
14206       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14207                                nullptr);
14208     }
14209 
14210     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14211       // Add alignment attributes if necessary; these attributes are checked
14212       // when the ASTContext lays out the structure.
14213       //
14214       // It is important for implementing the correct semantics that this
14215       // happen here (in ActOnTag). The #pragma pack stack is
14216       // maintained as a result of parser callbacks which can occur at
14217       // many points during the parsing of a struct declaration (because
14218       // the #pragma tokens are effectively skipped over during the
14219       // parsing of the struct).
14220       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14221         AddAlignmentAttributesForRecord(RD);
14222         AddMsStructLayoutForRecord(RD);
14223       }
14224     }
14225     New->setLexicalDeclContext(CurContext);
14226     return New;
14227   };
14228 
14229   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14230   if (Name && SS.isNotEmpty()) {
14231     // We have a nested-name tag ('struct foo::bar').
14232 
14233     // Check for invalid 'foo::'.
14234     if (SS.isInvalid()) {
14235       Name = nullptr;
14236       goto CreateNewDecl;
14237     }
14238 
14239     // If this is a friend or a reference to a class in a dependent
14240     // context, don't try to make a decl for it.
14241     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14242       DC = computeDeclContext(SS, false);
14243       if (!DC) {
14244         IsDependent = true;
14245         return nullptr;
14246       }
14247     } else {
14248       DC = computeDeclContext(SS, true);
14249       if (!DC) {
14250         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14251           << SS.getRange();
14252         return nullptr;
14253       }
14254     }
14255 
14256     if (RequireCompleteDeclContext(SS, DC))
14257       return nullptr;
14258 
14259     SearchDC = DC;
14260     // Look-up name inside 'foo::'.
14261     LookupQualifiedName(Previous, DC);
14262 
14263     if (Previous.isAmbiguous())
14264       return nullptr;
14265 
14266     if (Previous.empty()) {
14267       // Name lookup did not find anything. However, if the
14268       // nested-name-specifier refers to the current instantiation,
14269       // and that current instantiation has any dependent base
14270       // classes, we might find something at instantiation time: treat
14271       // this as a dependent elaborated-type-specifier.
14272       // But this only makes any sense for reference-like lookups.
14273       if (Previous.wasNotFoundInCurrentInstantiation() &&
14274           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14275         IsDependent = true;
14276         return nullptr;
14277       }
14278 
14279       // A tag 'foo::bar' must already exist.
14280       Diag(NameLoc, diag::err_not_tag_in_scope)
14281         << Kind << Name << DC << SS.getRange();
14282       Name = nullptr;
14283       Invalid = true;
14284       goto CreateNewDecl;
14285     }
14286   } else if (Name) {
14287     // C++14 [class.mem]p14:
14288     //   If T is the name of a class, then each of the following shall have a
14289     //   name different from T:
14290     //    -- every member of class T that is itself a type
14291     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14292         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14293       return nullptr;
14294 
14295     // If this is a named struct, check to see if there was a previous forward
14296     // declaration or definition.
14297     // FIXME: We're looking into outer scopes here, even when we
14298     // shouldn't be. Doing so can result in ambiguities that we
14299     // shouldn't be diagnosing.
14300     LookupName(Previous, S);
14301 
14302     // When declaring or defining a tag, ignore ambiguities introduced
14303     // by types using'ed into this scope.
14304     if (Previous.isAmbiguous() &&
14305         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14306       LookupResult::Filter F = Previous.makeFilter();
14307       while (F.hasNext()) {
14308         NamedDecl *ND = F.next();
14309         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14310                 SearchDC->getRedeclContext()))
14311           F.erase();
14312       }
14313       F.done();
14314     }
14315 
14316     // C++11 [namespace.memdef]p3:
14317     //   If the name in a friend declaration is neither qualified nor
14318     //   a template-id and the declaration is a function or an
14319     //   elaborated-type-specifier, the lookup to determine whether
14320     //   the entity has been previously declared shall not consider
14321     //   any scopes outside the innermost enclosing namespace.
14322     //
14323     // MSVC doesn't implement the above rule for types, so a friend tag
14324     // declaration may be a redeclaration of a type declared in an enclosing
14325     // scope.  They do implement this rule for friend functions.
14326     //
14327     // Does it matter that this should be by scope instead of by
14328     // semantic context?
14329     if (!Previous.empty() && TUK == TUK_Friend) {
14330       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14331       LookupResult::Filter F = Previous.makeFilter();
14332       bool FriendSawTagOutsideEnclosingNamespace = false;
14333       while (F.hasNext()) {
14334         NamedDecl *ND = F.next();
14335         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14336         if (DC->isFileContext() &&
14337             !EnclosingNS->Encloses(ND->getDeclContext())) {
14338           if (getLangOpts().MSVCCompat)
14339             FriendSawTagOutsideEnclosingNamespace = true;
14340           else
14341             F.erase();
14342         }
14343       }
14344       F.done();
14345 
14346       // Diagnose this MSVC extension in the easy case where lookup would have
14347       // unambiguously found something outside the enclosing namespace.
14348       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14349         NamedDecl *ND = Previous.getFoundDecl();
14350         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14351             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14352       }
14353     }
14354 
14355     // Note:  there used to be some attempt at recovery here.
14356     if (Previous.isAmbiguous())
14357       return nullptr;
14358 
14359     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14360       // FIXME: This makes sure that we ignore the contexts associated
14361       // with C structs, unions, and enums when looking for a matching
14362       // tag declaration or definition. See the similar lookup tweak
14363       // in Sema::LookupName; is there a better way to deal with this?
14364       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14365         SearchDC = SearchDC->getParent();
14366     }
14367   }
14368 
14369   if (Previous.isSingleResult() &&
14370       Previous.getFoundDecl()->isTemplateParameter()) {
14371     // Maybe we will complain about the shadowed template parameter.
14372     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14373     // Just pretend that we didn't see the previous declaration.
14374     Previous.clear();
14375   }
14376 
14377   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14378       DC->Equals(getStdNamespace())) {
14379     if (Name->isStr("bad_alloc")) {
14380       // This is a declaration of or a reference to "std::bad_alloc".
14381       isStdBadAlloc = true;
14382 
14383       // If std::bad_alloc has been implicitly declared (but made invisible to
14384       // name lookup), fill in this implicit declaration as the previous
14385       // declaration, so that the declarations get chained appropriately.
14386       if (Previous.empty() && StdBadAlloc)
14387         Previous.addDecl(getStdBadAlloc());
14388     } else if (Name->isStr("align_val_t")) {
14389       isStdAlignValT = true;
14390       if (Previous.empty() && StdAlignValT)
14391         Previous.addDecl(getStdAlignValT());
14392     }
14393   }
14394 
14395   // If we didn't find a previous declaration, and this is a reference
14396   // (or friend reference), move to the correct scope.  In C++, we
14397   // also need to do a redeclaration lookup there, just in case
14398   // there's a shadow friend decl.
14399   if (Name && Previous.empty() &&
14400       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14401     if (Invalid) goto CreateNewDecl;
14402     assert(SS.isEmpty());
14403 
14404     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14405       // C++ [basic.scope.pdecl]p5:
14406       //   -- for an elaborated-type-specifier of the form
14407       //
14408       //          class-key identifier
14409       //
14410       //      if the elaborated-type-specifier is used in the
14411       //      decl-specifier-seq or parameter-declaration-clause of a
14412       //      function defined in namespace scope, the identifier is
14413       //      declared as a class-name in the namespace that contains
14414       //      the declaration; otherwise, except as a friend
14415       //      declaration, the identifier is declared in the smallest
14416       //      non-class, non-function-prototype scope that contains the
14417       //      declaration.
14418       //
14419       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14420       // C structs and unions.
14421       //
14422       // It is an error in C++ to declare (rather than define) an enum
14423       // type, including via an elaborated type specifier.  We'll
14424       // diagnose that later; for now, declare the enum in the same
14425       // scope as we would have picked for any other tag type.
14426       //
14427       // GNU C also supports this behavior as part of its incomplete
14428       // enum types extension, while GNU C++ does not.
14429       //
14430       // Find the context where we'll be declaring the tag.
14431       // FIXME: We would like to maintain the current DeclContext as the
14432       // lexical context,
14433       SearchDC = getTagInjectionContext(SearchDC);
14434 
14435       // Find the scope where we'll be declaring the tag.
14436       S = getTagInjectionScope(S, getLangOpts());
14437     } else {
14438       assert(TUK == TUK_Friend);
14439       // C++ [namespace.memdef]p3:
14440       //   If a friend declaration in a non-local class first declares a
14441       //   class or function, the friend class or function is a member of
14442       //   the innermost enclosing namespace.
14443       SearchDC = SearchDC->getEnclosingNamespaceContext();
14444     }
14445 
14446     // In C++, we need to do a redeclaration lookup to properly
14447     // diagnose some problems.
14448     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14449     // hidden declaration so that we don't get ambiguity errors when using a
14450     // type declared by an elaborated-type-specifier.  In C that is not correct
14451     // and we should instead merge compatible types found by lookup.
14452     if (getLangOpts().CPlusPlus) {
14453       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14454       LookupQualifiedName(Previous, SearchDC);
14455     } else {
14456       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14457       LookupName(Previous, S);
14458     }
14459   }
14460 
14461   // If we have a known previous declaration to use, then use it.
14462   if (Previous.empty() && SkipBody && SkipBody->Previous)
14463     Previous.addDecl(SkipBody->Previous);
14464 
14465   if (!Previous.empty()) {
14466     NamedDecl *PrevDecl = Previous.getFoundDecl();
14467     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14468 
14469     // It's okay to have a tag decl in the same scope as a typedef
14470     // which hides a tag decl in the same scope.  Finding this
14471     // insanity with a redeclaration lookup can only actually happen
14472     // in C++.
14473     //
14474     // This is also okay for elaborated-type-specifiers, which is
14475     // technically forbidden by the current standard but which is
14476     // okay according to the likely resolution of an open issue;
14477     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14478     if (getLangOpts().CPlusPlus) {
14479       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14480         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14481           TagDecl *Tag = TT->getDecl();
14482           if (Tag->getDeclName() == Name &&
14483               Tag->getDeclContext()->getRedeclContext()
14484                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14485             PrevDecl = Tag;
14486             Previous.clear();
14487             Previous.addDecl(Tag);
14488             Previous.resolveKind();
14489           }
14490         }
14491       }
14492     }
14493 
14494     // If this is a redeclaration of a using shadow declaration, it must
14495     // declare a tag in the same context. In MSVC mode, we allow a
14496     // redefinition if either context is within the other.
14497     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14498       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14499       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14500           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14501           !(OldTag && isAcceptableTagRedeclContext(
14502                           *this, OldTag->getDeclContext(), SearchDC))) {
14503         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14504         Diag(Shadow->getTargetDecl()->getLocation(),
14505              diag::note_using_decl_target);
14506         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14507             << 0;
14508         // Recover by ignoring the old declaration.
14509         Previous.clear();
14510         goto CreateNewDecl;
14511       }
14512     }
14513 
14514     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14515       // If this is a use of a previous tag, or if the tag is already declared
14516       // in the same scope (so that the definition/declaration completes or
14517       // rementions the tag), reuse the decl.
14518       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14519           isDeclInScope(DirectPrevDecl, SearchDC, S,
14520                         SS.isNotEmpty() || isMemberSpecialization)) {
14521         // Make sure that this wasn't declared as an enum and now used as a
14522         // struct or something similar.
14523         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14524                                           TUK == TUK_Definition, KWLoc,
14525                                           Name)) {
14526           bool SafeToContinue
14527             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14528                Kind != TTK_Enum);
14529           if (SafeToContinue)
14530             Diag(KWLoc, diag::err_use_with_wrong_tag)
14531               << Name
14532               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14533                                               PrevTagDecl->getKindName());
14534           else
14535             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14536           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14537 
14538           if (SafeToContinue)
14539             Kind = PrevTagDecl->getTagKind();
14540           else {
14541             // Recover by making this an anonymous redefinition.
14542             Name = nullptr;
14543             Previous.clear();
14544             Invalid = true;
14545           }
14546         }
14547 
14548         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14549           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14550 
14551           // If this is an elaborated-type-specifier for a scoped enumeration,
14552           // the 'class' keyword is not necessary and not permitted.
14553           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14554             if (ScopedEnum)
14555               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14556                 << PrevEnum->isScoped()
14557                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14558             return PrevTagDecl;
14559           }
14560 
14561           QualType EnumUnderlyingTy;
14562           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14563             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14564           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14565             EnumUnderlyingTy = QualType(T, 0);
14566 
14567           // All conflicts with previous declarations are recovered by
14568           // returning the previous declaration, unless this is a definition,
14569           // in which case we want the caller to bail out.
14570           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14571                                      ScopedEnum, EnumUnderlyingTy,
14572                                      IsFixed, PrevEnum))
14573             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14574         }
14575 
14576         // C++11 [class.mem]p1:
14577         //   A member shall not be declared twice in the member-specification,
14578         //   except that a nested class or member class template can be declared
14579         //   and then later defined.
14580         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14581             S->isDeclScope(PrevDecl)) {
14582           Diag(NameLoc, diag::ext_member_redeclared);
14583           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14584         }
14585 
14586         if (!Invalid) {
14587           // If this is a use, just return the declaration we found, unless
14588           // we have attributes.
14589           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14590             if (!Attrs.empty()) {
14591               // FIXME: Diagnose these attributes. For now, we create a new
14592               // declaration to hold them.
14593             } else if (TUK == TUK_Reference &&
14594                        (PrevTagDecl->getFriendObjectKind() ==
14595                             Decl::FOK_Undeclared ||
14596                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14597                        SS.isEmpty()) {
14598               // This declaration is a reference to an existing entity, but
14599               // has different visibility from that entity: it either makes
14600               // a friend visible or it makes a type visible in a new module.
14601               // In either case, create a new declaration. We only do this if
14602               // the declaration would have meant the same thing if no prior
14603               // declaration were found, that is, if it was found in the same
14604               // scope where we would have injected a declaration.
14605               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14606                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14607                 return PrevTagDecl;
14608               // This is in the injected scope, create a new declaration in
14609               // that scope.
14610               S = getTagInjectionScope(S, getLangOpts());
14611             } else {
14612               return PrevTagDecl;
14613             }
14614           }
14615 
14616           // Diagnose attempts to redefine a tag.
14617           if (TUK == TUK_Definition) {
14618             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14619               // If we're defining a specialization and the previous definition
14620               // is from an implicit instantiation, don't emit an error
14621               // here; we'll catch this in the general case below.
14622               bool IsExplicitSpecializationAfterInstantiation = false;
14623               if (isMemberSpecialization) {
14624                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14625                   IsExplicitSpecializationAfterInstantiation =
14626                     RD->getTemplateSpecializationKind() !=
14627                     TSK_ExplicitSpecialization;
14628                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14629                   IsExplicitSpecializationAfterInstantiation =
14630                     ED->getTemplateSpecializationKind() !=
14631                     TSK_ExplicitSpecialization;
14632               }
14633 
14634               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14635               // not keep more that one definition around (merge them). However,
14636               // ensure the decl passes the structural compatibility check in
14637               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14638               NamedDecl *Hidden = nullptr;
14639               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14640                 // There is a definition of this tag, but it is not visible. We
14641                 // explicitly make use of C++'s one definition rule here, and
14642                 // assume that this definition is identical to the hidden one
14643                 // we already have. Make the existing definition visible and
14644                 // use it in place of this one.
14645                 if (!getLangOpts().CPlusPlus) {
14646                   // Postpone making the old definition visible until after we
14647                   // complete parsing the new one and do the structural
14648                   // comparison.
14649                   SkipBody->CheckSameAsPrevious = true;
14650                   SkipBody->New = createTagFromNewDecl();
14651                   SkipBody->Previous = Def;
14652                   return Def;
14653                 } else {
14654                   SkipBody->ShouldSkip = true;
14655                   SkipBody->Previous = Def;
14656                   makeMergedDefinitionVisible(Hidden);
14657                   // Carry on and handle it like a normal definition. We'll
14658                   // skip starting the definitiion later.
14659                 }
14660               } else if (!IsExplicitSpecializationAfterInstantiation) {
14661                 // A redeclaration in function prototype scope in C isn't
14662                 // visible elsewhere, so merely issue a warning.
14663                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14664                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14665                 else
14666                   Diag(NameLoc, diag::err_redefinition) << Name;
14667                 notePreviousDefinition(Def,
14668                                        NameLoc.isValid() ? NameLoc : KWLoc);
14669                 // If this is a redefinition, recover by making this
14670                 // struct be anonymous, which will make any later
14671                 // references get the previous definition.
14672                 Name = nullptr;
14673                 Previous.clear();
14674                 Invalid = true;
14675               }
14676             } else {
14677               // If the type is currently being defined, complain
14678               // about a nested redefinition.
14679               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14680               if (TD->isBeingDefined()) {
14681                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14682                 Diag(PrevTagDecl->getLocation(),
14683                      diag::note_previous_definition);
14684                 Name = nullptr;
14685                 Previous.clear();
14686                 Invalid = true;
14687               }
14688             }
14689 
14690             // Okay, this is definition of a previously declared or referenced
14691             // tag. We're going to create a new Decl for it.
14692           }
14693 
14694           // Okay, we're going to make a redeclaration.  If this is some kind
14695           // of reference, make sure we build the redeclaration in the same DC
14696           // as the original, and ignore the current access specifier.
14697           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14698             SearchDC = PrevTagDecl->getDeclContext();
14699             AS = AS_none;
14700           }
14701         }
14702         // If we get here we have (another) forward declaration or we
14703         // have a definition.  Just create a new decl.
14704 
14705       } else {
14706         // If we get here, this is a definition of a new tag type in a nested
14707         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14708         // new decl/type.  We set PrevDecl to NULL so that the entities
14709         // have distinct types.
14710         Previous.clear();
14711       }
14712       // If we get here, we're going to create a new Decl. If PrevDecl
14713       // is non-NULL, it's a definition of the tag declared by
14714       // PrevDecl. If it's NULL, we have a new definition.
14715 
14716     // Otherwise, PrevDecl is not a tag, but was found with tag
14717     // lookup.  This is only actually possible in C++, where a few
14718     // things like templates still live in the tag namespace.
14719     } else {
14720       // Use a better diagnostic if an elaborated-type-specifier
14721       // found the wrong kind of type on the first
14722       // (non-redeclaration) lookup.
14723       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14724           !Previous.isForRedeclaration()) {
14725         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14726         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14727                                                        << Kind;
14728         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14729         Invalid = true;
14730 
14731       // Otherwise, only diagnose if the declaration is in scope.
14732       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14733                                 SS.isNotEmpty() || isMemberSpecialization)) {
14734         // do nothing
14735 
14736       // Diagnose implicit declarations introduced by elaborated types.
14737       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14738         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14739         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14740         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14741         Invalid = true;
14742 
14743       // Otherwise it's a declaration.  Call out a particularly common
14744       // case here.
14745       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14746         unsigned Kind = 0;
14747         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14748         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14749           << Name << Kind << TND->getUnderlyingType();
14750         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14751         Invalid = true;
14752 
14753       // Otherwise, diagnose.
14754       } else {
14755         // The tag name clashes with something else in the target scope,
14756         // issue an error and recover by making this tag be anonymous.
14757         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14758         notePreviousDefinition(PrevDecl, NameLoc);
14759         Name = nullptr;
14760         Invalid = true;
14761       }
14762 
14763       // The existing declaration isn't relevant to us; we're in a
14764       // new scope, so clear out the previous declaration.
14765       Previous.clear();
14766     }
14767   }
14768 
14769 CreateNewDecl:
14770 
14771   TagDecl *PrevDecl = nullptr;
14772   if (Previous.isSingleResult())
14773     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14774 
14775   // If there is an identifier, use the location of the identifier as the
14776   // location of the decl, otherwise use the location of the struct/union
14777   // keyword.
14778   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14779 
14780   // Otherwise, create a new declaration. If there is a previous
14781   // declaration of the same entity, the two will be linked via
14782   // PrevDecl.
14783   TagDecl *New;
14784 
14785   if (Kind == TTK_Enum) {
14786     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14787     // enum X { A, B, C } D;    D should chain to X.
14788     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14789                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14790                            ScopedEnumUsesClassTag, IsFixed);
14791 
14792     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14793       StdAlignValT = cast<EnumDecl>(New);
14794 
14795     // If this is an undefined enum, warn.
14796     if (TUK != TUK_Definition && !Invalid) {
14797       TagDecl *Def;
14798       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14799         // C++0x: 7.2p2: opaque-enum-declaration.
14800         // Conflicts are diagnosed above. Do nothing.
14801       }
14802       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14803         Diag(Loc, diag::ext_forward_ref_enum_def)
14804           << New;
14805         Diag(Def->getLocation(), diag::note_previous_definition);
14806       } else {
14807         unsigned DiagID = diag::ext_forward_ref_enum;
14808         if (getLangOpts().MSVCCompat)
14809           DiagID = diag::ext_ms_forward_ref_enum;
14810         else if (getLangOpts().CPlusPlus)
14811           DiagID = diag::err_forward_ref_enum;
14812         Diag(Loc, DiagID);
14813       }
14814     }
14815 
14816     if (EnumUnderlying) {
14817       EnumDecl *ED = cast<EnumDecl>(New);
14818       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14819         ED->setIntegerTypeSourceInfo(TI);
14820       else
14821         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14822       ED->setPromotionType(ED->getIntegerType());
14823       assert(ED->isComplete() && "enum with type should be complete");
14824     }
14825   } else {
14826     // struct/union/class
14827 
14828     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14829     // struct X { int A; } D;    D should chain to X.
14830     if (getLangOpts().CPlusPlus) {
14831       // FIXME: Look for a way to use RecordDecl for simple structs.
14832       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14833                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14834 
14835       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14836         StdBadAlloc = cast<CXXRecordDecl>(New);
14837     } else
14838       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14839                                cast_or_null<RecordDecl>(PrevDecl));
14840   }
14841 
14842   // C++11 [dcl.type]p3:
14843   //   A type-specifier-seq shall not define a class or enumeration [...].
14844   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14845       TUK == TUK_Definition) {
14846     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14847       << Context.getTagDeclType(New);
14848     Invalid = true;
14849   }
14850 
14851   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14852       DC->getDeclKind() == Decl::Enum) {
14853     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14854       << Context.getTagDeclType(New);
14855     Invalid = true;
14856   }
14857 
14858   // Maybe add qualifier info.
14859   if (SS.isNotEmpty()) {
14860     if (SS.isSet()) {
14861       // If this is either a declaration or a definition, check the
14862       // nested-name-specifier against the current context.
14863       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14864           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14865                                        isMemberSpecialization))
14866         Invalid = true;
14867 
14868       New->setQualifierInfo(SS.getWithLocInContext(Context));
14869       if (TemplateParameterLists.size() > 0) {
14870         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14871       }
14872     }
14873     else
14874       Invalid = true;
14875   }
14876 
14877   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14878     // Add alignment attributes if necessary; these attributes are checked when
14879     // the ASTContext lays out the structure.
14880     //
14881     // It is important for implementing the correct semantics that this
14882     // happen here (in ActOnTag). The #pragma pack stack is
14883     // maintained as a result of parser callbacks which can occur at
14884     // many points during the parsing of a struct declaration (because
14885     // the #pragma tokens are effectively skipped over during the
14886     // parsing of the struct).
14887     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14888       AddAlignmentAttributesForRecord(RD);
14889       AddMsStructLayoutForRecord(RD);
14890     }
14891   }
14892 
14893   if (ModulePrivateLoc.isValid()) {
14894     if (isMemberSpecialization)
14895       Diag(New->getLocation(), diag::err_module_private_specialization)
14896         << 2
14897         << FixItHint::CreateRemoval(ModulePrivateLoc);
14898     // __module_private__ does not apply to local classes. However, we only
14899     // diagnose this as an error when the declaration specifiers are
14900     // freestanding. Here, we just ignore the __module_private__.
14901     else if (!SearchDC->isFunctionOrMethod())
14902       New->setModulePrivate();
14903   }
14904 
14905   // If this is a specialization of a member class (of a class template),
14906   // check the specialization.
14907   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14908     Invalid = true;
14909 
14910   // If we're declaring or defining a tag in function prototype scope in C,
14911   // note that this type can only be used within the function and add it to
14912   // the list of decls to inject into the function definition scope.
14913   if ((Name || Kind == TTK_Enum) &&
14914       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14915     if (getLangOpts().CPlusPlus) {
14916       // C++ [dcl.fct]p6:
14917       //   Types shall not be defined in return or parameter types.
14918       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14919         Diag(Loc, diag::err_type_defined_in_param_type)
14920             << Name;
14921         Invalid = true;
14922       }
14923     } else if (!PrevDecl) {
14924       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14925     }
14926   }
14927 
14928   if (Invalid)
14929     New->setInvalidDecl();
14930 
14931   // Set the lexical context. If the tag has a C++ scope specifier, the
14932   // lexical context will be different from the semantic context.
14933   New->setLexicalDeclContext(CurContext);
14934 
14935   // Mark this as a friend decl if applicable.
14936   // In Microsoft mode, a friend declaration also acts as a forward
14937   // declaration so we always pass true to setObjectOfFriendDecl to make
14938   // the tag name visible.
14939   if (TUK == TUK_Friend)
14940     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14941 
14942   // Set the access specifier.
14943   if (!Invalid && SearchDC->isRecord())
14944     SetMemberAccessSpecifier(New, PrevDecl, AS);
14945 
14946   if (PrevDecl)
14947     CheckRedeclarationModuleOwnership(New, PrevDecl);
14948 
14949   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14950     New->startDefinition();
14951 
14952   ProcessDeclAttributeList(S, New, Attrs);
14953   AddPragmaAttributes(S, New);
14954 
14955   // If this has an identifier, add it to the scope stack.
14956   if (TUK == TUK_Friend) {
14957     // We might be replacing an existing declaration in the lookup tables;
14958     // if so, borrow its access specifier.
14959     if (PrevDecl)
14960       New->setAccess(PrevDecl->getAccess());
14961 
14962     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14963     DC->makeDeclVisibleInContext(New);
14964     if (Name) // can be null along some error paths
14965       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14966         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14967   } else if (Name) {
14968     S = getNonFieldDeclScope(S);
14969     PushOnScopeChains(New, S, true);
14970   } else {
14971     CurContext->addDecl(New);
14972   }
14973 
14974   // If this is the C FILE type, notify the AST context.
14975   if (IdentifierInfo *II = New->getIdentifier())
14976     if (!New->isInvalidDecl() &&
14977         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14978         II->isStr("FILE"))
14979       Context.setFILEDecl(New);
14980 
14981   if (PrevDecl)
14982     mergeDeclAttributes(New, PrevDecl);
14983 
14984   // If there's a #pragma GCC visibility in scope, set the visibility of this
14985   // record.
14986   AddPushedVisibilityAttribute(New);
14987 
14988   if (isMemberSpecialization && !New->isInvalidDecl())
14989     CompleteMemberSpecialization(New, Previous);
14990 
14991   OwnedDecl = true;
14992   // In C++, don't return an invalid declaration. We can't recover well from
14993   // the cases where we make the type anonymous.
14994   if (Invalid && getLangOpts().CPlusPlus) {
14995     if (New->isBeingDefined())
14996       if (auto RD = dyn_cast<RecordDecl>(New))
14997         RD->completeDefinition();
14998     return nullptr;
14999   } else if (SkipBody && SkipBody->ShouldSkip) {
15000     return SkipBody->Previous;
15001   } else {
15002     return New;
15003   }
15004 }
15005 
15006 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15007   AdjustDeclIfTemplate(TagD);
15008   TagDecl *Tag = cast<TagDecl>(TagD);
15009 
15010   // Enter the tag context.
15011   PushDeclContext(S, Tag);
15012 
15013   ActOnDocumentableDecl(TagD);
15014 
15015   // If there's a #pragma GCC visibility in scope, set the visibility of this
15016   // record.
15017   AddPushedVisibilityAttribute(Tag);
15018 }
15019 
15020 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15021                                     SkipBodyInfo &SkipBody) {
15022   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15023     return false;
15024 
15025   // Make the previous decl visible.
15026   makeMergedDefinitionVisible(SkipBody.Previous);
15027   return true;
15028 }
15029 
15030 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15031   assert(isa<ObjCContainerDecl>(IDecl) &&
15032          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15033   DeclContext *OCD = cast<DeclContext>(IDecl);
15034   assert(getContainingDC(OCD) == CurContext &&
15035       "The next DeclContext should be lexically contained in the current one.");
15036   CurContext = OCD;
15037   return IDecl;
15038 }
15039 
15040 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15041                                            SourceLocation FinalLoc,
15042                                            bool IsFinalSpelledSealed,
15043                                            SourceLocation LBraceLoc) {
15044   AdjustDeclIfTemplate(TagD);
15045   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15046 
15047   FieldCollector->StartClass();
15048 
15049   if (!Record->getIdentifier())
15050     return;
15051 
15052   if (FinalLoc.isValid())
15053     Record->addAttr(new (Context)
15054                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15055 
15056   // C++ [class]p2:
15057   //   [...] The class-name is also inserted into the scope of the
15058   //   class itself; this is known as the injected-class-name. For
15059   //   purposes of access checking, the injected-class-name is treated
15060   //   as if it were a public member name.
15061   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15062       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15063       Record->getLocation(), Record->getIdentifier(),
15064       /*PrevDecl=*/nullptr,
15065       /*DelayTypeCreation=*/true);
15066   Context.getTypeDeclType(InjectedClassName, Record);
15067   InjectedClassName->setImplicit();
15068   InjectedClassName->setAccess(AS_public);
15069   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15070       InjectedClassName->setDescribedClassTemplate(Template);
15071   PushOnScopeChains(InjectedClassName, S);
15072   assert(InjectedClassName->isInjectedClassName() &&
15073          "Broken injected-class-name");
15074 }
15075 
15076 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15077                                     SourceRange BraceRange) {
15078   AdjustDeclIfTemplate(TagD);
15079   TagDecl *Tag = cast<TagDecl>(TagD);
15080   Tag->setBraceRange(BraceRange);
15081 
15082   // Make sure we "complete" the definition even it is invalid.
15083   if (Tag->isBeingDefined()) {
15084     assert(Tag->isInvalidDecl() && "We should already have completed it");
15085     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15086       RD->completeDefinition();
15087   }
15088 
15089   if (isa<CXXRecordDecl>(Tag)) {
15090     FieldCollector->FinishClass();
15091   }
15092 
15093   // Exit this scope of this tag's definition.
15094   PopDeclContext();
15095 
15096   if (getCurLexicalContext()->isObjCContainer() &&
15097       Tag->getDeclContext()->isFileContext())
15098     Tag->setTopLevelDeclInObjCContainer();
15099 
15100   // Notify the consumer that we've defined a tag.
15101   if (!Tag->isInvalidDecl())
15102     Consumer.HandleTagDeclDefinition(Tag);
15103 }
15104 
15105 void Sema::ActOnObjCContainerFinishDefinition() {
15106   // Exit this scope of this interface definition.
15107   PopDeclContext();
15108 }
15109 
15110 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15111   assert(DC == CurContext && "Mismatch of container contexts");
15112   OriginalLexicalContext = DC;
15113   ActOnObjCContainerFinishDefinition();
15114 }
15115 
15116 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15117   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15118   OriginalLexicalContext = nullptr;
15119 }
15120 
15121 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15122   AdjustDeclIfTemplate(TagD);
15123   TagDecl *Tag = cast<TagDecl>(TagD);
15124   Tag->setInvalidDecl();
15125 
15126   // Make sure we "complete" the definition even it is invalid.
15127   if (Tag->isBeingDefined()) {
15128     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15129       RD->completeDefinition();
15130   }
15131 
15132   // We're undoing ActOnTagStartDefinition here, not
15133   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15134   // the FieldCollector.
15135 
15136   PopDeclContext();
15137 }
15138 
15139 // Note that FieldName may be null for anonymous bitfields.
15140 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15141                                 IdentifierInfo *FieldName,
15142                                 QualType FieldTy, bool IsMsStruct,
15143                                 Expr *BitWidth, bool *ZeroWidth) {
15144   // Default to true; that shouldn't confuse checks for emptiness
15145   if (ZeroWidth)
15146     *ZeroWidth = true;
15147 
15148   // C99 6.7.2.1p4 - verify the field type.
15149   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15150   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15151     // Handle incomplete types with specific error.
15152     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15153       return ExprError();
15154     if (FieldName)
15155       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15156         << FieldName << FieldTy << BitWidth->getSourceRange();
15157     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15158       << FieldTy << BitWidth->getSourceRange();
15159   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15160                                              UPPC_BitFieldWidth))
15161     return ExprError();
15162 
15163   // If the bit-width is type- or value-dependent, don't try to check
15164   // it now.
15165   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15166     return BitWidth;
15167 
15168   llvm::APSInt Value;
15169   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15170   if (ICE.isInvalid())
15171     return ICE;
15172   BitWidth = ICE.get();
15173 
15174   if (Value != 0 && ZeroWidth)
15175     *ZeroWidth = false;
15176 
15177   // Zero-width bitfield is ok for anonymous field.
15178   if (Value == 0 && FieldName)
15179     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15180 
15181   if (Value.isSigned() && Value.isNegative()) {
15182     if (FieldName)
15183       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15184                << FieldName << Value.toString(10);
15185     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15186       << Value.toString(10);
15187   }
15188 
15189   if (!FieldTy->isDependentType()) {
15190     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15191     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15192     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15193 
15194     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15195     // ABI.
15196     bool CStdConstraintViolation =
15197         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15198     bool MSBitfieldViolation =
15199         Value.ugt(TypeStorageSize) &&
15200         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15201     if (CStdConstraintViolation || MSBitfieldViolation) {
15202       unsigned DiagWidth =
15203           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15204       if (FieldName)
15205         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15206                << FieldName << (unsigned)Value.getZExtValue()
15207                << !CStdConstraintViolation << DiagWidth;
15208 
15209       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15210              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15211              << DiagWidth;
15212     }
15213 
15214     // Warn on types where the user might conceivably expect to get all
15215     // specified bits as value bits: that's all integral types other than
15216     // 'bool'.
15217     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15218       if (FieldName)
15219         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15220             << FieldName << (unsigned)Value.getZExtValue()
15221             << (unsigned)TypeWidth;
15222       else
15223         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15224             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15225     }
15226   }
15227 
15228   return BitWidth;
15229 }
15230 
15231 /// ActOnField - Each field of a C struct/union is passed into this in order
15232 /// to create a FieldDecl object for it.
15233 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15234                        Declarator &D, Expr *BitfieldWidth) {
15235   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15236                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15237                                /*InitStyle=*/ICIS_NoInit, AS_public);
15238   return Res;
15239 }
15240 
15241 /// HandleField - Analyze a field of a C struct or a C++ data member.
15242 ///
15243 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15244                              SourceLocation DeclStart,
15245                              Declarator &D, Expr *BitWidth,
15246                              InClassInitStyle InitStyle,
15247                              AccessSpecifier AS) {
15248   if (D.isDecompositionDeclarator()) {
15249     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15250     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15251       << Decomp.getSourceRange();
15252     return nullptr;
15253   }
15254 
15255   IdentifierInfo *II = D.getIdentifier();
15256   SourceLocation Loc = DeclStart;
15257   if (II) Loc = D.getIdentifierLoc();
15258 
15259   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15260   QualType T = TInfo->getType();
15261   if (getLangOpts().CPlusPlus) {
15262     CheckExtraCXXDefaultArguments(D);
15263 
15264     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15265                                         UPPC_DataMemberType)) {
15266       D.setInvalidType();
15267       T = Context.IntTy;
15268       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15269     }
15270   }
15271 
15272   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15273 
15274   if (D.getDeclSpec().isInlineSpecified())
15275     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15276         << getLangOpts().CPlusPlus17;
15277   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15278     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15279          diag::err_invalid_thread)
15280       << DeclSpec::getSpecifierName(TSCS);
15281 
15282   // Check to see if this name was declared as a member previously
15283   NamedDecl *PrevDecl = nullptr;
15284   LookupResult Previous(*this, II, Loc, LookupMemberName,
15285                         ForVisibleRedeclaration);
15286   LookupName(Previous, S);
15287   switch (Previous.getResultKind()) {
15288     case LookupResult::Found:
15289     case LookupResult::FoundUnresolvedValue:
15290       PrevDecl = Previous.getAsSingle<NamedDecl>();
15291       break;
15292 
15293     case LookupResult::FoundOverloaded:
15294       PrevDecl = Previous.getRepresentativeDecl();
15295       break;
15296 
15297     case LookupResult::NotFound:
15298     case LookupResult::NotFoundInCurrentInstantiation:
15299     case LookupResult::Ambiguous:
15300       break;
15301   }
15302   Previous.suppressDiagnostics();
15303 
15304   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15305     // Maybe we will complain about the shadowed template parameter.
15306     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15307     // Just pretend that we didn't see the previous declaration.
15308     PrevDecl = nullptr;
15309   }
15310 
15311   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15312     PrevDecl = nullptr;
15313 
15314   bool Mutable
15315     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15316   SourceLocation TSSL = D.getBeginLoc();
15317   FieldDecl *NewFD
15318     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15319                      TSSL, AS, PrevDecl, &D);
15320 
15321   if (NewFD->isInvalidDecl())
15322     Record->setInvalidDecl();
15323 
15324   if (D.getDeclSpec().isModulePrivateSpecified())
15325     NewFD->setModulePrivate();
15326 
15327   if (NewFD->isInvalidDecl() && PrevDecl) {
15328     // Don't introduce NewFD into scope; there's already something
15329     // with the same name in the same scope.
15330   } else if (II) {
15331     PushOnScopeChains(NewFD, S);
15332   } else
15333     Record->addDecl(NewFD);
15334 
15335   return NewFD;
15336 }
15337 
15338 /// Build a new FieldDecl and check its well-formedness.
15339 ///
15340 /// This routine builds a new FieldDecl given the fields name, type,
15341 /// record, etc. \p PrevDecl should refer to any previous declaration
15342 /// with the same name and in the same scope as the field to be
15343 /// created.
15344 ///
15345 /// \returns a new FieldDecl.
15346 ///
15347 /// \todo The Declarator argument is a hack. It will be removed once
15348 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15349                                 TypeSourceInfo *TInfo,
15350                                 RecordDecl *Record, SourceLocation Loc,
15351                                 bool Mutable, Expr *BitWidth,
15352                                 InClassInitStyle InitStyle,
15353                                 SourceLocation TSSL,
15354                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15355                                 Declarator *D) {
15356   IdentifierInfo *II = Name.getAsIdentifierInfo();
15357   bool InvalidDecl = false;
15358   if (D) InvalidDecl = D->isInvalidType();
15359 
15360   // If we receive a broken type, recover by assuming 'int' and
15361   // marking this declaration as invalid.
15362   if (T.isNull()) {
15363     InvalidDecl = true;
15364     T = Context.IntTy;
15365   }
15366 
15367   QualType EltTy = Context.getBaseElementType(T);
15368   if (!EltTy->isDependentType()) {
15369     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15370       // Fields of incomplete type force their record to be invalid.
15371       Record->setInvalidDecl();
15372       InvalidDecl = true;
15373     } else {
15374       NamedDecl *Def;
15375       EltTy->isIncompleteType(&Def);
15376       if (Def && Def->isInvalidDecl()) {
15377         Record->setInvalidDecl();
15378         InvalidDecl = true;
15379       }
15380     }
15381   }
15382 
15383   // TR 18037 does not allow fields to be declared with address space
15384   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15385       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15386     Diag(Loc, diag::err_field_with_address_space);
15387     Record->setInvalidDecl();
15388     InvalidDecl = true;
15389   }
15390 
15391   if (LangOpts.OpenCL) {
15392     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15393     // used as structure or union field: image, sampler, event or block types.
15394     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15395         T->isBlockPointerType()) {
15396       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15397       Record->setInvalidDecl();
15398       InvalidDecl = true;
15399     }
15400     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15401     if (BitWidth) {
15402       Diag(Loc, diag::err_opencl_bitfields);
15403       InvalidDecl = true;
15404     }
15405   }
15406 
15407   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15408   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15409       T.hasQualifiers()) {
15410     InvalidDecl = true;
15411     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15412   }
15413 
15414   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15415   // than a variably modified type.
15416   if (!InvalidDecl && T->isVariablyModifiedType()) {
15417     bool SizeIsNegative;
15418     llvm::APSInt Oversized;
15419 
15420     TypeSourceInfo *FixedTInfo =
15421       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15422                                                     SizeIsNegative,
15423                                                     Oversized);
15424     if (FixedTInfo) {
15425       Diag(Loc, diag::warn_illegal_constant_array_size);
15426       TInfo = FixedTInfo;
15427       T = FixedTInfo->getType();
15428     } else {
15429       if (SizeIsNegative)
15430         Diag(Loc, diag::err_typecheck_negative_array_size);
15431       else if (Oversized.getBoolValue())
15432         Diag(Loc, diag::err_array_too_large)
15433           << Oversized.toString(10);
15434       else
15435         Diag(Loc, diag::err_typecheck_field_variable_size);
15436       InvalidDecl = true;
15437     }
15438   }
15439 
15440   // Fields can not have abstract class types
15441   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15442                                              diag::err_abstract_type_in_decl,
15443                                              AbstractFieldType))
15444     InvalidDecl = true;
15445 
15446   bool ZeroWidth = false;
15447   if (InvalidDecl)
15448     BitWidth = nullptr;
15449   // If this is declared as a bit-field, check the bit-field.
15450   if (BitWidth) {
15451     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15452                               &ZeroWidth).get();
15453     if (!BitWidth) {
15454       InvalidDecl = true;
15455       BitWidth = nullptr;
15456       ZeroWidth = false;
15457     }
15458   }
15459 
15460   // Check that 'mutable' is consistent with the type of the declaration.
15461   if (!InvalidDecl && Mutable) {
15462     unsigned DiagID = 0;
15463     if (T->isReferenceType())
15464       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15465                                         : diag::err_mutable_reference;
15466     else if (T.isConstQualified())
15467       DiagID = diag::err_mutable_const;
15468 
15469     if (DiagID) {
15470       SourceLocation ErrLoc = Loc;
15471       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15472         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15473       Diag(ErrLoc, DiagID);
15474       if (DiagID != diag::ext_mutable_reference) {
15475         Mutable = false;
15476         InvalidDecl = true;
15477       }
15478     }
15479   }
15480 
15481   // C++11 [class.union]p8 (DR1460):
15482   //   At most one variant member of a union may have a
15483   //   brace-or-equal-initializer.
15484   if (InitStyle != ICIS_NoInit)
15485     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15486 
15487   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15488                                        BitWidth, Mutable, InitStyle);
15489   if (InvalidDecl)
15490     NewFD->setInvalidDecl();
15491 
15492   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15493     Diag(Loc, diag::err_duplicate_member) << II;
15494     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15495     NewFD->setInvalidDecl();
15496   }
15497 
15498   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15499     if (Record->isUnion()) {
15500       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15501         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15502         if (RDecl->getDefinition()) {
15503           // C++ [class.union]p1: An object of a class with a non-trivial
15504           // constructor, a non-trivial copy constructor, a non-trivial
15505           // destructor, or a non-trivial copy assignment operator
15506           // cannot be a member of a union, nor can an array of such
15507           // objects.
15508           if (CheckNontrivialField(NewFD))
15509             NewFD->setInvalidDecl();
15510         }
15511       }
15512 
15513       // C++ [class.union]p1: If a union contains a member of reference type,
15514       // the program is ill-formed, except when compiling with MSVC extensions
15515       // enabled.
15516       if (EltTy->isReferenceType()) {
15517         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15518                                     diag::ext_union_member_of_reference_type :
15519                                     diag::err_union_member_of_reference_type)
15520           << NewFD->getDeclName() << EltTy;
15521         if (!getLangOpts().MicrosoftExt)
15522           NewFD->setInvalidDecl();
15523       }
15524     }
15525   }
15526 
15527   // FIXME: We need to pass in the attributes given an AST
15528   // representation, not a parser representation.
15529   if (D) {
15530     // FIXME: The current scope is almost... but not entirely... correct here.
15531     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15532 
15533     if (NewFD->hasAttrs())
15534       CheckAlignasUnderalignment(NewFD);
15535   }
15536 
15537   // In auto-retain/release, infer strong retension for fields of
15538   // retainable type.
15539   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15540     NewFD->setInvalidDecl();
15541 
15542   if (T.isObjCGCWeak())
15543     Diag(Loc, diag::warn_attribute_weak_on_field);
15544 
15545   NewFD->setAccess(AS);
15546   return NewFD;
15547 }
15548 
15549 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15550   assert(FD);
15551   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15552 
15553   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15554     return false;
15555 
15556   QualType EltTy = Context.getBaseElementType(FD->getType());
15557   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15558     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15559     if (RDecl->getDefinition()) {
15560       // We check for copy constructors before constructors
15561       // because otherwise we'll never get complaints about
15562       // copy constructors.
15563 
15564       CXXSpecialMember member = CXXInvalid;
15565       // We're required to check for any non-trivial constructors. Since the
15566       // implicit default constructor is suppressed if there are any
15567       // user-declared constructors, we just need to check that there is a
15568       // trivial default constructor and a trivial copy constructor. (We don't
15569       // worry about move constructors here, since this is a C++98 check.)
15570       if (RDecl->hasNonTrivialCopyConstructor())
15571         member = CXXCopyConstructor;
15572       else if (!RDecl->hasTrivialDefaultConstructor())
15573         member = CXXDefaultConstructor;
15574       else if (RDecl->hasNonTrivialCopyAssignment())
15575         member = CXXCopyAssignment;
15576       else if (RDecl->hasNonTrivialDestructor())
15577         member = CXXDestructor;
15578 
15579       if (member != CXXInvalid) {
15580         if (!getLangOpts().CPlusPlus11 &&
15581             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15582           // Objective-C++ ARC: it is an error to have a non-trivial field of
15583           // a union. However, system headers in Objective-C programs
15584           // occasionally have Objective-C lifetime objects within unions,
15585           // and rather than cause the program to fail, we make those
15586           // members unavailable.
15587           SourceLocation Loc = FD->getLocation();
15588           if (getSourceManager().isInSystemHeader(Loc)) {
15589             if (!FD->hasAttr<UnavailableAttr>())
15590               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15591                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15592             return false;
15593           }
15594         }
15595 
15596         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15597                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15598                diag::err_illegal_union_or_anon_struct_member)
15599           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15600         DiagnoseNontrivial(RDecl, member);
15601         return !getLangOpts().CPlusPlus11;
15602       }
15603     }
15604   }
15605 
15606   return false;
15607 }
15608 
15609 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15610 ///  AST enum value.
15611 static ObjCIvarDecl::AccessControl
15612 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15613   switch (ivarVisibility) {
15614   default: llvm_unreachable("Unknown visitibility kind");
15615   case tok::objc_private: return ObjCIvarDecl::Private;
15616   case tok::objc_public: return ObjCIvarDecl::Public;
15617   case tok::objc_protected: return ObjCIvarDecl::Protected;
15618   case tok::objc_package: return ObjCIvarDecl::Package;
15619   }
15620 }
15621 
15622 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15623 /// in order to create an IvarDecl object for it.
15624 Decl *Sema::ActOnIvar(Scope *S,
15625                                 SourceLocation DeclStart,
15626                                 Declarator &D, Expr *BitfieldWidth,
15627                                 tok::ObjCKeywordKind Visibility) {
15628 
15629   IdentifierInfo *II = D.getIdentifier();
15630   Expr *BitWidth = (Expr*)BitfieldWidth;
15631   SourceLocation Loc = DeclStart;
15632   if (II) Loc = D.getIdentifierLoc();
15633 
15634   // FIXME: Unnamed fields can be handled in various different ways, for
15635   // example, unnamed unions inject all members into the struct namespace!
15636 
15637   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15638   QualType T = TInfo->getType();
15639 
15640   if (BitWidth) {
15641     // 6.7.2.1p3, 6.7.2.1p4
15642     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15643     if (!BitWidth)
15644       D.setInvalidType();
15645   } else {
15646     // Not a bitfield.
15647 
15648     // validate II.
15649 
15650   }
15651   if (T->isReferenceType()) {
15652     Diag(Loc, diag::err_ivar_reference_type);
15653     D.setInvalidType();
15654   }
15655   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15656   // than a variably modified type.
15657   else if (T->isVariablyModifiedType()) {
15658     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15659     D.setInvalidType();
15660   }
15661 
15662   // Get the visibility (access control) for this ivar.
15663   ObjCIvarDecl::AccessControl ac =
15664     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15665                                         : ObjCIvarDecl::None;
15666   // Must set ivar's DeclContext to its enclosing interface.
15667   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15668   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15669     return nullptr;
15670   ObjCContainerDecl *EnclosingContext;
15671   if (ObjCImplementationDecl *IMPDecl =
15672       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15673     if (LangOpts.ObjCRuntime.isFragile()) {
15674     // Case of ivar declared in an implementation. Context is that of its class.
15675       EnclosingContext = IMPDecl->getClassInterface();
15676       assert(EnclosingContext && "Implementation has no class interface!");
15677     }
15678     else
15679       EnclosingContext = EnclosingDecl;
15680   } else {
15681     if (ObjCCategoryDecl *CDecl =
15682         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15683       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15684         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15685         return nullptr;
15686       }
15687     }
15688     EnclosingContext = EnclosingDecl;
15689   }
15690 
15691   // Construct the decl.
15692   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15693                                              DeclStart, Loc, II, T,
15694                                              TInfo, ac, (Expr *)BitfieldWidth);
15695 
15696   if (II) {
15697     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15698                                            ForVisibleRedeclaration);
15699     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15700         && !isa<TagDecl>(PrevDecl)) {
15701       Diag(Loc, diag::err_duplicate_member) << II;
15702       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15703       NewID->setInvalidDecl();
15704     }
15705   }
15706 
15707   // Process attributes attached to the ivar.
15708   ProcessDeclAttributes(S, NewID, D);
15709 
15710   if (D.isInvalidType())
15711     NewID->setInvalidDecl();
15712 
15713   // In ARC, infer 'retaining' for ivars of retainable type.
15714   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15715     NewID->setInvalidDecl();
15716 
15717   if (D.getDeclSpec().isModulePrivateSpecified())
15718     NewID->setModulePrivate();
15719 
15720   if (II) {
15721     // FIXME: When interfaces are DeclContexts, we'll need to add
15722     // these to the interface.
15723     S->AddDecl(NewID);
15724     IdResolver.AddDecl(NewID);
15725   }
15726 
15727   if (LangOpts.ObjCRuntime.isNonFragile() &&
15728       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15729     Diag(Loc, diag::warn_ivars_in_interface);
15730 
15731   return NewID;
15732 }
15733 
15734 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15735 /// class and class extensions. For every class \@interface and class
15736 /// extension \@interface, if the last ivar is a bitfield of any type,
15737 /// then add an implicit `char :0` ivar to the end of that interface.
15738 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15739                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15740   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15741     return;
15742 
15743   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15744   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15745 
15746   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15747     return;
15748   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15749   if (!ID) {
15750     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15751       if (!CD->IsClassExtension())
15752         return;
15753     }
15754     // No need to add this to end of @implementation.
15755     else
15756       return;
15757   }
15758   // All conditions are met. Add a new bitfield to the tail end of ivars.
15759   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15760   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15761 
15762   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15763                               DeclLoc, DeclLoc, nullptr,
15764                               Context.CharTy,
15765                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15766                                                                DeclLoc),
15767                               ObjCIvarDecl::Private, BW,
15768                               true);
15769   AllIvarDecls.push_back(Ivar);
15770 }
15771 
15772 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15773                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15774                        SourceLocation RBrac,
15775                        const ParsedAttributesView &Attrs) {
15776   assert(EnclosingDecl && "missing record or interface decl");
15777 
15778   // If this is an Objective-C @implementation or category and we have
15779   // new fields here we should reset the layout of the interface since
15780   // it will now change.
15781   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15782     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15783     switch (DC->getKind()) {
15784     default: break;
15785     case Decl::ObjCCategory:
15786       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15787       break;
15788     case Decl::ObjCImplementation:
15789       Context.
15790         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15791       break;
15792     }
15793   }
15794 
15795   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15796   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15797 
15798   // Start counting up the number of named members; make sure to include
15799   // members of anonymous structs and unions in the total.
15800   unsigned NumNamedMembers = 0;
15801   if (Record) {
15802     for (const auto *I : Record->decls()) {
15803       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15804         if (IFD->getDeclName())
15805           ++NumNamedMembers;
15806     }
15807   }
15808 
15809   // Verify that all the fields are okay.
15810   SmallVector<FieldDecl*, 32> RecFields;
15811 
15812   bool ObjCFieldLifetimeErrReported = false;
15813   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15814        i != end; ++i) {
15815     FieldDecl *FD = cast<FieldDecl>(*i);
15816 
15817     // Get the type for the field.
15818     const Type *FDTy = FD->getType().getTypePtr();
15819 
15820     if (!FD->isAnonymousStructOrUnion()) {
15821       // Remember all fields written by the user.
15822       RecFields.push_back(FD);
15823     }
15824 
15825     // If the field is already invalid for some reason, don't emit more
15826     // diagnostics about it.
15827     if (FD->isInvalidDecl()) {
15828       EnclosingDecl->setInvalidDecl();
15829       continue;
15830     }
15831 
15832     // C99 6.7.2.1p2:
15833     //   A structure or union shall not contain a member with
15834     //   incomplete or function type (hence, a structure shall not
15835     //   contain an instance of itself, but may contain a pointer to
15836     //   an instance of itself), except that the last member of a
15837     //   structure with more than one named member may have incomplete
15838     //   array type; such a structure (and any union containing,
15839     //   possibly recursively, a member that is such a structure)
15840     //   shall not be a member of a structure or an element of an
15841     //   array.
15842     bool IsLastField = (i + 1 == Fields.end());
15843     if (FDTy->isFunctionType()) {
15844       // Field declared as a function.
15845       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15846         << FD->getDeclName();
15847       FD->setInvalidDecl();
15848       EnclosingDecl->setInvalidDecl();
15849       continue;
15850     } else if (FDTy->isIncompleteArrayType() &&
15851                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15852       if (Record) {
15853         // Flexible array member.
15854         // Microsoft and g++ is more permissive regarding flexible array.
15855         // It will accept flexible array in union and also
15856         // as the sole element of a struct/class.
15857         unsigned DiagID = 0;
15858         if (!Record->isUnion() && !IsLastField) {
15859           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15860             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15861           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15862           FD->setInvalidDecl();
15863           EnclosingDecl->setInvalidDecl();
15864           continue;
15865         } else if (Record->isUnion())
15866           DiagID = getLangOpts().MicrosoftExt
15867                        ? diag::ext_flexible_array_union_ms
15868                        : getLangOpts().CPlusPlus
15869                              ? diag::ext_flexible_array_union_gnu
15870                              : diag::err_flexible_array_union;
15871         else if (NumNamedMembers < 1)
15872           DiagID = getLangOpts().MicrosoftExt
15873                        ? diag::ext_flexible_array_empty_aggregate_ms
15874                        : getLangOpts().CPlusPlus
15875                              ? diag::ext_flexible_array_empty_aggregate_gnu
15876                              : diag::err_flexible_array_empty_aggregate;
15877 
15878         if (DiagID)
15879           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15880                                           << Record->getTagKind();
15881         // While the layout of types that contain virtual bases is not specified
15882         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15883         // virtual bases after the derived members.  This would make a flexible
15884         // array member declared at the end of an object not adjacent to the end
15885         // of the type.
15886         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15887           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15888               << FD->getDeclName() << Record->getTagKind();
15889         if (!getLangOpts().C99)
15890           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15891             << FD->getDeclName() << Record->getTagKind();
15892 
15893         // If the element type has a non-trivial destructor, we would not
15894         // implicitly destroy the elements, so disallow it for now.
15895         //
15896         // FIXME: GCC allows this. We should probably either implicitly delete
15897         // the destructor of the containing class, or just allow this.
15898         QualType BaseElem = Context.getBaseElementType(FD->getType());
15899         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15900           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15901             << FD->getDeclName() << FD->getType();
15902           FD->setInvalidDecl();
15903           EnclosingDecl->setInvalidDecl();
15904           continue;
15905         }
15906         // Okay, we have a legal flexible array member at the end of the struct.
15907         Record->setHasFlexibleArrayMember(true);
15908       } else {
15909         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15910         // unless they are followed by another ivar. That check is done
15911         // elsewhere, after synthesized ivars are known.
15912       }
15913     } else if (!FDTy->isDependentType() &&
15914                RequireCompleteType(FD->getLocation(), FD->getType(),
15915                                    diag::err_field_incomplete)) {
15916       // Incomplete type
15917       FD->setInvalidDecl();
15918       EnclosingDecl->setInvalidDecl();
15919       continue;
15920     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15921       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15922         // A type which contains a flexible array member is considered to be a
15923         // flexible array member.
15924         Record->setHasFlexibleArrayMember(true);
15925         if (!Record->isUnion()) {
15926           // If this is a struct/class and this is not the last element, reject
15927           // it.  Note that GCC supports variable sized arrays in the middle of
15928           // structures.
15929           if (!IsLastField)
15930             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15931               << FD->getDeclName() << FD->getType();
15932           else {
15933             // We support flexible arrays at the end of structs in
15934             // other structs as an extension.
15935             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15936               << FD->getDeclName();
15937           }
15938         }
15939       }
15940       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15941           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15942                                  diag::err_abstract_type_in_decl,
15943                                  AbstractIvarType)) {
15944         // Ivars can not have abstract class types
15945         FD->setInvalidDecl();
15946       }
15947       if (Record && FDTTy->getDecl()->hasObjectMember())
15948         Record->setHasObjectMember(true);
15949       if (Record && FDTTy->getDecl()->hasVolatileMember())
15950         Record->setHasVolatileMember(true);
15951       if (Record && Record->isUnion() &&
15952           FD->getType().isNonTrivialPrimitiveCType(Context))
15953         Diag(FD->getLocation(),
15954              diag::err_nontrivial_primitive_type_in_union);
15955     } else if (FDTy->isObjCObjectType()) {
15956       /// A field cannot be an Objective-c object
15957       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15958         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15959       QualType T = Context.getObjCObjectPointerType(FD->getType());
15960       FD->setType(T);
15961     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15962                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
15963                !getLangOpts().CPlusPlus) {
15964       // It's an error in ARC or Weak if a field has lifetime.
15965       // We don't want to report this in a system header, though,
15966       // so we just make the field unavailable.
15967       // FIXME: that's really not sufficient; we need to make the type
15968       // itself invalid to, say, initialize or copy.
15969       QualType T = FD->getType();
15970       if (T.hasNonTrivialObjCLifetime()) {
15971         SourceLocation loc = FD->getLocation();
15972         if (getSourceManager().isInSystemHeader(loc)) {
15973           if (!FD->hasAttr<UnavailableAttr>()) {
15974             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15975                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15976           }
15977         } else {
15978           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15979             << T->isBlockPointerType() << Record->getTagKind();
15980         }
15981         ObjCFieldLifetimeErrReported = true;
15982       }
15983     } else if (getLangOpts().ObjC &&
15984                getLangOpts().getGC() != LangOptions::NonGC &&
15985                Record && !Record->hasObjectMember()) {
15986       if (FD->getType()->isObjCObjectPointerType() ||
15987           FD->getType().isObjCGCStrong())
15988         Record->setHasObjectMember(true);
15989       else if (Context.getAsArrayType(FD->getType())) {
15990         QualType BaseType = Context.getBaseElementType(FD->getType());
15991         if (BaseType->isRecordType() &&
15992             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15993           Record->setHasObjectMember(true);
15994         else if (BaseType->isObjCObjectPointerType() ||
15995                  BaseType.isObjCGCStrong())
15996                Record->setHasObjectMember(true);
15997       }
15998     }
15999 
16000     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16001       QualType FT = FD->getType();
16002       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16003         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16004       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16005       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16006         Record->setNonTrivialToPrimitiveCopy(true);
16007       if (FT.isDestructedType()) {
16008         Record->setNonTrivialToPrimitiveDestroy(true);
16009         Record->setParamDestroyedInCallee(true);
16010       }
16011 
16012       if (const auto *RT = FT->getAs<RecordType>()) {
16013         if (RT->getDecl()->getArgPassingRestrictions() ==
16014             RecordDecl::APK_CanNeverPassInRegs)
16015           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16016       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16017         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16018     }
16019 
16020     if (Record && FD->getType().isVolatileQualified())
16021       Record->setHasVolatileMember(true);
16022     // Keep track of the number of named members.
16023     if (FD->getIdentifier())
16024       ++NumNamedMembers;
16025   }
16026 
16027   // Okay, we successfully defined 'Record'.
16028   if (Record) {
16029     bool Completed = false;
16030     if (CXXRecord) {
16031       if (!CXXRecord->isInvalidDecl()) {
16032         // Set access bits correctly on the directly-declared conversions.
16033         for (CXXRecordDecl::conversion_iterator
16034                I = CXXRecord->conversion_begin(),
16035                E = CXXRecord->conversion_end(); I != E; ++I)
16036           I.setAccess((*I)->getAccess());
16037       }
16038 
16039       if (!CXXRecord->isDependentType()) {
16040         // Add any implicitly-declared members to this class.
16041         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16042 
16043         if (!CXXRecord->isInvalidDecl()) {
16044           // If we have virtual base classes, we may end up finding multiple
16045           // final overriders for a given virtual function. Check for this
16046           // problem now.
16047           if (CXXRecord->getNumVBases()) {
16048             CXXFinalOverriderMap FinalOverriders;
16049             CXXRecord->getFinalOverriders(FinalOverriders);
16050 
16051             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16052                                              MEnd = FinalOverriders.end();
16053                  M != MEnd; ++M) {
16054               for (OverridingMethods::iterator SO = M->second.begin(),
16055                                             SOEnd = M->second.end();
16056                    SO != SOEnd; ++SO) {
16057                 assert(SO->second.size() > 0 &&
16058                        "Virtual function without overriding functions?");
16059                 if (SO->second.size() == 1)
16060                   continue;
16061 
16062                 // C++ [class.virtual]p2:
16063                 //   In a derived class, if a virtual member function of a base
16064                 //   class subobject has more than one final overrider the
16065                 //   program is ill-formed.
16066                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16067                   << (const NamedDecl *)M->first << Record;
16068                 Diag(M->first->getLocation(),
16069                      diag::note_overridden_virtual_function);
16070                 for (OverridingMethods::overriding_iterator
16071                           OM = SO->second.begin(),
16072                        OMEnd = SO->second.end();
16073                      OM != OMEnd; ++OM)
16074                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16075                     << (const NamedDecl *)M->first << OM->Method->getParent();
16076 
16077                 Record->setInvalidDecl();
16078               }
16079             }
16080             CXXRecord->completeDefinition(&FinalOverriders);
16081             Completed = true;
16082           }
16083         }
16084       }
16085     }
16086 
16087     if (!Completed)
16088       Record->completeDefinition();
16089 
16090     // Handle attributes before checking the layout.
16091     ProcessDeclAttributeList(S, Record, Attrs);
16092 
16093     // We may have deferred checking for a deleted destructor. Check now.
16094     if (CXXRecord) {
16095       auto *Dtor = CXXRecord->getDestructor();
16096       if (Dtor && Dtor->isImplicit() &&
16097           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16098         CXXRecord->setImplicitDestructorIsDeleted();
16099         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16100       }
16101     }
16102 
16103     if (Record->hasAttrs()) {
16104       CheckAlignasUnderalignment(Record);
16105 
16106       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16107         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16108                                            IA->getRange(), IA->getBestCase(),
16109                                            IA->getSemanticSpelling());
16110     }
16111 
16112     // Check if the structure/union declaration is a type that can have zero
16113     // size in C. For C this is a language extension, for C++ it may cause
16114     // compatibility problems.
16115     bool CheckForZeroSize;
16116     if (!getLangOpts().CPlusPlus) {
16117       CheckForZeroSize = true;
16118     } else {
16119       // For C++ filter out types that cannot be referenced in C code.
16120       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16121       CheckForZeroSize =
16122           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16123           !CXXRecord->isDependentType() &&
16124           CXXRecord->isCLike();
16125     }
16126     if (CheckForZeroSize) {
16127       bool ZeroSize = true;
16128       bool IsEmpty = true;
16129       unsigned NonBitFields = 0;
16130       for (RecordDecl::field_iterator I = Record->field_begin(),
16131                                       E = Record->field_end();
16132            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16133         IsEmpty = false;
16134         if (I->isUnnamedBitfield()) {
16135           if (!I->isZeroLengthBitField(Context))
16136             ZeroSize = false;
16137         } else {
16138           ++NonBitFields;
16139           QualType FieldType = I->getType();
16140           if (FieldType->isIncompleteType() ||
16141               !Context.getTypeSizeInChars(FieldType).isZero())
16142             ZeroSize = false;
16143         }
16144       }
16145 
16146       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16147       // allowed in C++, but warn if its declaration is inside
16148       // extern "C" block.
16149       if (ZeroSize) {
16150         Diag(RecLoc, getLangOpts().CPlusPlus ?
16151                          diag::warn_zero_size_struct_union_in_extern_c :
16152                          diag::warn_zero_size_struct_union_compat)
16153           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16154       }
16155 
16156       // Structs without named members are extension in C (C99 6.7.2.1p7),
16157       // but are accepted by GCC.
16158       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16159         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16160                                diag::ext_no_named_members_in_struct_union)
16161           << Record->isUnion();
16162       }
16163     }
16164   } else {
16165     ObjCIvarDecl **ClsFields =
16166       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16167     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16168       ID->setEndOfDefinitionLoc(RBrac);
16169       // Add ivar's to class's DeclContext.
16170       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16171         ClsFields[i]->setLexicalDeclContext(ID);
16172         ID->addDecl(ClsFields[i]);
16173       }
16174       // Must enforce the rule that ivars in the base classes may not be
16175       // duplicates.
16176       if (ID->getSuperClass())
16177         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16178     } else if (ObjCImplementationDecl *IMPDecl =
16179                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16180       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16181       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16182         // Ivar declared in @implementation never belongs to the implementation.
16183         // Only it is in implementation's lexical context.
16184         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16185       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16186       IMPDecl->setIvarLBraceLoc(LBrac);
16187       IMPDecl->setIvarRBraceLoc(RBrac);
16188     } else if (ObjCCategoryDecl *CDecl =
16189                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16190       // case of ivars in class extension; all other cases have been
16191       // reported as errors elsewhere.
16192       // FIXME. Class extension does not have a LocEnd field.
16193       // CDecl->setLocEnd(RBrac);
16194       // Add ivar's to class extension's DeclContext.
16195       // Diagnose redeclaration of private ivars.
16196       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16197       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16198         if (IDecl) {
16199           if (const ObjCIvarDecl *ClsIvar =
16200               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16201             Diag(ClsFields[i]->getLocation(),
16202                  diag::err_duplicate_ivar_declaration);
16203             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16204             continue;
16205           }
16206           for (const auto *Ext : IDecl->known_extensions()) {
16207             if (const ObjCIvarDecl *ClsExtIvar
16208                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16209               Diag(ClsFields[i]->getLocation(),
16210                    diag::err_duplicate_ivar_declaration);
16211               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16212               continue;
16213             }
16214           }
16215         }
16216         ClsFields[i]->setLexicalDeclContext(CDecl);
16217         CDecl->addDecl(ClsFields[i]);
16218       }
16219       CDecl->setIvarLBraceLoc(LBrac);
16220       CDecl->setIvarRBraceLoc(RBrac);
16221     }
16222   }
16223 }
16224 
16225 /// Determine whether the given integral value is representable within
16226 /// the given type T.
16227 static bool isRepresentableIntegerValue(ASTContext &Context,
16228                                         llvm::APSInt &Value,
16229                                         QualType T) {
16230   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16231          "Integral type required!");
16232   unsigned BitWidth = Context.getIntWidth(T);
16233 
16234   if (Value.isUnsigned() || Value.isNonNegative()) {
16235     if (T->isSignedIntegerOrEnumerationType())
16236       --BitWidth;
16237     return Value.getActiveBits() <= BitWidth;
16238   }
16239   return Value.getMinSignedBits() <= BitWidth;
16240 }
16241 
16242 // Given an integral type, return the next larger integral type
16243 // (or a NULL type of no such type exists).
16244 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16245   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16246   // enum checking below.
16247   assert((T->isIntegralType(Context) ||
16248          T->isEnumeralType()) && "Integral type required!");
16249   const unsigned NumTypes = 4;
16250   QualType SignedIntegralTypes[NumTypes] = {
16251     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16252   };
16253   QualType UnsignedIntegralTypes[NumTypes] = {
16254     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16255     Context.UnsignedLongLongTy
16256   };
16257 
16258   unsigned BitWidth = Context.getTypeSize(T);
16259   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16260                                                         : UnsignedIntegralTypes;
16261   for (unsigned I = 0; I != NumTypes; ++I)
16262     if (Context.getTypeSize(Types[I]) > BitWidth)
16263       return Types[I];
16264 
16265   return QualType();
16266 }
16267 
16268 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16269                                           EnumConstantDecl *LastEnumConst,
16270                                           SourceLocation IdLoc,
16271                                           IdentifierInfo *Id,
16272                                           Expr *Val) {
16273   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16274   llvm::APSInt EnumVal(IntWidth);
16275   QualType EltTy;
16276 
16277   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16278     Val = nullptr;
16279 
16280   if (Val)
16281     Val = DefaultLvalueConversion(Val).get();
16282 
16283   if (Val) {
16284     if (Enum->isDependentType() || Val->isTypeDependent())
16285       EltTy = Context.DependentTy;
16286     else {
16287       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16288           !getLangOpts().MSVCCompat) {
16289         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16290         // constant-expression in the enumerator-definition shall be a converted
16291         // constant expression of the underlying type.
16292         EltTy = Enum->getIntegerType();
16293         ExprResult Converted =
16294           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16295                                            CCEK_Enumerator);
16296         if (Converted.isInvalid())
16297           Val = nullptr;
16298         else
16299           Val = Converted.get();
16300       } else if (!Val->isValueDependent() &&
16301                  !(Val = VerifyIntegerConstantExpression(Val,
16302                                                          &EnumVal).get())) {
16303         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16304       } else {
16305         if (Enum->isComplete()) {
16306           EltTy = Enum->getIntegerType();
16307 
16308           // In Obj-C and Microsoft mode, require the enumeration value to be
16309           // representable in the underlying type of the enumeration. In C++11,
16310           // we perform a non-narrowing conversion as part of converted constant
16311           // expression checking.
16312           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16313             if (getLangOpts().MSVCCompat) {
16314               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16315               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16316             } else
16317               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16318           } else
16319             Val = ImpCastExprToType(Val, EltTy,
16320                                     EltTy->isBooleanType() ?
16321                                     CK_IntegralToBoolean : CK_IntegralCast)
16322                     .get();
16323         } else if (getLangOpts().CPlusPlus) {
16324           // C++11 [dcl.enum]p5:
16325           //   If the underlying type is not fixed, the type of each enumerator
16326           //   is the type of its initializing value:
16327           //     - If an initializer is specified for an enumerator, the
16328           //       initializing value has the same type as the expression.
16329           EltTy = Val->getType();
16330         } else {
16331           // C99 6.7.2.2p2:
16332           //   The expression that defines the value of an enumeration constant
16333           //   shall be an integer constant expression that has a value
16334           //   representable as an int.
16335 
16336           // Complain if the value is not representable in an int.
16337           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16338             Diag(IdLoc, diag::ext_enum_value_not_int)
16339               << EnumVal.toString(10) << Val->getSourceRange()
16340               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16341           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16342             // Force the type of the expression to 'int'.
16343             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16344           }
16345           EltTy = Val->getType();
16346         }
16347       }
16348     }
16349   }
16350 
16351   if (!Val) {
16352     if (Enum->isDependentType())
16353       EltTy = Context.DependentTy;
16354     else if (!LastEnumConst) {
16355       // C++0x [dcl.enum]p5:
16356       //   If the underlying type is not fixed, the type of each enumerator
16357       //   is the type of its initializing value:
16358       //     - If no initializer is specified for the first enumerator, the
16359       //       initializing value has an unspecified integral type.
16360       //
16361       // GCC uses 'int' for its unspecified integral type, as does
16362       // C99 6.7.2.2p3.
16363       if (Enum->isFixed()) {
16364         EltTy = Enum->getIntegerType();
16365       }
16366       else {
16367         EltTy = Context.IntTy;
16368       }
16369     } else {
16370       // Assign the last value + 1.
16371       EnumVal = LastEnumConst->getInitVal();
16372       ++EnumVal;
16373       EltTy = LastEnumConst->getType();
16374 
16375       // Check for overflow on increment.
16376       if (EnumVal < LastEnumConst->getInitVal()) {
16377         // C++0x [dcl.enum]p5:
16378         //   If the underlying type is not fixed, the type of each enumerator
16379         //   is the type of its initializing value:
16380         //
16381         //     - Otherwise the type of the initializing value is the same as
16382         //       the type of the initializing value of the preceding enumerator
16383         //       unless the incremented value is not representable in that type,
16384         //       in which case the type is an unspecified integral type
16385         //       sufficient to contain the incremented value. If no such type
16386         //       exists, the program is ill-formed.
16387         QualType T = getNextLargerIntegralType(Context, EltTy);
16388         if (T.isNull() || Enum->isFixed()) {
16389           // There is no integral type larger enough to represent this
16390           // value. Complain, then allow the value to wrap around.
16391           EnumVal = LastEnumConst->getInitVal();
16392           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16393           ++EnumVal;
16394           if (Enum->isFixed())
16395             // When the underlying type is fixed, this is ill-formed.
16396             Diag(IdLoc, diag::err_enumerator_wrapped)
16397               << EnumVal.toString(10)
16398               << EltTy;
16399           else
16400             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16401               << EnumVal.toString(10);
16402         } else {
16403           EltTy = T;
16404         }
16405 
16406         // Retrieve the last enumerator's value, extent that type to the
16407         // type that is supposed to be large enough to represent the incremented
16408         // value, then increment.
16409         EnumVal = LastEnumConst->getInitVal();
16410         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16411         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16412         ++EnumVal;
16413 
16414         // If we're not in C++, diagnose the overflow of enumerator values,
16415         // which in C99 means that the enumerator value is not representable in
16416         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16417         // permits enumerator values that are representable in some larger
16418         // integral type.
16419         if (!getLangOpts().CPlusPlus && !T.isNull())
16420           Diag(IdLoc, diag::warn_enum_value_overflow);
16421       } else if (!getLangOpts().CPlusPlus &&
16422                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16423         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16424         Diag(IdLoc, diag::ext_enum_value_not_int)
16425           << EnumVal.toString(10) << 1;
16426       }
16427     }
16428   }
16429 
16430   if (!EltTy->isDependentType()) {
16431     // Make the enumerator value match the signedness and size of the
16432     // enumerator's type.
16433     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16434     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16435   }
16436 
16437   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16438                                   Val, EnumVal);
16439 }
16440 
16441 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16442                                                 SourceLocation IILoc) {
16443   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16444       !getLangOpts().CPlusPlus)
16445     return SkipBodyInfo();
16446 
16447   // We have an anonymous enum definition. Look up the first enumerator to
16448   // determine if we should merge the definition with an existing one and
16449   // skip the body.
16450   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16451                                          forRedeclarationInCurContext());
16452   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16453   if (!PrevECD)
16454     return SkipBodyInfo();
16455 
16456   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16457   NamedDecl *Hidden;
16458   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16459     SkipBodyInfo Skip;
16460     Skip.Previous = Hidden;
16461     return Skip;
16462   }
16463 
16464   return SkipBodyInfo();
16465 }
16466 
16467 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16468                               SourceLocation IdLoc, IdentifierInfo *Id,
16469                               const ParsedAttributesView &Attrs,
16470                               SourceLocation EqualLoc, Expr *Val) {
16471   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16472   EnumConstantDecl *LastEnumConst =
16473     cast_or_null<EnumConstantDecl>(lastEnumConst);
16474 
16475   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16476   // we find one that is.
16477   S = getNonFieldDeclScope(S);
16478 
16479   // Verify that there isn't already something declared with this name in this
16480   // scope.
16481   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16482   LookupName(R, S);
16483   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16484 
16485   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16486     // Maybe we will complain about the shadowed template parameter.
16487     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16488     // Just pretend that we didn't see the previous declaration.
16489     PrevDecl = nullptr;
16490   }
16491 
16492   // C++ [class.mem]p15:
16493   // If T is the name of a class, then each of the following shall have a name
16494   // different from T:
16495   // - every enumerator of every member of class T that is an unscoped
16496   // enumerated type
16497   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16498     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16499                             DeclarationNameInfo(Id, IdLoc));
16500 
16501   EnumConstantDecl *New =
16502     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16503   if (!New)
16504     return nullptr;
16505 
16506   if (PrevDecl) {
16507     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16508       // Check for other kinds of shadowing not already handled.
16509       CheckShadow(New, PrevDecl, R);
16510     }
16511 
16512     // When in C++, we may get a TagDecl with the same name; in this case the
16513     // enum constant will 'hide' the tag.
16514     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16515            "Received TagDecl when not in C++!");
16516     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16517       if (isa<EnumConstantDecl>(PrevDecl))
16518         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16519       else
16520         Diag(IdLoc, diag::err_redefinition) << Id;
16521       notePreviousDefinition(PrevDecl, IdLoc);
16522       return nullptr;
16523     }
16524   }
16525 
16526   // Process attributes.
16527   ProcessDeclAttributeList(S, New, Attrs);
16528   AddPragmaAttributes(S, New);
16529 
16530   // Register this decl in the current scope stack.
16531   New->setAccess(TheEnumDecl->getAccess());
16532   PushOnScopeChains(New, S);
16533 
16534   ActOnDocumentableDecl(New);
16535 
16536   return New;
16537 }
16538 
16539 // Returns true when the enum initial expression does not trigger the
16540 // duplicate enum warning.  A few common cases are exempted as follows:
16541 // Element2 = Element1
16542 // Element2 = Element1 + 1
16543 // Element2 = Element1 - 1
16544 // Where Element2 and Element1 are from the same enum.
16545 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16546   Expr *InitExpr = ECD->getInitExpr();
16547   if (!InitExpr)
16548     return true;
16549   InitExpr = InitExpr->IgnoreImpCasts();
16550 
16551   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16552     if (!BO->isAdditiveOp())
16553       return true;
16554     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16555     if (!IL)
16556       return true;
16557     if (IL->getValue() != 1)
16558       return true;
16559 
16560     InitExpr = BO->getLHS();
16561   }
16562 
16563   // This checks if the elements are from the same enum.
16564   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16565   if (!DRE)
16566     return true;
16567 
16568   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16569   if (!EnumConstant)
16570     return true;
16571 
16572   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16573       Enum)
16574     return true;
16575 
16576   return false;
16577 }
16578 
16579 // Emits a warning when an element is implicitly set a value that
16580 // a previous element has already been set to.
16581 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16582                                         EnumDecl *Enum, QualType EnumType) {
16583   // Avoid anonymous enums
16584   if (!Enum->getIdentifier())
16585     return;
16586 
16587   // Only check for small enums.
16588   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16589     return;
16590 
16591   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16592     return;
16593 
16594   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16595   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16596 
16597   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16598   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16599 
16600   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16601   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16602     llvm::APSInt Val = D->getInitVal();
16603     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16604   };
16605 
16606   DuplicatesVector DupVector;
16607   ValueToVectorMap EnumMap;
16608 
16609   // Populate the EnumMap with all values represented by enum constants without
16610   // an initializer.
16611   for (auto *Element : Elements) {
16612     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16613 
16614     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16615     // this constant.  Skip this enum since it may be ill-formed.
16616     if (!ECD) {
16617       return;
16618     }
16619 
16620     // Constants with initalizers are handled in the next loop.
16621     if (ECD->getInitExpr())
16622       continue;
16623 
16624     // Duplicate values are handled in the next loop.
16625     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16626   }
16627 
16628   if (EnumMap.size() == 0)
16629     return;
16630 
16631   // Create vectors for any values that has duplicates.
16632   for (auto *Element : Elements) {
16633     // The last loop returned if any constant was null.
16634     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16635     if (!ValidDuplicateEnum(ECD, Enum))
16636       continue;
16637 
16638     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16639     if (Iter == EnumMap.end())
16640       continue;
16641 
16642     DeclOrVector& Entry = Iter->second;
16643     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16644       // Ensure constants are different.
16645       if (D == ECD)
16646         continue;
16647 
16648       // Create new vector and push values onto it.
16649       auto Vec = llvm::make_unique<ECDVector>();
16650       Vec->push_back(D);
16651       Vec->push_back(ECD);
16652 
16653       // Update entry to point to the duplicates vector.
16654       Entry = Vec.get();
16655 
16656       // Store the vector somewhere we can consult later for quick emission of
16657       // diagnostics.
16658       DupVector.emplace_back(std::move(Vec));
16659       continue;
16660     }
16661 
16662     ECDVector *Vec = Entry.get<ECDVector*>();
16663     // Make sure constants are not added more than once.
16664     if (*Vec->begin() == ECD)
16665       continue;
16666 
16667     Vec->push_back(ECD);
16668   }
16669 
16670   // Emit diagnostics.
16671   for (const auto &Vec : DupVector) {
16672     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16673 
16674     // Emit warning for one enum constant.
16675     auto *FirstECD = Vec->front();
16676     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16677       << FirstECD << FirstECD->getInitVal().toString(10)
16678       << FirstECD->getSourceRange();
16679 
16680     // Emit one note for each of the remaining enum constants with
16681     // the same value.
16682     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16683       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16684         << ECD << ECD->getInitVal().toString(10)
16685         << ECD->getSourceRange();
16686   }
16687 }
16688 
16689 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16690                              bool AllowMask) const {
16691   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16692   assert(ED->isCompleteDefinition() && "expected enum definition");
16693 
16694   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16695   llvm::APInt &FlagBits = R.first->second;
16696 
16697   if (R.second) {
16698     for (auto *E : ED->enumerators()) {
16699       const auto &EVal = E->getInitVal();
16700       // Only single-bit enumerators introduce new flag values.
16701       if (EVal.isPowerOf2())
16702         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16703     }
16704   }
16705 
16706   // A value is in a flag enum if either its bits are a subset of the enum's
16707   // flag bits (the first condition) or we are allowing masks and the same is
16708   // true of its complement (the second condition). When masks are allowed, we
16709   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16710   //
16711   // While it's true that any value could be used as a mask, the assumption is
16712   // that a mask will have all of the insignificant bits set. Anything else is
16713   // likely a logic error.
16714   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16715   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16716 }
16717 
16718 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16719                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16720                          const ParsedAttributesView &Attrs) {
16721   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16722   QualType EnumType = Context.getTypeDeclType(Enum);
16723 
16724   ProcessDeclAttributeList(S, Enum, Attrs);
16725 
16726   if (Enum->isDependentType()) {
16727     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16728       EnumConstantDecl *ECD =
16729         cast_or_null<EnumConstantDecl>(Elements[i]);
16730       if (!ECD) continue;
16731 
16732       ECD->setType(EnumType);
16733     }
16734 
16735     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16736     return;
16737   }
16738 
16739   // TODO: If the result value doesn't fit in an int, it must be a long or long
16740   // long value.  ISO C does not support this, but GCC does as an extension,
16741   // emit a warning.
16742   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16743   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16744   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16745 
16746   // Verify that all the values are okay, compute the size of the values, and
16747   // reverse the list.
16748   unsigned NumNegativeBits = 0;
16749   unsigned NumPositiveBits = 0;
16750 
16751   // Keep track of whether all elements have type int.
16752   bool AllElementsInt = true;
16753 
16754   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16755     EnumConstantDecl *ECD =
16756       cast_or_null<EnumConstantDecl>(Elements[i]);
16757     if (!ECD) continue;  // Already issued a diagnostic.
16758 
16759     const llvm::APSInt &InitVal = ECD->getInitVal();
16760 
16761     // Keep track of the size of positive and negative values.
16762     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16763       NumPositiveBits = std::max(NumPositiveBits,
16764                                  (unsigned)InitVal.getActiveBits());
16765     else
16766       NumNegativeBits = std::max(NumNegativeBits,
16767                                  (unsigned)InitVal.getMinSignedBits());
16768 
16769     // Keep track of whether every enum element has type int (very common).
16770     if (AllElementsInt)
16771       AllElementsInt = ECD->getType() == Context.IntTy;
16772   }
16773 
16774   // Figure out the type that should be used for this enum.
16775   QualType BestType;
16776   unsigned BestWidth;
16777 
16778   // C++0x N3000 [conv.prom]p3:
16779   //   An rvalue of an unscoped enumeration type whose underlying
16780   //   type is not fixed can be converted to an rvalue of the first
16781   //   of the following types that can represent all the values of
16782   //   the enumeration: int, unsigned int, long int, unsigned long
16783   //   int, long long int, or unsigned long long int.
16784   // C99 6.4.4.3p2:
16785   //   An identifier declared as an enumeration constant has type int.
16786   // The C99 rule is modified by a gcc extension
16787   QualType BestPromotionType;
16788 
16789   bool Packed = Enum->hasAttr<PackedAttr>();
16790   // -fshort-enums is the equivalent to specifying the packed attribute on all
16791   // enum definitions.
16792   if (LangOpts.ShortEnums)
16793     Packed = true;
16794 
16795   // If the enum already has a type because it is fixed or dictated by the
16796   // target, promote that type instead of analyzing the enumerators.
16797   if (Enum->isComplete()) {
16798     BestType = Enum->getIntegerType();
16799     if (BestType->isPromotableIntegerType())
16800       BestPromotionType = Context.getPromotedIntegerType(BestType);
16801     else
16802       BestPromotionType = BestType;
16803 
16804     BestWidth = Context.getIntWidth(BestType);
16805   }
16806   else if (NumNegativeBits) {
16807     // If there is a negative value, figure out the smallest integer type (of
16808     // int/long/longlong) that fits.
16809     // If it's packed, check also if it fits a char or a short.
16810     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16811       BestType = Context.SignedCharTy;
16812       BestWidth = CharWidth;
16813     } else if (Packed && NumNegativeBits <= ShortWidth &&
16814                NumPositiveBits < ShortWidth) {
16815       BestType = Context.ShortTy;
16816       BestWidth = ShortWidth;
16817     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16818       BestType = Context.IntTy;
16819       BestWidth = IntWidth;
16820     } else {
16821       BestWidth = Context.getTargetInfo().getLongWidth();
16822 
16823       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16824         BestType = Context.LongTy;
16825       } else {
16826         BestWidth = Context.getTargetInfo().getLongLongWidth();
16827 
16828         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16829           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16830         BestType = Context.LongLongTy;
16831       }
16832     }
16833     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16834   } else {
16835     // If there is no negative value, figure out the smallest type that fits
16836     // all of the enumerator values.
16837     // If it's packed, check also if it fits a char or a short.
16838     if (Packed && NumPositiveBits <= CharWidth) {
16839       BestType = Context.UnsignedCharTy;
16840       BestPromotionType = Context.IntTy;
16841       BestWidth = CharWidth;
16842     } else if (Packed && NumPositiveBits <= ShortWidth) {
16843       BestType = Context.UnsignedShortTy;
16844       BestPromotionType = Context.IntTy;
16845       BestWidth = ShortWidth;
16846     } else if (NumPositiveBits <= IntWidth) {
16847       BestType = Context.UnsignedIntTy;
16848       BestWidth = IntWidth;
16849       BestPromotionType
16850         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16851                            ? Context.UnsignedIntTy : Context.IntTy;
16852     } else if (NumPositiveBits <=
16853                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16854       BestType = Context.UnsignedLongTy;
16855       BestPromotionType
16856         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16857                            ? Context.UnsignedLongTy : Context.LongTy;
16858     } else {
16859       BestWidth = Context.getTargetInfo().getLongLongWidth();
16860       assert(NumPositiveBits <= BestWidth &&
16861              "How could an initializer get larger than ULL?");
16862       BestType = Context.UnsignedLongLongTy;
16863       BestPromotionType
16864         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16865                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16866     }
16867   }
16868 
16869   // Loop over all of the enumerator constants, changing their types to match
16870   // the type of the enum if needed.
16871   for (auto *D : Elements) {
16872     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16873     if (!ECD) continue;  // Already issued a diagnostic.
16874 
16875     // Standard C says the enumerators have int type, but we allow, as an
16876     // extension, the enumerators to be larger than int size.  If each
16877     // enumerator value fits in an int, type it as an int, otherwise type it the
16878     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16879     // that X has type 'int', not 'unsigned'.
16880 
16881     // Determine whether the value fits into an int.
16882     llvm::APSInt InitVal = ECD->getInitVal();
16883 
16884     // If it fits into an integer type, force it.  Otherwise force it to match
16885     // the enum decl type.
16886     QualType NewTy;
16887     unsigned NewWidth;
16888     bool NewSign;
16889     if (!getLangOpts().CPlusPlus &&
16890         !Enum->isFixed() &&
16891         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16892       NewTy = Context.IntTy;
16893       NewWidth = IntWidth;
16894       NewSign = true;
16895     } else if (ECD->getType() == BestType) {
16896       // Already the right type!
16897       if (getLangOpts().CPlusPlus)
16898         // C++ [dcl.enum]p4: Following the closing brace of an
16899         // enum-specifier, each enumerator has the type of its
16900         // enumeration.
16901         ECD->setType(EnumType);
16902       continue;
16903     } else {
16904       NewTy = BestType;
16905       NewWidth = BestWidth;
16906       NewSign = BestType->isSignedIntegerOrEnumerationType();
16907     }
16908 
16909     // Adjust the APSInt value.
16910     InitVal = InitVal.extOrTrunc(NewWidth);
16911     InitVal.setIsSigned(NewSign);
16912     ECD->setInitVal(InitVal);
16913 
16914     // Adjust the Expr initializer and type.
16915     if (ECD->getInitExpr() &&
16916         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16917       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16918                                                 CK_IntegralCast,
16919                                                 ECD->getInitExpr(),
16920                                                 /*base paths*/ nullptr,
16921                                                 VK_RValue));
16922     if (getLangOpts().CPlusPlus)
16923       // C++ [dcl.enum]p4: Following the closing brace of an
16924       // enum-specifier, each enumerator has the type of its
16925       // enumeration.
16926       ECD->setType(EnumType);
16927     else
16928       ECD->setType(NewTy);
16929   }
16930 
16931   Enum->completeDefinition(BestType, BestPromotionType,
16932                            NumPositiveBits, NumNegativeBits);
16933 
16934   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16935 
16936   if (Enum->isClosedFlag()) {
16937     for (Decl *D : Elements) {
16938       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16939       if (!ECD) continue;  // Already issued a diagnostic.
16940 
16941       llvm::APSInt InitVal = ECD->getInitVal();
16942       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16943           !IsValueInFlagEnum(Enum, InitVal, true))
16944         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16945           << ECD << Enum;
16946     }
16947   }
16948 
16949   // Now that the enum type is defined, ensure it's not been underaligned.
16950   if (Enum->hasAttrs())
16951     CheckAlignasUnderalignment(Enum);
16952 }
16953 
16954 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16955                                   SourceLocation StartLoc,
16956                                   SourceLocation EndLoc) {
16957   StringLiteral *AsmString = cast<StringLiteral>(expr);
16958 
16959   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16960                                                    AsmString, StartLoc,
16961                                                    EndLoc);
16962   CurContext->addDecl(New);
16963   return New;
16964 }
16965 
16966 static void checkModuleImportContext(Sema &S, Module *M,
16967                                      SourceLocation ImportLoc, DeclContext *DC,
16968                                      bool FromInclude = false) {
16969   SourceLocation ExternCLoc;
16970 
16971   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16972     switch (LSD->getLanguage()) {
16973     case LinkageSpecDecl::lang_c:
16974       if (ExternCLoc.isInvalid())
16975         ExternCLoc = LSD->getBeginLoc();
16976       break;
16977     case LinkageSpecDecl::lang_cxx:
16978       break;
16979     }
16980     DC = LSD->getParent();
16981   }
16982 
16983   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16984     DC = DC->getParent();
16985 
16986   if (!isa<TranslationUnitDecl>(DC)) {
16987     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16988                           ? diag::ext_module_import_not_at_top_level_noop
16989                           : diag::err_module_import_not_at_top_level_fatal)
16990         << M->getFullModuleName() << DC;
16991     S.Diag(cast<Decl>(DC)->getBeginLoc(),
16992            diag::note_module_import_not_at_top_level)
16993         << DC;
16994   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16995     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16996       << M->getFullModuleName();
16997     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16998   }
16999 }
17000 
17001 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
17002                                            SourceLocation ModuleLoc,
17003                                            ModuleDeclKind MDK,
17004                                            ModuleIdPath Path) {
17005   assert(getLangOpts().ModulesTS &&
17006          "should only have module decl in modules TS");
17007 
17008   // A module implementation unit requires that we are not compiling a module
17009   // of any kind. A module interface unit requires that we are not compiling a
17010   // module map.
17011   switch (getLangOpts().getCompilingModule()) {
17012   case LangOptions::CMK_None:
17013     // It's OK to compile a module interface as a normal translation unit.
17014     break;
17015 
17016   case LangOptions::CMK_ModuleInterface:
17017     if (MDK != ModuleDeclKind::Implementation)
17018       break;
17019 
17020     // We were asked to compile a module interface unit but this is a module
17021     // implementation unit. That indicates the 'export' is missing.
17022     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
17023       << FixItHint::CreateInsertion(ModuleLoc, "export ");
17024     MDK = ModuleDeclKind::Interface;
17025     break;
17026 
17027   case LangOptions::CMK_ModuleMap:
17028     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
17029     return nullptr;
17030 
17031   case LangOptions::CMK_HeaderModule:
17032     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
17033     return nullptr;
17034   }
17035 
17036   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
17037 
17038   // FIXME: Most of this work should be done by the preprocessor rather than
17039   // here, in order to support macro import.
17040 
17041   // Only one module-declaration is permitted per source file.
17042   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
17043     Diag(ModuleLoc, diag::err_module_redeclaration);
17044     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
17045          diag::note_prev_module_declaration);
17046     return nullptr;
17047   }
17048 
17049   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
17050   // modules, the dots here are just another character that can appear in a
17051   // module name.
17052   std::string ModuleName;
17053   for (auto &Piece : Path) {
17054     if (!ModuleName.empty())
17055       ModuleName += ".";
17056     ModuleName += Piece.first->getName();
17057   }
17058 
17059   // If a module name was explicitly specified on the command line, it must be
17060   // correct.
17061   if (!getLangOpts().CurrentModule.empty() &&
17062       getLangOpts().CurrentModule != ModuleName) {
17063     Diag(Path.front().second, diag::err_current_module_name_mismatch)
17064         << SourceRange(Path.front().second, Path.back().second)
17065         << getLangOpts().CurrentModule;
17066     return nullptr;
17067   }
17068   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
17069 
17070   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
17071   Module *Mod;
17072 
17073   switch (MDK) {
17074   case ModuleDeclKind::Interface: {
17075     // We can't have parsed or imported a definition of this module or parsed a
17076     // module map defining it already.
17077     if (auto *M = Map.findModule(ModuleName)) {
17078       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
17079       if (M->DefinitionLoc.isValid())
17080         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
17081       else if (const auto *FE = M->getASTFile())
17082         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
17083             << FE->getName();
17084       Mod = M;
17085       break;
17086     }
17087 
17088     // Create a Module for the module that we're defining.
17089     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17090                                            ModuleScopes.front().Module);
17091     assert(Mod && "module creation should not fail");
17092     break;
17093   }
17094 
17095   case ModuleDeclKind::Partition:
17096     // FIXME: Check we are in a submodule of the named module.
17097     return nullptr;
17098 
17099   case ModuleDeclKind::Implementation:
17100     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
17101         PP.getIdentifierInfo(ModuleName), Path[0].second);
17102     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
17103                                        Module::AllVisible,
17104                                        /*IsIncludeDirective=*/false);
17105     if (!Mod) {
17106       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
17107       // Create an empty module interface unit for error recovery.
17108       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17109                                              ModuleScopes.front().Module);
17110     }
17111     break;
17112   }
17113 
17114   // Switch from the global module to the named module.
17115   ModuleScopes.back().Module = Mod;
17116   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
17117   VisibleModules.setVisible(Mod, ModuleLoc);
17118 
17119   // From now on, we have an owning module for all declarations we see.
17120   // However, those declarations are module-private unless explicitly
17121   // exported.
17122   auto *TU = Context.getTranslationUnitDecl();
17123   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
17124   TU->setLocalOwningModule(Mod);
17125 
17126   // FIXME: Create a ModuleDecl.
17127   return nullptr;
17128 }
17129 
17130 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
17131                                    SourceLocation ImportLoc,
17132                                    ModuleIdPath Path) {
17133   // Flatten the module path for a Modules TS module name.
17134   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
17135   if (getLangOpts().ModulesTS) {
17136     std::string ModuleName;
17137     for (auto &Piece : Path) {
17138       if (!ModuleName.empty())
17139         ModuleName += ".";
17140       ModuleName += Piece.first->getName();
17141     }
17142     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
17143     Path = ModuleIdPath(ModuleNameLoc);
17144   }
17145 
17146   Module *Mod =
17147       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
17148                                    /*IsIncludeDirective=*/false);
17149   if (!Mod)
17150     return true;
17151 
17152   VisibleModules.setVisible(Mod, ImportLoc);
17153 
17154   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
17155 
17156   // FIXME: we should support importing a submodule within a different submodule
17157   // of the same top-level module. Until we do, make it an error rather than
17158   // silently ignoring the import.
17159   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
17160   // warn on a redundant import of the current module?
17161   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
17162       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17163     Diag(ImportLoc, getLangOpts().isCompilingModule()
17164                         ? diag::err_module_self_import
17165                         : diag::err_module_import_in_implementation)
17166         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17167 
17168   SmallVector<SourceLocation, 2> IdentifierLocs;
17169   Module *ModCheck = Mod;
17170   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
17171     // If we've run out of module parents, just drop the remaining identifiers.
17172     // We need the length to be consistent.
17173     if (!ModCheck)
17174       break;
17175     ModCheck = ModCheck->Parent;
17176 
17177     IdentifierLocs.push_back(Path[I].second);
17178   }
17179 
17180   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17181                                           Mod, IdentifierLocs);
17182   if (!ModuleScopes.empty())
17183     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17184   CurContext->addDecl(Import);
17185 
17186   // Re-export the module if needed.
17187   if (Import->isExported() &&
17188       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17189     getCurrentModule()->Exports.emplace_back(Mod, false);
17190 
17191   return Import;
17192 }
17193 
17194 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17195   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17196   BuildModuleInclude(DirectiveLoc, Mod);
17197 }
17198 
17199 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17200   // Determine whether we're in the #include buffer for a module. The #includes
17201   // in that buffer do not qualify as module imports; they're just an
17202   // implementation detail of us building the module.
17203   //
17204   // FIXME: Should we even get ActOnModuleInclude calls for those?
17205   bool IsInModuleIncludes =
17206       TUKind == TU_Module &&
17207       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17208 
17209   bool ShouldAddImport = !IsInModuleIncludes;
17210 
17211   // If this module import was due to an inclusion directive, create an
17212   // implicit import declaration to capture it in the AST.
17213   if (ShouldAddImport) {
17214     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17215     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17216                                                      DirectiveLoc, Mod,
17217                                                      DirectiveLoc);
17218     if (!ModuleScopes.empty())
17219       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17220     TU->addDecl(ImportD);
17221     Consumer.HandleImplicitImportDecl(ImportD);
17222   }
17223 
17224   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17225   VisibleModules.setVisible(Mod, DirectiveLoc);
17226 }
17227 
17228 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17229   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17230 
17231   ModuleScopes.push_back({});
17232   ModuleScopes.back().Module = Mod;
17233   if (getLangOpts().ModulesLocalVisibility)
17234     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17235 
17236   VisibleModules.setVisible(Mod, DirectiveLoc);
17237 
17238   // The enclosing context is now part of this module.
17239   // FIXME: Consider creating a child DeclContext to hold the entities
17240   // lexically within the module.
17241   if (getLangOpts().trackLocalOwningModule()) {
17242     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17243       cast<Decl>(DC)->setModuleOwnershipKind(
17244           getLangOpts().ModulesLocalVisibility
17245               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17246               : Decl::ModuleOwnershipKind::Visible);
17247       cast<Decl>(DC)->setLocalOwningModule(Mod);
17248     }
17249   }
17250 }
17251 
17252 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17253   if (getLangOpts().ModulesLocalVisibility) {
17254     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17255     // Leaving a module hides namespace names, so our visible namespace cache
17256     // is now out of date.
17257     VisibleNamespaceCache.clear();
17258   }
17259 
17260   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17261          "left the wrong module scope");
17262   ModuleScopes.pop_back();
17263 
17264   // We got to the end of processing a local module. Create an
17265   // ImportDecl as we would for an imported module.
17266   FileID File = getSourceManager().getFileID(EomLoc);
17267   SourceLocation DirectiveLoc;
17268   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17269     // We reached the end of a #included module header. Use the #include loc.
17270     assert(File != getSourceManager().getMainFileID() &&
17271            "end of submodule in main source file");
17272     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17273   } else {
17274     // We reached an EOM pragma. Use the pragma location.
17275     DirectiveLoc = EomLoc;
17276   }
17277   BuildModuleInclude(DirectiveLoc, Mod);
17278 
17279   // Any further declarations are in whatever module we returned to.
17280   if (getLangOpts().trackLocalOwningModule()) {
17281     // The parser guarantees that this is the same context that we entered
17282     // the module within.
17283     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17284       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17285       if (!getCurrentModule())
17286         cast<Decl>(DC)->setModuleOwnershipKind(
17287             Decl::ModuleOwnershipKind::Unowned);
17288     }
17289   }
17290 }
17291 
17292 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17293                                                       Module *Mod) {
17294   // Bail if we're not allowed to implicitly import a module here.
17295   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17296       VisibleModules.isVisible(Mod))
17297     return;
17298 
17299   // Create the implicit import declaration.
17300   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17301   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17302                                                    Loc, Mod, Loc);
17303   TU->addDecl(ImportD);
17304   Consumer.HandleImplicitImportDecl(ImportD);
17305 
17306   // Make the module visible.
17307   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17308   VisibleModules.setVisible(Mod, Loc);
17309 }
17310 
17311 /// We have parsed the start of an export declaration, including the '{'
17312 /// (if present).
17313 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17314                                  SourceLocation LBraceLoc) {
17315   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17316 
17317   // C++ Modules TS draft:
17318   //   An export-declaration shall appear in the purview of a module other than
17319   //   the global module.
17320   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17321     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17322 
17323   //   An export-declaration [...] shall not contain more than one
17324   //   export keyword.
17325   //
17326   // The intent here is that an export-declaration cannot appear within another
17327   // export-declaration.
17328   if (D->isExported())
17329     Diag(ExportLoc, diag::err_export_within_export);
17330 
17331   CurContext->addDecl(D);
17332   PushDeclContext(S, D);
17333   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17334   return D;
17335 }
17336 
17337 /// Complete the definition of an export declaration.
17338 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17339   auto *ED = cast<ExportDecl>(D);
17340   if (RBraceLoc.isValid())
17341     ED->setRBraceLoc(RBraceLoc);
17342 
17343   // FIXME: Diagnose export of internal-linkage declaration (including
17344   // anonymous namespace).
17345 
17346   PopDeclContext();
17347   return D;
17348 }
17349 
17350 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17351                                       IdentifierInfo* AliasName,
17352                                       SourceLocation PragmaLoc,
17353                                       SourceLocation NameLoc,
17354                                       SourceLocation AliasNameLoc) {
17355   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17356                                          LookupOrdinaryName);
17357   AsmLabelAttr *Attr =
17358       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17359 
17360   // If a declaration that:
17361   // 1) declares a function or a variable
17362   // 2) has external linkage
17363   // already exists, add a label attribute to it.
17364   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17365     if (isDeclExternC(PrevDecl))
17366       PrevDecl->addAttr(Attr);
17367     else
17368       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17369           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17370   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17371   } else
17372     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17373 }
17374 
17375 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17376                              SourceLocation PragmaLoc,
17377                              SourceLocation NameLoc) {
17378   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17379 
17380   if (PrevDecl) {
17381     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17382   } else {
17383     (void)WeakUndeclaredIdentifiers.insert(
17384       std::pair<IdentifierInfo*,WeakInfo>
17385         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17386   }
17387 }
17388 
17389 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17390                                 IdentifierInfo* AliasName,
17391                                 SourceLocation PragmaLoc,
17392                                 SourceLocation NameLoc,
17393                                 SourceLocation AliasNameLoc) {
17394   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17395                                     LookupOrdinaryName);
17396   WeakInfo W = WeakInfo(Name, NameLoc);
17397 
17398   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17399     if (!PrevDecl->hasAttr<AliasAttr>())
17400       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17401         DeclApplyPragmaWeak(TUScope, ND, W);
17402   } else {
17403     (void)WeakUndeclaredIdentifiers.insert(
17404       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17405   }
17406 }
17407 
17408 Decl *Sema::getObjCDeclContext() const {
17409   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17410 }
17411