]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88
89       if (AllowNonTemplates)
90         return true;
91
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102
103       return false;
104     }
105
106     return !WantClassName && candidate.isKeyword();
107   }
108
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115
116 } // end anonymous namespace
117
118 /// Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150
151   case tok::kw_char8_t:
152     return getLangOpts().Char8;
153
154   default:
155     break;
156   }
157
158   return false;
159 }
160
161 namespace {
162 enum class UnqualifiedTypeNameLookupResult {
163   NotFound,
164   FoundNonType,
165   FoundType
166 };
167 } // end anonymous namespace
168
169 /// Tries to perform unqualified lookup of the type decls in bases for
170 /// dependent class.
171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
172 /// type decl, \a FoundType if only type decls are found.
173 static UnqualifiedTypeNameLookupResult
174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
175                                 SourceLocation NameLoc,
176                                 const CXXRecordDecl *RD) {
177   if (!RD->hasDefinition())
178     return UnqualifiedTypeNameLookupResult::NotFound;
179   // Look for type decls in base classes.
180   UnqualifiedTypeNameLookupResult FoundTypeDecl =
181       UnqualifiedTypeNameLookupResult::NotFound;
182   for (const auto &Base : RD->bases()) {
183     const CXXRecordDecl *BaseRD = nullptr;
184     if (auto *BaseTT = Base.getType()->getAs<TagType>())
185       BaseRD = BaseTT->getAsCXXRecordDecl();
186     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
187       // Look for type decls in dependent base classes that have known primary
188       // templates.
189       if (!TST || !TST->isDependentType())
190         continue;
191       auto *TD = TST->getTemplateName().getAsTemplateDecl();
192       if (!TD)
193         continue;
194       if (auto *BasePrimaryTemplate =
195           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
196         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
197           BaseRD = BasePrimaryTemplate;
198         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199           if (const ClassTemplatePartialSpecializationDecl *PS =
200                   CTD->findPartialSpecialization(Base.getType()))
201             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
202               BaseRD = PS;
203         }
204       }
205     }
206     if (BaseRD) {
207       for (NamedDecl *ND : BaseRD->lookup(&II)) {
208         if (!isa<TypeDecl>(ND))
209           return UnqualifiedTypeNameLookupResult::FoundNonType;
210         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
211       }
212       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
213         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
214         case UnqualifiedTypeNameLookupResult::FoundNonType:
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         case UnqualifiedTypeNameLookupResult::FoundType:
217           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218           break;
219         case UnqualifiedTypeNameLookupResult::NotFound:
220           break;
221         }
222       }
223     }
224   }
225
226   return FoundTypeDecl;
227 }
228
229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
230                                                       const IdentifierInfo &II,
231                                                       SourceLocation NameLoc) {
232   // Lookup in the parent class template context, if any.
233   const CXXRecordDecl *RD = nullptr;
234   UnqualifiedTypeNameLookupResult FoundTypeDecl =
235       UnqualifiedTypeNameLookupResult::NotFound;
236   for (DeclContext *DC = S.CurContext;
237        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
238        DC = DC->getParent()) {
239     // Look for type decls in dependent base classes that have known primary
240     // templates.
241     RD = dyn_cast<CXXRecordDecl>(DC);
242     if (RD && RD->getDescribedClassTemplate())
243       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
244   }
245   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
246     return nullptr;
247
248   // We found some types in dependent base classes.  Recover as if the user
249   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
250   // lookup during template instantiation.
251   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
252
253   ASTContext &Context = S.Context;
254   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
255                                           cast<Type>(Context.getRecordType(RD)));
256   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
257
258   CXXScopeSpec SS;
259   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
260
261   TypeLocBuilder Builder;
262   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
263   DepTL.setNameLoc(NameLoc);
264   DepTL.setElaboratedKeywordLoc(SourceLocation());
265   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
266   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
267 }
268
269 /// If the identifier refers to a type name within this scope,
270 /// return the declaration of that type.
271 ///
272 /// This routine performs ordinary name lookup of the identifier II
273 /// within the given scope, with optional C++ scope specifier SS, to
274 /// determine whether the name refers to a type. If so, returns an
275 /// opaque pointer (actually a QualType) corresponding to that
276 /// type. Otherwise, returns NULL.
277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
278                              Scope *S, CXXScopeSpec *SS,
279                              bool isClassName, bool HasTrailingDot,
280                              ParsedType ObjectTypePtr,
281                              bool IsCtorOrDtorName,
282                              bool WantNontrivialTypeSourceInfo,
283                              bool IsClassTemplateDeductionContext,
284                              IdentifierInfo **CorrectedII) {
285   // FIXME: Consider allowing this outside C++1z mode as an extension.
286   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
288                               !isClassName && !HasTrailingDot;
289
290   // Determine where we will perform name lookup.
291   DeclContext *LookupCtx = nullptr;
292   if (ObjectTypePtr) {
293     QualType ObjectType = ObjectTypePtr.get();
294     if (ObjectType->isRecordType())
295       LookupCtx = computeDeclContext(ObjectType);
296   } else if (SS && SS->isNotEmpty()) {
297     LookupCtx = computeDeclContext(*SS, false);
298
299     if (!LookupCtx) {
300       if (isDependentScopeSpecifier(*SS)) {
301         // C++ [temp.res]p3:
302         //   A qualified-id that refers to a type and in which the
303         //   nested-name-specifier depends on a template-parameter (14.6.2)
304         //   shall be prefixed by the keyword typename to indicate that the
305         //   qualified-id denotes a type, forming an
306         //   elaborated-type-specifier (7.1.5.3).
307         //
308         // We therefore do not perform any name lookup if the result would
309         // refer to a member of an unknown specialization.
310         if (!isClassName && !IsCtorOrDtorName)
311           return nullptr;
312
313         // We know from the grammar that this name refers to a type,
314         // so build a dependent node to describe the type.
315         if (WantNontrivialTypeSourceInfo)
316           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
317
318         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
319         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
320                                        II, NameLoc);
321         return ParsedType::make(T);
322       }
323
324       return nullptr;
325     }
326
327     if (!LookupCtx->isDependentContext() &&
328         RequireCompleteDeclContext(*SS, LookupCtx))
329       return nullptr;
330   }
331
332   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
333   // lookup for class-names.
334   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
335                                       LookupOrdinaryName;
336   LookupResult Result(*this, &II, NameLoc, Kind);
337   if (LookupCtx) {
338     // Perform "qualified" name lookup into the declaration context we
339     // computed, which is either the type of the base of a member access
340     // expression or the declaration context associated with a prior
341     // nested-name-specifier.
342     LookupQualifiedName(Result, LookupCtx);
343
344     if (ObjectTypePtr && Result.empty()) {
345       // C++ [basic.lookup.classref]p3:
346       //   If the unqualified-id is ~type-name, the type-name is looked up
347       //   in the context of the entire postfix-expression. If the type T of
348       //   the object expression is of a class type C, the type-name is also
349       //   looked up in the scope of class C. At least one of the lookups shall
350       //   find a name that refers to (possibly cv-qualified) T.
351       LookupName(Result, S);
352     }
353   } else {
354     // Perform unqualified name lookup.
355     LookupName(Result, S);
356
357     // For unqualified lookup in a class template in MSVC mode, look into
358     // dependent base classes where the primary class template is known.
359     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
360       if (ParsedType TypeInBase =
361               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
362         return TypeInBase;
363     }
364   }
365
366   NamedDecl *IIDecl = nullptr;
367   switch (Result.getResultKind()) {
368   case LookupResult::NotFound:
369   case LookupResult::NotFoundInCurrentInstantiation:
370     if (CorrectedII) {
371       TypoCorrection Correction =
372           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
373                       llvm::make_unique<TypeNameValidatorCCC>(
374                           true, isClassName, AllowDeducedTemplate),
375                       CTK_ErrorRecovery);
376       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
377       TemplateTy Template;
378       bool MemberOfUnknownSpecialization;
379       UnqualifiedId TemplateName;
380       TemplateName.setIdentifier(NewII, NameLoc);
381       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
382       CXXScopeSpec NewSS, *NewSSPtr = SS;
383       if (SS && NNS) {
384         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
385         NewSSPtr = &NewSS;
386       }
387       if (Correction && (NNS || NewII != &II) &&
388           // Ignore a correction to a template type as the to-be-corrected
389           // identifier is not a template (typo correction for template names
390           // is handled elsewhere).
391           !(getLangOpts().CPlusPlus && NewSSPtr &&
392             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
393                            Template, MemberOfUnknownSpecialization))) {
394         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
395                                     isClassName, HasTrailingDot, ObjectTypePtr,
396                                     IsCtorOrDtorName,
397                                     WantNontrivialTypeSourceInfo,
398                                     IsClassTemplateDeductionContext);
399         if (Ty) {
400           diagnoseTypo(Correction,
401                        PDiag(diag::err_unknown_type_or_class_name_suggest)
402                          << Result.getLookupName() << isClassName);
403           if (SS && NNS)
404             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
405           *CorrectedII = NewII;
406           return Ty;
407         }
408       }
409     }
410     // If typo correction failed or was not performed, fall through
411     LLVM_FALLTHROUGH;
412   case LookupResult::FoundOverloaded:
413   case LookupResult::FoundUnresolvedValue:
414     Result.suppressDiagnostics();
415     return nullptr;
416
417   case LookupResult::Ambiguous:
418     // Recover from type-hiding ambiguities by hiding the type.  We'll
419     // do the lookup again when looking for an object, and we can
420     // diagnose the error then.  If we don't do this, then the error
421     // about hiding the type will be immediately followed by an error
422     // that only makes sense if the identifier was treated like a type.
423     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
424       Result.suppressDiagnostics();
425       return nullptr;
426     }
427
428     // Look to see if we have a type anywhere in the list of results.
429     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
430          Res != ResEnd; ++Res) {
431       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
432           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
433         if (!IIDecl ||
434             (*Res)->getLocation().getRawEncoding() <
435               IIDecl->getLocation().getRawEncoding())
436           IIDecl = *Res;
437       }
438     }
439
440     if (!IIDecl) {
441       // None of the entities we found is a type, so there is no way
442       // to even assume that the result is a type. In this case, don't
443       // complain about the ambiguity. The parser will either try to
444       // perform this lookup again (e.g., as an object name), which
445       // will produce the ambiguity, or will complain that it expected
446       // a type name.
447       Result.suppressDiagnostics();
448       return nullptr;
449     }
450
451     // We found a type within the ambiguous lookup; diagnose the
452     // ambiguity and then return that type. This might be the right
453     // answer, or it might not be, but it suppresses any attempt to
454     // perform the name lookup again.
455     break;
456
457   case LookupResult::Found:
458     IIDecl = Result.getFoundDecl();
459     break;
460   }
461
462   assert(IIDecl && "Didn't find decl");
463
464   QualType T;
465   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
466     // C++ [class.qual]p2: A lookup that would find the injected-class-name
467     // instead names the constructors of the class, except when naming a class.
468     // This is ill-formed when we're not actually forming a ctor or dtor name.
469     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
470     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
471     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
472         FoundRD->isInjectedClassName() &&
473         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
474       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
475           << &II << /*Type*/1;
476
477     DiagnoseUseOfDecl(IIDecl, NameLoc);
478
479     T = Context.getTypeDeclType(TD);
480     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
481   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
482     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
483     if (!HasTrailingDot)
484       T = Context.getObjCInterfaceType(IDecl);
485   } else if (AllowDeducedTemplate) {
486     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
488                                                        QualType(), false);
489   }
490
491   if (T.isNull()) {
492     // If it's not plausibly a type, suppress diagnostics.
493     Result.suppressDiagnostics();
494     return nullptr;
495   }
496
497   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
498   // constructor or destructor name (in such a case, the scope specifier
499   // will be attached to the enclosing Expr or Decl node).
500   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
501       !isa<ObjCInterfaceDecl>(IIDecl)) {
502     if (WantNontrivialTypeSourceInfo) {
503       // Construct a type with type-source information.
504       TypeLocBuilder Builder;
505       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
506
507       T = getElaboratedType(ETK_None, *SS, T);
508       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509       ElabTL.setElaboratedKeywordLoc(SourceLocation());
510       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
511       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
512     } else {
513       T = getElaboratedType(ETK_None, *SS, T);
514     }
515   }
516
517   return ParsedType::make(T);
518 }
519
520 // Builds a fake NNS for the given decl context.
521 static NestedNameSpecifier *
522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
523   for (;; DC = DC->getLookupParent()) {
524     DC = DC->getPrimaryContext();
525     auto *ND = dyn_cast<NamespaceDecl>(DC);
526     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
527       return NestedNameSpecifier::Create(Context, nullptr, ND);
528     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
529       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
530                                          RD->getTypeForDecl());
531     else if (isa<TranslationUnitDecl>(DC))
532       return NestedNameSpecifier::GlobalSpecifier(Context);
533   }
534   llvm_unreachable("something isn't in TU scope?");
535 }
536
537 /// Find the parent class with dependent bases of the innermost enclosing method
538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
539 /// up allowing unqualified dependent type names at class-level, which MSVC
540 /// correctly rejects.
541 static const CXXRecordDecl *
542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
543   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
544     DC = DC->getPrimaryContext();
545     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
546       if (MD->getParent()->hasAnyDependentBases())
547         return MD->getParent();
548   }
549   return nullptr;
550 }
551
552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
553                                           SourceLocation NameLoc,
554                                           bool IsTemplateTypeArg) {
555   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
556
557   NestedNameSpecifier *NNS = nullptr;
558   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
559     // If we weren't able to parse a default template argument, delay lookup
560     // until instantiation time by making a non-dependent DependentTypeName. We
561     // pretend we saw a NestedNameSpecifier referring to the current scope, and
562     // lookup is retried.
563     // FIXME: This hurts our diagnostic quality, since we get errors like "no
564     // type named 'Foo' in 'current_namespace'" when the user didn't write any
565     // name specifiers.
566     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
567     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
568   } else if (const CXXRecordDecl *RD =
569                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
570     // Build a DependentNameType that will perform lookup into RD at
571     // instantiation time.
572     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
573                                       RD->getTypeForDecl());
574
575     // Diagnose that this identifier was undeclared, and retry the lookup during
576     // template instantiation.
577     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
578                                                                       << RD;
579   } else {
580     // This is not a situation that we should recover from.
581     return ParsedType();
582   }
583
584   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
585
586   // Build type location information.  We synthesized the qualifier, so we have
587   // to build a fake NestedNameSpecifierLoc.
588   NestedNameSpecifierLocBuilder NNSLocBuilder;
589   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
590   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
591
592   TypeLocBuilder Builder;
593   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
594   DepTL.setNameLoc(NameLoc);
595   DepTL.setElaboratedKeywordLoc(SourceLocation());
596   DepTL.setQualifierLoc(QualifierLoc);
597   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
598 }
599
600 /// isTagName() - This method is called *for error recovery purposes only*
601 /// to determine if the specified name is a valid tag name ("struct foo").  If
602 /// so, this returns the TST for the tag corresponding to it (TST_enum,
603 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
604 /// cases in C where the user forgot to specify the tag.
605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
606   // Do a tag name lookup in this scope.
607   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
608   LookupName(R, S, false);
609   R.suppressDiagnostics();
610   if (R.getResultKind() == LookupResult::Found)
611     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
612       switch (TD->getTagKind()) {
613       case TTK_Struct: return DeclSpec::TST_struct;
614       case TTK_Interface: return DeclSpec::TST_interface;
615       case TTK_Union:  return DeclSpec::TST_union;
616       case TTK_Class:  return DeclSpec::TST_class;
617       case TTK_Enum:   return DeclSpec::TST_enum;
618       }
619     }
620
621   return DeclSpec::TST_unspecified;
622 }
623
624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
626 /// then downgrade the missing typename error to a warning.
627 /// This is needed for MSVC compatibility; Example:
628 /// @code
629 /// template<class T> class A {
630 /// public:
631 ///   typedef int TYPE;
632 /// };
633 /// template<class T> class B : public A<T> {
634 /// public:
635 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
636 /// };
637 /// @endcode
638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
639   if (CurContext->isRecord()) {
640     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
641       return true;
642
643     const Type *Ty = SS->getScopeRep()->getAsType();
644
645     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
646     for (const auto &Base : RD->bases())
647       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
648         return true;
649     return S->isFunctionPrototypeScope();
650   }
651   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
652 }
653
654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
655                                    SourceLocation IILoc,
656                                    Scope *S,
657                                    CXXScopeSpec *SS,
658                                    ParsedType &SuggestedType,
659                                    bool IsTemplateName) {
660   // Don't report typename errors for editor placeholders.
661   if (II->isEditorPlaceholder())
662     return;
663   // We don't have anything to suggest (yet).
664   SuggestedType = nullptr;
665
666   // There may have been a typo in the name of the type. Look up typo
667   // results, in case we have something that we can suggest.
668   if (TypoCorrection Corrected =
669           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
670                       llvm::make_unique<TypeNameValidatorCCC>(
671                           false, false, IsTemplateName, !IsTemplateName),
672                       CTK_ErrorRecovery)) {
673     // FIXME: Support error recovery for the template-name case.
674     bool CanRecover = !IsTemplateName;
675     if (Corrected.isKeyword()) {
676       // We corrected to a keyword.
677       diagnoseTypo(Corrected,
678                    PDiag(IsTemplateName ? diag::err_no_template_suggest
679                                         : diag::err_unknown_typename_suggest)
680                        << II);
681       II = Corrected.getCorrectionAsIdentifierInfo();
682     } else {
683       // We found a similarly-named type or interface; suggest that.
684       if (!SS || !SS->isSet()) {
685         diagnoseTypo(Corrected,
686                      PDiag(IsTemplateName ? diag::err_no_template_suggest
687                                           : diag::err_unknown_typename_suggest)
688                          << II, CanRecover);
689       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
690         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
691         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
692                                 II->getName().equals(CorrectedStr);
693         diagnoseTypo(Corrected,
694                      PDiag(IsTemplateName
695                                ? diag::err_no_member_template_suggest
696                                : diag::err_unknown_nested_typename_suggest)
697                          << II << DC << DroppedSpecifier << SS->getRange(),
698                      CanRecover);
699       } else {
700         llvm_unreachable("could not have corrected a typo here");
701       }
702
703       if (!CanRecover)
704         return;
705
706       CXXScopeSpec tmpSS;
707       if (Corrected.getCorrectionSpecifier())
708         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
709                           SourceRange(IILoc));
710       // FIXME: Support class template argument deduction here.
711       SuggestedType =
712           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
713                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
714                       /*IsCtorOrDtorName=*/false,
715                       /*NonTrivialTypeSourceInfo=*/true);
716     }
717     return;
718   }
719
720   if (getLangOpts().CPlusPlus && !IsTemplateName) {
721     // See if II is a class template that the user forgot to pass arguments to.
722     UnqualifiedId Name;
723     Name.setIdentifier(II, IILoc);
724     CXXScopeSpec EmptySS;
725     TemplateTy TemplateResult;
726     bool MemberOfUnknownSpecialization;
727     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
728                        Name, nullptr, true, TemplateResult,
729                        MemberOfUnknownSpecialization) == TNK_Type_template) {
730       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
731       return;
732     }
733   }
734
735   // FIXME: Should we move the logic that tries to recover from a missing tag
736   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
737
738   if (!SS || (!SS->isSet() && !SS->isInvalid()))
739     Diag(IILoc, IsTemplateName ? diag::err_no_template
740                                : diag::err_unknown_typename)
741         << II;
742   else if (DeclContext *DC = computeDeclContext(*SS, false))
743     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
744                                : diag::err_typename_nested_not_found)
745         << II << DC << SS->getRange();
746   else if (isDependentScopeSpecifier(*SS)) {
747     unsigned DiagID = diag::err_typename_missing;
748     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
749       DiagID = diag::ext_typename_missing;
750
751     Diag(SS->getRange().getBegin(), DiagID)
752       << SS->getScopeRep() << II->getName()
753       << SourceRange(SS->getRange().getBegin(), IILoc)
754       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
755     SuggestedType = ActOnTypenameType(S, SourceLocation(),
756                                       *SS, *II, IILoc).get();
757   } else {
758     assert(SS && SS->isInvalid() &&
759            "Invalid scope specifier has already been diagnosed");
760   }
761 }
762
763 /// Determine whether the given result set contains either a type name
764 /// or
765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
766   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
767                        NextToken.is(tok::less);
768
769   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
770     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
771       return true;
772
773     if (CheckTemplate && isa<TemplateDecl>(*I))
774       return true;
775   }
776
777   return false;
778 }
779
780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
781                                     Scope *S, CXXScopeSpec &SS,
782                                     IdentifierInfo *&Name,
783                                     SourceLocation NameLoc) {
784   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
785   SemaRef.LookupParsedName(R, S, &SS);
786   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
787     StringRef FixItTagName;
788     switch (Tag->getTagKind()) {
789       case TTK_Class:
790         FixItTagName = "class ";
791         break;
792
793       case TTK_Enum:
794         FixItTagName = "enum ";
795         break;
796
797       case TTK_Struct:
798         FixItTagName = "struct ";
799         break;
800
801       case TTK_Interface:
802         FixItTagName = "__interface ";
803         break;
804
805       case TTK_Union:
806         FixItTagName = "union ";
807         break;
808     }
809
810     StringRef TagName = FixItTagName.drop_back();
811     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
812       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
813       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
814
815     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
816          I != IEnd; ++I)
817       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
818         << Name << TagName;
819
820     // Replace lookup results with just the tag decl.
821     Result.clear(Sema::LookupTagName);
822     SemaRef.LookupParsedName(Result, S, &SS);
823     return true;
824   }
825
826   return false;
827 }
828
829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
831                                   QualType T, SourceLocation NameLoc) {
832   ASTContext &Context = S.Context;
833
834   TypeLocBuilder Builder;
835   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
836
837   T = S.getElaboratedType(ETK_None, SS, T);
838   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839   ElabTL.setElaboratedKeywordLoc(SourceLocation());
840   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
841   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
842 }
843
844 Sema::NameClassification
845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
846                    SourceLocation NameLoc, const Token &NextToken,
847                    bool IsAddressOfOperand,
848                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
849   DeclarationNameInfo NameInfo(Name, NameLoc);
850   ObjCMethodDecl *CurMethod = getCurMethodDecl();
851
852   if (NextToken.is(tok::coloncolon)) {
853     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
854     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
855   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
856              isCurrentClassName(*Name, S, &SS)) {
857     // Per [class.qual]p2, this names the constructors of SS, not the
858     // injected-class-name. We don't have a classification for that.
859     // There's not much point caching this result, since the parser
860     // will reject it later.
861     return NameClassification::Unknown();
862   }
863
864   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865   LookupParsedName(Result, S, &SS, !CurMethod);
866
867   // For unqualified lookup in a class template in MSVC mode, look into
868   // dependent base classes where the primary class template is known.
869   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
870     if (ParsedType TypeInBase =
871             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
872       return TypeInBase;
873   }
874
875   // Perform lookup for Objective-C instance variables (including automatically
876   // synthesized instance variables), if we're in an Objective-C method.
877   // FIXME: This lookup really, really needs to be folded in to the normal
878   // unqualified lookup mechanism.
879   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
880     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
881     if (E.get() || E.isInvalid())
882       return E;
883   }
884
885   bool SecondTry = false;
886   bool IsFilteredTemplateName = false;
887
888 Corrected:
889   switch (Result.getResultKind()) {
890   case LookupResult::NotFound:
891     // If an unqualified-id is followed by a '(', then we have a function
892     // call.
893     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
894       // In C++, this is an ADL-only call.
895       // FIXME: Reference?
896       if (getLangOpts().CPlusPlus)
897         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
898
899       // C90 6.3.2.2:
900       //   If the expression that precedes the parenthesized argument list in a
901       //   function call consists solely of an identifier, and if no
902       //   declaration is visible for this identifier, the identifier is
903       //   implicitly declared exactly as if, in the innermost block containing
904       //   the function call, the declaration
905       //
906       //     extern int identifier ();
907       //
908       //   appeared.
909       //
910       // We also allow this in C99 as an extension.
911       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
912         Result.addDecl(D);
913         Result.resolveKind();
914         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
915       }
916     }
917
918     // In C, we first see whether there is a tag type by the same name, in
919     // which case it's likely that the user just forgot to write "enum",
920     // "struct", or "union".
921     if (!getLangOpts().CPlusPlus && !SecondTry &&
922         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
923       break;
924     }
925
926     // Perform typo correction to determine if there is another name that is
927     // close to this name.
928     if (!SecondTry && CCC) {
929       SecondTry = true;
930       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
931                                                  Result.getLookupKind(), S,
932                                                  &SS, std::move(CCC),
933                                                  CTK_ErrorRecovery)) {
934         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
935         unsigned QualifiedDiag = diag::err_no_member_suggest;
936
937         NamedDecl *FirstDecl = Corrected.getFoundDecl();
938         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
939         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
940             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
941           UnqualifiedDiag = diag::err_no_template_suggest;
942           QualifiedDiag = diag::err_no_member_template_suggest;
943         } else if (UnderlyingFirstDecl &&
944                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
946                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
947           UnqualifiedDiag = diag::err_unknown_typename_suggest;
948           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
949         }
950
951         if (SS.isEmpty()) {
952           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
953         } else {// FIXME: is this even reachable? Test it.
954           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
955           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
956                                   Name->getName().equals(CorrectedStr);
957           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
958                                     << Name << computeDeclContext(SS, false)
959                                     << DroppedSpecifier << SS.getRange());
960         }
961
962         // Update the name, so that the caller has the new name.
963         Name = Corrected.getCorrectionAsIdentifierInfo();
964
965         // Typo correction corrected to a keyword.
966         if (Corrected.isKeyword())
967           return Name;
968
969         // Also update the LookupResult...
970         // FIXME: This should probably go away at some point
971         Result.clear();
972         Result.setLookupName(Corrected.getCorrection());
973         if (FirstDecl)
974           Result.addDecl(FirstDecl);
975
976         // If we found an Objective-C instance variable, let
977         // LookupInObjCMethod build the appropriate expression to
978         // reference the ivar.
979         // FIXME: This is a gross hack.
980         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
981           Result.clear();
982           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
983           return E;
984         }
985
986         goto Corrected;
987       }
988     }
989
990     // We failed to correct; just fall through and let the parser deal with it.
991     Result.suppressDiagnostics();
992     return NameClassification::Unknown();
993
994   case LookupResult::NotFoundInCurrentInstantiation: {
995     // We performed name lookup into the current instantiation, and there were
996     // dependent bases, so we treat this result the same way as any other
997     // dependent nested-name-specifier.
998
999     // C++ [temp.res]p2:
1000     //   A name used in a template declaration or definition and that is
1001     //   dependent on a template-parameter is assumed not to name a type
1002     //   unless the applicable name lookup finds a type name or the name is
1003     //   qualified by the keyword typename.
1004     //
1005     // FIXME: If the next token is '<', we might want to ask the parser to
1006     // perform some heroics to see if we actually have a
1007     // template-argument-list, which would indicate a missing 'template'
1008     // keyword here.
1009     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1010                                       NameInfo, IsAddressOfOperand,
1011                                       /*TemplateArgs=*/nullptr);
1012   }
1013
1014   case LookupResult::Found:
1015   case LookupResult::FoundOverloaded:
1016   case LookupResult::FoundUnresolvedValue:
1017     break;
1018
1019   case LookupResult::Ambiguous:
1020     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1021         hasAnyAcceptableTemplateNames(Result)) {
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 || hasAnyAcceptableTemplateNames(Result))) {
1046     // C++ [temp.names]p3:
1047     //   After name lookup (3.4) finds that a name is a template-name or that
1048     //   an operator-function-id or a literal- operator-id refers to a set of
1049     //   overloaded functions any member of which is a function template if
1050     //   this is followed by a <, the < is always taken as the delimiter of a
1051     //   template-argument-list and never as the less-than operator.
1052     if (!IsFilteredTemplateName)
1053       FilterAcceptableTemplateNames(Result);
1054
1055     if (!Result.empty()) {
1056       bool IsFunctionTemplate;
1057       bool IsVarTemplate;
1058       TemplateName Template;
1059       if (Result.end() - Result.begin() > 1) {
1060         IsFunctionTemplate = true;
1061         Template = Context.getOverloadedTemplateName(Result.begin(),
1062                                                      Result.end());
1063       } else {
1064         TemplateDecl *TD
1065           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1066         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1067         IsVarTemplate = isa<VarTemplateDecl>(TD);
1068
1069         if (SS.isSet() && !SS.isInvalid())
1070           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1071                                                     /*TemplateKeyword=*/false,
1072                                                       TD);
1073         else
1074           Template = TemplateName(TD);
1075       }
1076
1077       if (IsFunctionTemplate) {
1078         // Function templates always go through overload resolution, at which
1079         // point we'll perform the various checks (e.g., accessibility) we need
1080         // to based on which function we selected.
1081         Result.suppressDiagnostics();
1082
1083         return NameClassification::FunctionTemplate(Template);
1084       }
1085
1086       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1087                            : NameClassification::TypeTemplate(Template);
1088     }
1089   }
1090
1091   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1092   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1093     DiagnoseUseOfDecl(Type, NameLoc);
1094     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1095     QualType T = Context.getTypeDeclType(Type);
1096     if (SS.isNotEmpty())
1097       return buildNestedType(*this, SS, T, NameLoc);
1098     return ParsedType::make(T);
1099   }
1100
1101   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1102   if (!Class) {
1103     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1104     if (ObjCCompatibleAliasDecl *Alias =
1105             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1106       Class = Alias->getClassInterface();
1107   }
1108
1109   if (Class) {
1110     DiagnoseUseOfDecl(Class, NameLoc);
1111
1112     if (NextToken.is(tok::period)) {
1113       // Interface. <something> is parsed as a property reference expression.
1114       // Just return "unknown" as a fall-through for now.
1115       Result.suppressDiagnostics();
1116       return NameClassification::Unknown();
1117     }
1118
1119     QualType T = Context.getObjCInterfaceType(Class);
1120     return ParsedType::make(T);
1121   }
1122
1123   // We can have a type template here if we're classifying a template argument.
1124   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1125       !isa<VarTemplateDecl>(FirstDecl))
1126     return NameClassification::TypeTemplate(
1127         TemplateName(cast<TemplateDecl>(FirstDecl)));
1128
1129   // Check for a tag type hidden by a non-type decl in a few cases where it
1130   // seems likely a type is wanted instead of the non-type that was found.
1131   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1132   if ((NextToken.is(tok::identifier) ||
1133        (NextIsOp &&
1134         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1135       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1136     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1137     DiagnoseUseOfDecl(Type, NameLoc);
1138     QualType T = Context.getTypeDeclType(Type);
1139     if (SS.isNotEmpty())
1140       return buildNestedType(*this, SS, T, NameLoc);
1141     return ParsedType::make(T);
1142   }
1143
1144   if (FirstDecl->isCXXClassMember())
1145     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1146                                            nullptr, S);
1147
1148   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1149   return BuildDeclarationNameExpr(SS, Result, ADL);
1150 }
1151
1152 Sema::TemplateNameKindForDiagnostics
1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1154   auto *TD = Name.getAsTemplateDecl();
1155   if (!TD)
1156     return TemplateNameKindForDiagnostics::DependentTemplate;
1157   if (isa<ClassTemplateDecl>(TD))
1158     return TemplateNameKindForDiagnostics::ClassTemplate;
1159   if (isa<FunctionTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::FunctionTemplate;
1161   if (isa<VarTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::VarTemplate;
1163   if (isa<TypeAliasTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::AliasTemplate;
1165   if (isa<TemplateTemplateParmDecl>(TD))
1166     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1167   return TemplateNameKindForDiagnostics::DependentTemplate;
1168 }
1169
1170 // Determines the context to return to after temporarily entering a
1171 // context.  This depends in an unnecessarily complicated way on the
1172 // exact ordering of callbacks from the parser.
1173 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1174
1175   // Functions defined inline within classes aren't parsed until we've
1176   // finished parsing the top-level class, so the top-level class is
1177   // the context we'll need to return to.
1178   // A Lambda call operator whose parent is a class must not be treated
1179   // as an inline member function.  A Lambda can be used legally
1180   // either as an in-class member initializer or a default argument.  These
1181   // are parsed once the class has been marked complete and so the containing
1182   // context would be the nested class (when the lambda is defined in one);
1183   // If the class is not complete, then the lambda is being used in an
1184   // ill-formed fashion (such as to specify the width of a bit-field, or
1185   // in an array-bound) - in which case we still want to return the
1186   // lexically containing DC (which could be a nested class).
1187   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1188     DC = DC->getLexicalParent();
1189
1190     // A function not defined within a class will always return to its
1191     // lexical context.
1192     if (!isa<CXXRecordDecl>(DC))
1193       return DC;
1194
1195     // A C++ inline method/friend is parsed *after* the topmost class
1196     // it was declared in is fully parsed ("complete");  the topmost
1197     // class is the context we need to return to.
1198     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1199       DC = RD;
1200
1201     // Return the declaration context of the topmost class the inline method is
1202     // declared in.
1203     return DC;
1204   }
1205
1206   return DC->getLexicalParent();
1207 }
1208
1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1210   assert(getContainingDC(DC) == CurContext &&
1211       "The next DeclContext should be lexically contained in the current one.");
1212   CurContext = DC;
1213   S->setEntity(DC);
1214 }
1215
1216 void Sema::PopDeclContext() {
1217   assert(CurContext && "DeclContext imbalance!");
1218
1219   CurContext = getContainingDC(CurContext);
1220   assert(CurContext && "Popped translation unit!");
1221 }
1222
1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1224                                                                     Decl *D) {
1225   // Unlike PushDeclContext, the context to which we return is not necessarily
1226   // the containing DC of TD, because the new context will be some pre-existing
1227   // TagDecl definition instead of a fresh one.
1228   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1229   CurContext = cast<TagDecl>(D)->getDefinition();
1230   assert(CurContext && "skipping definition of undefined tag");
1231   // Start lookups from the parent of the current context; we don't want to look
1232   // into the pre-existing complete definition.
1233   S->setEntity(CurContext->getLookupParent());
1234   return Result;
1235 }
1236
1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1238   CurContext = static_cast<decltype(CurContext)>(Context);
1239 }
1240
1241 /// EnterDeclaratorContext - Used when we must lookup names in the context
1242 /// of a declarator's nested name specifier.
1243 ///
1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1245   // C++0x [basic.lookup.unqual]p13:
1246   //   A name used in the definition of a static data member of class
1247   //   X (after the qualified-id of the static member) is looked up as
1248   //   if the name was used in a member function of X.
1249   // C++0x [basic.lookup.unqual]p14:
1250   //   If a variable member of a namespace is defined outside of the
1251   //   scope of its namespace then any name used in the definition of
1252   //   the variable member (after the declarator-id) is looked up as
1253   //   if the definition of the variable member occurred in its
1254   //   namespace.
1255   // Both of these imply that we should push a scope whose context
1256   // is the semantic context of the declaration.  We can't use
1257   // PushDeclContext here because that context is not necessarily
1258   // lexically contained in the current context.  Fortunately,
1259   // the containing scope should have the appropriate information.
1260
1261   assert(!S->getEntity() && "scope already has entity");
1262
1263 #ifndef NDEBUG
1264   Scope *Ancestor = S->getParent();
1265   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1266   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1267 #endif
1268
1269   CurContext = DC;
1270   S->setEntity(DC);
1271 }
1272
1273 void Sema::ExitDeclaratorContext(Scope *S) {
1274   assert(S->getEntity() == CurContext && "Context imbalance!");
1275
1276   // Switch back to the lexical context.  The safety of this is
1277   // enforced by an assert in EnterDeclaratorContext.
1278   Scope *Ancestor = S->getParent();
1279   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1280   CurContext = Ancestor->getEntity();
1281
1282   // We don't need to do anything with the scope, which is going to
1283   // disappear.
1284 }
1285
1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1287   // We assume that the caller has already called
1288   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1289   FunctionDecl *FD = D->getAsFunction();
1290   if (!FD)
1291     return;
1292
1293   // Same implementation as PushDeclContext, but enters the context
1294   // from the lexical parent, rather than the top-level class.
1295   assert(CurContext == FD->getLexicalParent() &&
1296     "The next DeclContext should be lexically contained in the current one.");
1297   CurContext = FD;
1298   S->setEntity(CurContext);
1299
1300   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1301     ParmVarDecl *Param = FD->getParamDecl(P);
1302     // If the parameter has an identifier, then add it to the scope
1303     if (Param->getIdentifier()) {
1304       S->AddDecl(Param);
1305       IdResolver.AddDecl(Param);
1306     }
1307   }
1308 }
1309
1310 void Sema::ActOnExitFunctionContext() {
1311   // Same implementation as PopDeclContext, but returns to the lexical parent,
1312   // rather than the top-level class.
1313   assert(CurContext && "DeclContext imbalance!");
1314   CurContext = CurContext->getLexicalParent();
1315   assert(CurContext && "Popped translation unit!");
1316 }
1317
1318 /// Determine whether we allow overloading of the function
1319 /// PrevDecl with another declaration.
1320 ///
1321 /// This routine determines whether overloading is possible, not
1322 /// whether some new function is actually an overload. It will return
1323 /// true in C++ (where we can always provide overloads) or, as an
1324 /// extension, in C when the previous function is already an
1325 /// overloaded function declaration or has the "overloadable"
1326 /// attribute.
1327 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1328                                        ASTContext &Context,
1329                                        const FunctionDecl *New) {
1330   if (Context.getLangOpts().CPlusPlus)
1331     return true;
1332
1333   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1334     return true;
1335
1336   return Previous.getResultKind() == LookupResult::Found &&
1337          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1338           New->hasAttr<OverloadableAttr>());
1339 }
1340
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380
1381   S->AddDecl(D);
1382
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419
1420   return nullptr;
1421 }
1422
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441
1442     F.erase();
1443   }
1444
1445   F.done();
1446 }
1447
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451   // FIXME: The Modules TS is not clear about how friend declarations are
1452   // to be treated. It's not meaningful to have different owning modules for
1453   // linkage in redeclarations of the same entity, so for now allow the
1454   // redeclaration and change the owning modules to match.
1455   if (New->getFriendObjectKind() &&
1456       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457     New->setLocalOwningModule(Old->getOwningModule());
1458     makeMergedDefinitionVisible(New);
1459     return false;
1460   }
1461
1462   Module *NewM = New->getOwningModule();
1463   Module *OldM = Old->getOwningModule();
1464   if (NewM == OldM)
1465     return false;
1466
1467   // FIXME: Check proclaimed-ownership-declarations here too.
1468   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1469   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1470   if (NewIsModuleInterface || OldIsModuleInterface) {
1471     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1472     //   if a declaration of D [...] appears in the purview of a module, all
1473     //   other such declarations shall appear in the purview of the same module
1474     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1475       << New
1476       << NewIsModuleInterface
1477       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1478       << OldIsModuleInterface
1479       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1480     Diag(Old->getLocation(), diag::note_previous_declaration);
1481     New->setInvalidDecl();
1482     return true;
1483   }
1484
1485   return false;
1486 }
1487
1488 static bool isUsingDecl(NamedDecl *D) {
1489   return isa<UsingShadowDecl>(D) ||
1490          isa<UnresolvedUsingTypenameDecl>(D) ||
1491          isa<UnresolvedUsingValueDecl>(D);
1492 }
1493
1494 /// Removes using shadow declarations from the lookup results.
1495 static void RemoveUsingDecls(LookupResult &R) {
1496   LookupResult::Filter F = R.makeFilter();
1497   while (F.hasNext())
1498     if (isUsingDecl(F.next()))
1499       F.erase();
1500
1501   F.done();
1502 }
1503
1504 /// Check for this common pattern:
1505 /// @code
1506 /// class S {
1507 ///   S(const S&); // DO NOT IMPLEMENT
1508 ///   void operator=(const S&); // DO NOT IMPLEMENT
1509 /// };
1510 /// @endcode
1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1512   // FIXME: Should check for private access too but access is set after we get
1513   // the decl here.
1514   if (D->doesThisDeclarationHaveABody())
1515     return false;
1516
1517   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1518     return CD->isCopyConstructor();
1519   return D->isCopyAssignmentOperator();
1520 }
1521
1522 // We need this to handle
1523 //
1524 // typedef struct {
1525 //   void *foo() { return 0; }
1526 // } A;
1527 //
1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1529 // for example. If 'A', foo will have external linkage. If we have '*A',
1530 // foo will have no linkage. Since we can't know until we get to the end
1531 // of the typedef, this function finds out if D might have non-external linkage.
1532 // Callers should verify at the end of the TU if it D has external linkage or
1533 // not.
1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1535   const DeclContext *DC = D->getDeclContext();
1536   while (!DC->isTranslationUnit()) {
1537     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1538       if (!RD->hasNameForLinkage())
1539         return true;
1540     }
1541     DC = DC->getParent();
1542   }
1543
1544   return !D->isExternallyVisible();
1545 }
1546
1547 // FIXME: This needs to be refactored; some other isInMainFile users want
1548 // these semantics.
1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1550   if (S.TUKind != TU_Complete)
1551     return false;
1552   return S.SourceMgr.isInMainFile(Loc);
1553 }
1554
1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1556   assert(D);
1557
1558   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1559     return false;
1560
1561   // Ignore all entities declared within templates, and out-of-line definitions
1562   // of members of class templates.
1563   if (D->getDeclContext()->isDependentContext() ||
1564       D->getLexicalDeclContext()->isDependentContext())
1565     return false;
1566
1567   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1569       return false;
1570     // A non-out-of-line declaration of a member specialization was implicitly
1571     // instantiated; it's the out-of-line declaration that we're interested in.
1572     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1573         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1574       return false;
1575
1576     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1577       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1578         return false;
1579     } else {
1580       // 'static inline' functions are defined in headers; don't warn.
1581       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1582         return false;
1583     }
1584
1585     if (FD->doesThisDeclarationHaveABody() &&
1586         Context.DeclMustBeEmitted(FD))
1587       return false;
1588   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1589     // Constants and utility variables are defined in headers with internal
1590     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1591     // like "inline".)
1592     if (!isMainFileLoc(*this, VD->getLocation()))
1593       return false;
1594
1595     if (Context.DeclMustBeEmitted(VD))
1596       return false;
1597
1598     if (VD->isStaticDataMember() &&
1599         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1600       return false;
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1603         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1604       return false;
1605
1606     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1607       return false;
1608   } else {
1609     return false;
1610   }
1611
1612   // Only warn for unused decls internal to the translation unit.
1613   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1614   // for inline functions defined in the main source file, for instance.
1615   return mightHaveNonExternalLinkage(D);
1616 }
1617
1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1619   if (!D)
1620     return;
1621
1622   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1623     const FunctionDecl *First = FD->getFirstDecl();
1624     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1625       return; // First should already be in the vector.
1626   }
1627
1628   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1629     const VarDecl *First = VD->getFirstDecl();
1630     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1631       return; // First should already be in the vector.
1632   }
1633
1634   if (ShouldWarnIfUnusedFileScopedDecl(D))
1635     UnusedFileScopedDecls.push_back(D);
1636 }
1637
1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1639   if (D->isInvalidDecl())
1640     return false;
1641
1642   bool Referenced = false;
1643   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1644     // For a decomposition declaration, warn if none of the bindings are
1645     // referenced, instead of if the variable itself is referenced (which
1646     // it is, by the bindings' expressions).
1647     for (auto *BD : DD->bindings()) {
1648       if (BD->isReferenced()) {
1649         Referenced = true;
1650         break;
1651       }
1652     }
1653   } else if (!D->getDeclName()) {
1654     return false;
1655   } else if (D->isReferenced() || D->isUsed()) {
1656     Referenced = true;
1657   }
1658
1659   if (Referenced || D->hasAttr<UnusedAttr>() ||
1660       D->hasAttr<ObjCPreciseLifetimeAttr>())
1661     return false;
1662
1663   if (isa<LabelDecl>(D))
1664     return true;
1665
1666   // Except for labels, we only care about unused decls that are local to
1667   // functions.
1668   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1669   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1670     // For dependent types, the diagnostic is deferred.
1671     WithinFunction =
1672         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1673   if (!WithinFunction)
1674     return false;
1675
1676   if (isa<TypedefNameDecl>(D))
1677     return true;
1678
1679   // White-list anything that isn't a local variable.
1680   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1681     return false;
1682
1683   // Types of valid local variables should be complete, so this should succeed.
1684   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1685
1686     // White-list anything with an __attribute__((unused)) type.
1687     const auto *Ty = VD->getType().getTypePtr();
1688
1689     // Only look at the outermost level of typedef.
1690     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1691       if (TT->getDecl()->hasAttr<UnusedAttr>())
1692         return false;
1693     }
1694
1695     // If we failed to complete the type for some reason, or if the type is
1696     // dependent, don't diagnose the variable.
1697     if (Ty->isIncompleteType() || Ty->isDependentType())
1698       return false;
1699
1700     // Look at the element type to ensure that the warning behaviour is
1701     // consistent for both scalars and arrays.
1702     Ty = Ty->getBaseElementTypeUnsafe();
1703
1704     if (const TagType *TT = Ty->getAs<TagType>()) {
1705       const TagDecl *Tag = TT->getDecl();
1706       if (Tag->hasAttr<UnusedAttr>())
1707         return false;
1708
1709       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1710         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1711           return false;
1712
1713         if (const Expr *Init = VD->getInit()) {
1714           if (const ExprWithCleanups *Cleanups =
1715                   dyn_cast<ExprWithCleanups>(Init))
1716             Init = Cleanups->getSubExpr();
1717           const CXXConstructExpr *Construct =
1718             dyn_cast<CXXConstructExpr>(Init);
1719           if (Construct && !Construct->isElidable()) {
1720             CXXConstructorDecl *CD = Construct->getConstructor();
1721             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1722                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1723               return false;
1724           }
1725         }
1726       }
1727     }
1728
1729     // TODO: __attribute__((unused)) templates?
1730   }
1731
1732   return true;
1733 }
1734
1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1736                                      FixItHint &Hint) {
1737   if (isa<LabelDecl>(D)) {
1738     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1739                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1740     if (AfterColon.isInvalid())
1741       return;
1742     Hint = FixItHint::CreateRemoval(CharSourceRange::
1743                                     getCharRange(D->getLocStart(), AfterColon));
1744   }
1745 }
1746
1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1748   if (D->getTypeForDecl()->isDependentType())
1749     return;
1750
1751   for (auto *TmpD : D->decls()) {
1752     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1753       DiagnoseUnusedDecl(T);
1754     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1755       DiagnoseUnusedNestedTypedefs(R);
1756   }
1757 }
1758
1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1760 /// unless they are marked attr(unused).
1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1762   if (!ShouldDiagnoseUnusedDecl(D))
1763     return;
1764
1765   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1766     // typedefs can be referenced later on, so the diagnostics are emitted
1767     // at end-of-translation-unit.
1768     UnusedLocalTypedefNameCandidates.insert(TD);
1769     return;
1770   }
1771
1772   FixItHint Hint;
1773   GenerateFixForUnusedDecl(D, Context, Hint);
1774
1775   unsigned DiagID;
1776   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1777     DiagID = diag::warn_unused_exception_param;
1778   else if (isa<LabelDecl>(D))
1779     DiagID = diag::warn_unused_label;
1780   else
1781     DiagID = diag::warn_unused_variable;
1782
1783   Diag(D->getLocation(), DiagID) << D << Hint;
1784 }
1785
1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1787   // Verify that we have no forward references left.  If so, there was a goto
1788   // or address of a label taken, but no definition of it.  Label fwd
1789   // definitions are indicated with a null substmt which is also not a resolved
1790   // MS inline assembly label name.
1791   bool Diagnose = false;
1792   if (L->isMSAsmLabel())
1793     Diagnose = !L->isResolvedMSAsmLabel();
1794   else
1795     Diagnose = L->getStmt() == nullptr;
1796   if (Diagnose)
1797     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1798 }
1799
1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1801   S->mergeNRVOIntoParent();
1802
1803   if (S->decl_empty()) return;
1804   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1805          "Scope shouldn't contain decls!");
1806
1807   for (auto *TmpD : S->decls()) {
1808     assert(TmpD && "This decl didn't get pushed??");
1809
1810     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1811     NamedDecl *D = cast<NamedDecl>(TmpD);
1812
1813     // Diagnose unused variables in this scope.
1814     if (!S->hasUnrecoverableErrorOccurred()) {
1815       DiagnoseUnusedDecl(D);
1816       if (const auto *RD = dyn_cast<RecordDecl>(D))
1817         DiagnoseUnusedNestedTypedefs(RD);
1818     }
1819
1820     if (!D->getDeclName()) continue;
1821
1822     // If this was a forward reference to a label, verify it was defined.
1823     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1824       CheckPoppedLabel(LD, *this);
1825
1826     // Remove this name from our lexical scope, and warn on it if we haven't
1827     // already.
1828     IdResolver.RemoveDecl(D);
1829     auto ShadowI = ShadowingDecls.find(D);
1830     if (ShadowI != ShadowingDecls.end()) {
1831       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1832         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1833             << D << FD << FD->getParent();
1834         Diag(FD->getLocation(), diag::note_previous_declaration);
1835       }
1836       ShadowingDecls.erase(ShadowI);
1837     }
1838   }
1839 }
1840
1841 /// Look for an Objective-C class in the translation unit.
1842 ///
1843 /// \param Id The name of the Objective-C class we're looking for. If
1844 /// typo-correction fixes this name, the Id will be updated
1845 /// to the fixed name.
1846 ///
1847 /// \param IdLoc The location of the name in the translation unit.
1848 ///
1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1850 /// if there is no class with the given name.
1851 ///
1852 /// \returns The declaration of the named Objective-C class, or NULL if the
1853 /// class could not be found.
1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1855                                               SourceLocation IdLoc,
1856                                               bool DoTypoCorrection) {
1857   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1858   // creation from this context.
1859   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1860
1861   if (!IDecl && DoTypoCorrection) {
1862     // Perform typo correction at the given location, but only if we
1863     // find an Objective-C class name.
1864     if (TypoCorrection C = CorrectTypo(
1865             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1866             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1867             CTK_ErrorRecovery)) {
1868       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1869       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1870       Id = IDecl->getIdentifier();
1871     }
1872   }
1873   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1874   // This routine must always return a class definition, if any.
1875   if (Def && Def->getDefinition())
1876       Def = Def->getDefinition();
1877   return Def;
1878 }
1879
1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1881 /// from S, where a non-field would be declared. This routine copes
1882 /// with the difference between C and C++ scoping rules in structs and
1883 /// unions. For example, the following code is well-formed in C but
1884 /// ill-formed in C++:
1885 /// @code
1886 /// struct S6 {
1887 ///   enum { BAR } e;
1888 /// };
1889 ///
1890 /// void test_S6() {
1891 ///   struct S6 a;
1892 ///   a.e = BAR;
1893 /// }
1894 /// @endcode
1895 /// For the declaration of BAR, this routine will return a different
1896 /// scope. The scope S will be the scope of the unnamed enumeration
1897 /// within S6. In C++, this routine will return the scope associated
1898 /// with S6, because the enumeration's scope is a transparent
1899 /// context but structures can contain non-field names. In C, this
1900 /// routine will return the translation unit scope, since the
1901 /// enumeration's scope is a transparent context and structures cannot
1902 /// contain non-field names.
1903 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1904   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1905          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1906          (S->isClassScope() && !getLangOpts().CPlusPlus))
1907     S = S->getParent();
1908   return S;
1909 }
1910
1911 /// Looks up the declaration of "struct objc_super" and
1912 /// saves it for later use in building builtin declaration of
1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1914 /// pre-existing declaration exists no action takes place.
1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1916                                         IdentifierInfo *II) {
1917   if (!II->isStr("objc_msgSendSuper"))
1918     return;
1919   ASTContext &Context = ThisSema.Context;
1920
1921   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1922                       SourceLocation(), Sema::LookupTagName);
1923   ThisSema.LookupName(Result, S);
1924   if (Result.getResultKind() == LookupResult::Found)
1925     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1926       Context.setObjCSuperType(Context.getTagDeclType(TD));
1927 }
1928
1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1930   switch (Error) {
1931   case ASTContext::GE_None:
1932     return "";
1933   case ASTContext::GE_Missing_stdio:
1934     return "stdio.h";
1935   case ASTContext::GE_Missing_setjmp:
1936     return "setjmp.h";
1937   case ASTContext::GE_Missing_ucontext:
1938     return "ucontext.h";
1939   }
1940   llvm_unreachable("unhandled error kind");
1941 }
1942
1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1944 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1945 /// if we're creating this built-in in anticipation of redeclaring the
1946 /// built-in.
1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1948                                      Scope *S, bool ForRedeclaration,
1949                                      SourceLocation Loc) {
1950   LookupPredefedObjCSuperType(*this, S, II);
1951
1952   ASTContext::GetBuiltinTypeError Error;
1953   QualType R = Context.GetBuiltinType(ID, Error);
1954   if (Error) {
1955     if (ForRedeclaration)
1956       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1957           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1958     return nullptr;
1959   }
1960
1961   if (!ForRedeclaration &&
1962       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1963        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1964     Diag(Loc, diag::ext_implicit_lib_function_decl)
1965         << Context.BuiltinInfo.getName(ID) << R;
1966     if (Context.BuiltinInfo.getHeaderName(ID) &&
1967         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1968       Diag(Loc, diag::note_include_header_or_declare)
1969           << Context.BuiltinInfo.getHeaderName(ID)
1970           << Context.BuiltinInfo.getName(ID);
1971   }
1972
1973   if (R.isNull())
1974     return nullptr;
1975
1976   DeclContext *Parent = Context.getTranslationUnitDecl();
1977   if (getLangOpts().CPlusPlus) {
1978     LinkageSpecDecl *CLinkageDecl =
1979         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1980                                 LinkageSpecDecl::lang_c, false);
1981     CLinkageDecl->setImplicit();
1982     Parent->addDecl(CLinkageDecl);
1983     Parent = CLinkageDecl;
1984   }
1985
1986   FunctionDecl *New = FunctionDecl::Create(Context,
1987                                            Parent,
1988                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1989                                            SC_Extern,
1990                                            false,
1991                                            R->isFunctionProtoType());
1992   New->setImplicit();
1993
1994   // Create Decl objects for each parameter, adding them to the
1995   // FunctionDecl.
1996   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1997     SmallVector<ParmVarDecl*, 16> Params;
1998     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1999       ParmVarDecl *parm =
2000           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2001                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2002                               SC_None, nullptr);
2003       parm->setScopeInfo(0, i);
2004       Params.push_back(parm);
2005     }
2006     New->setParams(Params);
2007   }
2008
2009   AddKnownFunctionAttributes(New);
2010   RegisterLocallyScopedExternCDecl(New, S);
2011
2012   // TUScope is the translation-unit scope to insert this function into.
2013   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2014   // relate Scopes to DeclContexts, and probably eliminate CurContext
2015   // entirely, but we're not there yet.
2016   DeclContext *SavedContext = CurContext;
2017   CurContext = Parent;
2018   PushOnScopeChains(New, TUScope);
2019   CurContext = SavedContext;
2020   return New;
2021 }
2022
2023 /// Typedef declarations don't have linkage, but they still denote the same
2024 /// entity if their types are the same.
2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2026 /// isSameEntity.
2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2028                                                      TypedefNameDecl *Decl,
2029                                                      LookupResult &Previous) {
2030   // This is only interesting when modules are enabled.
2031   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2032     return;
2033
2034   // Empty sets are uninteresting.
2035   if (Previous.empty())
2036     return;
2037
2038   LookupResult::Filter Filter = Previous.makeFilter();
2039   while (Filter.hasNext()) {
2040     NamedDecl *Old = Filter.next();
2041
2042     // Non-hidden declarations are never ignored.
2043     if (S.isVisible(Old))
2044       continue;
2045
2046     // Declarations of the same entity are not ignored, even if they have
2047     // different linkages.
2048     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2049       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2050                                 Decl->getUnderlyingType()))
2051         continue;
2052
2053       // If both declarations give a tag declaration a typedef name for linkage
2054       // purposes, then they declare the same entity.
2055       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2056           Decl->getAnonDeclWithTypedefName())
2057         continue;
2058     }
2059
2060     Filter.erase();
2061   }
2062
2063   Filter.done();
2064 }
2065
2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2067   QualType OldType;
2068   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2069     OldType = OldTypedef->getUnderlyingType();
2070   else
2071     OldType = Context.getTypeDeclType(Old);
2072   QualType NewType = New->getUnderlyingType();
2073
2074   if (NewType->isVariablyModifiedType()) {
2075     // Must not redefine a typedef with a variably-modified type.
2076     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2077     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2078       << Kind << NewType;
2079     if (Old->getLocation().isValid())
2080       notePreviousDefinition(Old, New->getLocation());
2081     New->setInvalidDecl();
2082     return true;
2083   }
2084
2085   if (OldType != NewType &&
2086       !OldType->isDependentType() &&
2087       !NewType->isDependentType() &&
2088       !Context.hasSameType(OldType, NewType)) {
2089     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2090     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2091       << Kind << NewType << OldType;
2092     if (Old->getLocation().isValid())
2093       notePreviousDefinition(Old, New->getLocation());
2094     New->setInvalidDecl();
2095     return true;
2096   }
2097   return false;
2098 }
2099
2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2101 /// same name and scope as a previous declaration 'Old'.  Figure out
2102 /// how to resolve this situation, merging decls or emitting
2103 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2104 ///
2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2106                                 LookupResult &OldDecls) {
2107   // If the new decl is known invalid already, don't bother doing any
2108   // merging checks.
2109   if (New->isInvalidDecl()) return;
2110
2111   // Allow multiple definitions for ObjC built-in typedefs.
2112   // FIXME: Verify the underlying types are equivalent!
2113   if (getLangOpts().ObjC1) {
2114     const IdentifierInfo *TypeID = New->getIdentifier();
2115     switch (TypeID->getLength()) {
2116     default: break;
2117     case 2:
2118       {
2119         if (!TypeID->isStr("id"))
2120           break;
2121         QualType T = New->getUnderlyingType();
2122         if (!T->isPointerType())
2123           break;
2124         if (!T->isVoidPointerType()) {
2125           QualType PT = T->getAs<PointerType>()->getPointeeType();
2126           if (!PT->isStructureType())
2127             break;
2128         }
2129         Context.setObjCIdRedefinitionType(T);
2130         // Install the built-in type for 'id', ignoring the current definition.
2131         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2132         return;
2133       }
2134     case 5:
2135       if (!TypeID->isStr("Class"))
2136         break;
2137       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2138       // Install the built-in type for 'Class', ignoring the current definition.
2139       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2140       return;
2141     case 3:
2142       if (!TypeID->isStr("SEL"))
2143         break;
2144       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2145       // Install the built-in type for 'SEL', ignoring the current definition.
2146       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2147       return;
2148     }
2149     // Fall through - the typedef name was not a builtin type.
2150   }
2151
2152   // Verify the old decl was also a type.
2153   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2154   if (!Old) {
2155     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2156       << New->getDeclName();
2157
2158     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2159     if (OldD->getLocation().isValid())
2160       notePreviousDefinition(OldD, New->getLocation());
2161
2162     return New->setInvalidDecl();
2163   }
2164
2165   // If the old declaration is invalid, just give up here.
2166   if (Old->isInvalidDecl())
2167     return New->setInvalidDecl();
2168
2169   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2170     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2171     auto *NewTag = New->getAnonDeclWithTypedefName();
2172     NamedDecl *Hidden = nullptr;
2173     if (OldTag && NewTag &&
2174         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2175         !hasVisibleDefinition(OldTag, &Hidden)) {
2176       // There is a definition of this tag, but it is not visible. Use it
2177       // instead of our tag.
2178       New->setTypeForDecl(OldTD->getTypeForDecl());
2179       if (OldTD->isModed())
2180         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2181                                     OldTD->getUnderlyingType());
2182       else
2183         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2184
2185       // Make the old tag definition visible.
2186       makeMergedDefinitionVisible(Hidden);
2187
2188       // If this was an unscoped enumeration, yank all of its enumerators
2189       // out of the scope.
2190       if (isa<EnumDecl>(NewTag)) {
2191         Scope *EnumScope = getNonFieldDeclScope(S);
2192         for (auto *D : NewTag->decls()) {
2193           auto *ED = cast<EnumConstantDecl>(D);
2194           assert(EnumScope->isDeclScope(ED));
2195           EnumScope->RemoveDecl(ED);
2196           IdResolver.RemoveDecl(ED);
2197           ED->getLexicalDeclContext()->removeDecl(ED);
2198         }
2199       }
2200     }
2201   }
2202
2203   // If the typedef types are not identical, reject them in all languages and
2204   // with any extensions enabled.
2205   if (isIncompatibleTypedef(Old, New))
2206     return;
2207
2208   // The types match.  Link up the redeclaration chain and merge attributes if
2209   // the old declaration was a typedef.
2210   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2211     New->setPreviousDecl(Typedef);
2212     mergeDeclAttributes(New, Old);
2213   }
2214
2215   if (getLangOpts().MicrosoftExt)
2216     return;
2217
2218   if (getLangOpts().CPlusPlus) {
2219     // C++ [dcl.typedef]p2:
2220     //   In a given non-class scope, a typedef specifier can be used to
2221     //   redefine the name of any type declared in that scope to refer
2222     //   to the type to which it already refers.
2223     if (!isa<CXXRecordDecl>(CurContext))
2224       return;
2225
2226     // C++0x [dcl.typedef]p4:
2227     //   In a given class scope, a typedef specifier can be used to redefine
2228     //   any class-name declared in that scope that is not also a typedef-name
2229     //   to refer to the type to which it already refers.
2230     //
2231     // This wording came in via DR424, which was a correction to the
2232     // wording in DR56, which accidentally banned code like:
2233     //
2234     //   struct S {
2235     //     typedef struct A { } A;
2236     //   };
2237     //
2238     // in the C++03 standard. We implement the C++0x semantics, which
2239     // allow the above but disallow
2240     //
2241     //   struct S {
2242     //     typedef int I;
2243     //     typedef int I;
2244     //   };
2245     //
2246     // since that was the intent of DR56.
2247     if (!isa<TypedefNameDecl>(Old))
2248       return;
2249
2250     Diag(New->getLocation(), diag::err_redefinition)
2251       << New->getDeclName();
2252     notePreviousDefinition(Old, New->getLocation());
2253     return New->setInvalidDecl();
2254   }
2255
2256   // Modules always permit redefinition of typedefs, as does C11.
2257   if (getLangOpts().Modules || getLangOpts().C11)
2258     return;
2259
2260   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2261   // is normally mapped to an error, but can be controlled with
2262   // -Wtypedef-redefinition.  If either the original or the redefinition is
2263   // in a system header, don't emit this for compatibility with GCC.
2264   if (getDiagnostics().getSuppressSystemWarnings() &&
2265       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2266       (Old->isImplicit() ||
2267        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2268        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2269     return;
2270
2271   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2272     << New->getDeclName();
2273   notePreviousDefinition(Old, New->getLocation());
2274 }
2275
2276 /// DeclhasAttr - returns true if decl Declaration already has the target
2277 /// attribute.
2278 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2279   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2280   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2281   for (const auto *i : D->attrs())
2282     if (i->getKind() == A->getKind()) {
2283       if (Ann) {
2284         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2285           return true;
2286         continue;
2287       }
2288       // FIXME: Don't hardcode this check
2289       if (OA && isa<OwnershipAttr>(i))
2290         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2291       return true;
2292     }
2293
2294   return false;
2295 }
2296
2297 static bool isAttributeTargetADefinition(Decl *D) {
2298   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2299     return VD->isThisDeclarationADefinition();
2300   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2301     return TD->isCompleteDefinition() || TD->isBeingDefined();
2302   return true;
2303 }
2304
2305 /// Merge alignment attributes from \p Old to \p New, taking into account the
2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2307 ///
2308 /// \return \c true if any attributes were added to \p New.
2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2310   // Look for alignas attributes on Old, and pick out whichever attribute
2311   // specifies the strictest alignment requirement.
2312   AlignedAttr *OldAlignasAttr = nullptr;
2313   AlignedAttr *OldStrictestAlignAttr = nullptr;
2314   unsigned OldAlign = 0;
2315   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2316     // FIXME: We have no way of representing inherited dependent alignments
2317     // in a case like:
2318     //   template<int A, int B> struct alignas(A) X;
2319     //   template<int A, int B> struct alignas(B) X {};
2320     // For now, we just ignore any alignas attributes which are not on the
2321     // definition in such a case.
2322     if (I->isAlignmentDependent())
2323       return false;
2324
2325     if (I->isAlignas())
2326       OldAlignasAttr = I;
2327
2328     unsigned Align = I->getAlignment(S.Context);
2329     if (Align > OldAlign) {
2330       OldAlign = Align;
2331       OldStrictestAlignAttr = I;
2332     }
2333   }
2334
2335   // Look for alignas attributes on New.
2336   AlignedAttr *NewAlignasAttr = nullptr;
2337   unsigned NewAlign = 0;
2338   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2339     if (I->isAlignmentDependent())
2340       return false;
2341
2342     if (I->isAlignas())
2343       NewAlignasAttr = I;
2344
2345     unsigned Align = I->getAlignment(S.Context);
2346     if (Align > NewAlign)
2347       NewAlign = Align;
2348   }
2349
2350   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2351     // Both declarations have 'alignas' attributes. We require them to match.
2352     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2353     // fall short. (If two declarations both have alignas, they must both match
2354     // every definition, and so must match each other if there is a definition.)
2355
2356     // If either declaration only contains 'alignas(0)' specifiers, then it
2357     // specifies the natural alignment for the type.
2358     if (OldAlign == 0 || NewAlign == 0) {
2359       QualType Ty;
2360       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2361         Ty = VD->getType();
2362       else
2363         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2364
2365       if (OldAlign == 0)
2366         OldAlign = S.Context.getTypeAlign(Ty);
2367       if (NewAlign == 0)
2368         NewAlign = S.Context.getTypeAlign(Ty);
2369     }
2370
2371     if (OldAlign != NewAlign) {
2372       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2373         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2374         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2375       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2376     }
2377   }
2378
2379   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2380     // C++11 [dcl.align]p6:
2381     //   if any declaration of an entity has an alignment-specifier,
2382     //   every defining declaration of that entity shall specify an
2383     //   equivalent alignment.
2384     // C11 6.7.5/7:
2385     //   If the definition of an object does not have an alignment
2386     //   specifier, any other declaration of that object shall also
2387     //   have no alignment specifier.
2388     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2389       << OldAlignasAttr;
2390     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2391       << OldAlignasAttr;
2392   }
2393
2394   bool AnyAdded = false;
2395
2396   // Ensure we have an attribute representing the strictest alignment.
2397   if (OldAlign > NewAlign) {
2398     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2399     Clone->setInherited(true);
2400     New->addAttr(Clone);
2401     AnyAdded = true;
2402   }
2403
2404   // Ensure we have an alignas attribute if the old declaration had one.
2405   if (OldAlignasAttr && !NewAlignasAttr &&
2406       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2407     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2408     Clone->setInherited(true);
2409     New->addAttr(Clone);
2410     AnyAdded = true;
2411   }
2412
2413   return AnyAdded;
2414 }
2415
2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2417                                const InheritableAttr *Attr,
2418                                Sema::AvailabilityMergeKind AMK) {
2419   // This function copies an attribute Attr from a previous declaration to the
2420   // new declaration D if the new declaration doesn't itself have that attribute
2421   // yet or if that attribute allows duplicates.
2422   // If you're adding a new attribute that requires logic different from
2423   // "use explicit attribute on decl if present, else use attribute from
2424   // previous decl", for example if the attribute needs to be consistent
2425   // between redeclarations, you need to call a custom merge function here.
2426   InheritableAttr *NewAttr = nullptr;
2427   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2428   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2429     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2430                                       AA->isImplicit(), AA->getIntroduced(),
2431                                       AA->getDeprecated(),
2432                                       AA->getObsoleted(), AA->getUnavailable(),
2433                                       AA->getMessage(), AA->getStrict(),
2434                                       AA->getReplacement(), AMK,
2435                                       AttrSpellingListIndex);
2436   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2437     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2438                                     AttrSpellingListIndex);
2439   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2440     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441                                         AttrSpellingListIndex);
2442   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2443     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2444                                    AttrSpellingListIndex);
2445   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2446     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2447                                    AttrSpellingListIndex);
2448   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2449     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2450                                 FA->getFormatIdx(), FA->getFirstArg(),
2451                                 AttrSpellingListIndex);
2452   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2453     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2454                                  AttrSpellingListIndex);
2455   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2456     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2457                                  AttrSpellingListIndex);
2458   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460                                        AttrSpellingListIndex,
2461                                        IA->getSemanticSpelling());
2462   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464                                       &S.Context.Idents.get(AA->getSpelling()),
2465                                       AttrSpellingListIndex);
2466   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468             isa<CUDAGlobalAttr>(Attr))) {
2469     // CUDA target attributes are part of function signature for
2470     // overloading purposes and must not be merged.
2471     return false;
2472   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477     NewAttr = S.mergeInternalLinkageAttr(
2478         D, InternalLinkageA->getRange(),
2479         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480         AttrSpellingListIndex);
2481   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483                                 &S.Context.Idents.get(CommonA->getSpelling()),
2484                                 AttrSpellingListIndex);
2485   else if (isa<AlignedAttr>(Attr))
2486     // AlignedAttrs are handled separately, because we need to handle all
2487     // such attributes on a declaration at the same time.
2488     NewAttr = nullptr;
2489   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490            (AMK == Sema::AMK_Override ||
2491             AMK == Sema::AMK_ProtocolImplementation))
2492     NewAttr = nullptr;
2493   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2495                               UA->getGuid());
2496   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2498
2499   if (NewAttr) {
2500     NewAttr->setInherited(true);
2501     D->addAttr(NewAttr);
2502     if (isa<MSInheritanceAttr>(NewAttr))
2503       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2504     return true;
2505   }
2506
2507   return false;
2508 }
2509
2510 static const NamedDecl *getDefinition(const Decl *D) {
2511   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512     return TD->getDefinition();
2513   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514     const VarDecl *Def = VD->getDefinition();
2515     if (Def)
2516       return Def;
2517     return VD->getActingDefinition();
2518   }
2519   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520     return FD->getDefinition();
2521   return nullptr;
2522 }
2523
2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525   for (const auto *Attribute : D->attrs())
2526     if (Attribute->getKind() == Kind)
2527       return true;
2528   return false;
2529 }
2530
2531 /// checkNewAttributesAfterDef - If we already have a definition, check that
2532 /// there are no new attributes in this declaration.
2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534   if (!New->hasAttrs())
2535     return;
2536
2537   const NamedDecl *Def = getDefinition(Old);
2538   if (!Def || Def == New)
2539     return;
2540
2541   AttrVec &NewAttributes = New->getAttrs();
2542   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543     const Attr *NewAttribute = NewAttributes[I];
2544
2545     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547         Sema::SkipBodyInfo SkipBody;
2548         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2549
2550         // If we're skipping this definition, drop the "alias" attribute.
2551         if (SkipBody.ShouldSkip) {
2552           NewAttributes.erase(NewAttributes.begin() + I);
2553           --E;
2554           continue;
2555         }
2556       } else {
2557         VarDecl *VD = cast<VarDecl>(New);
2558         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559                                 VarDecl::TentativeDefinition
2560                             ? diag::err_alias_after_tentative
2561                             : diag::err_redefinition;
2562         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563         if (Diag == diag::err_redefinition)
2564           S.notePreviousDefinition(Def, VD->getLocation());
2565         else
2566           S.Diag(Def->getLocation(), diag::note_previous_definition);
2567         VD->setInvalidDecl();
2568       }
2569       ++I;
2570       continue;
2571     }
2572
2573     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574       // Tentative definitions are only interesting for the alias check above.
2575       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2576         ++I;
2577         continue;
2578       }
2579     }
2580
2581     if (hasAttribute(Def, NewAttribute->getKind())) {
2582       ++I;
2583       continue; // regular attr merging will take care of validating this.
2584     }
2585
2586     if (isa<C11NoReturnAttr>(NewAttribute)) {
2587       // C's _Noreturn is allowed to be added to a function after it is defined.
2588       ++I;
2589       continue;
2590     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591       if (AA->isAlignas()) {
2592         // C++11 [dcl.align]p6:
2593         //   if any declaration of an entity has an alignment-specifier,
2594         //   every defining declaration of that entity shall specify an
2595         //   equivalent alignment.
2596         // C11 6.7.5/7:
2597         //   If the definition of an object does not have an alignment
2598         //   specifier, any other declaration of that object shall also
2599         //   have no alignment specifier.
2600         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2601           << AA;
2602         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2603           << AA;
2604         NewAttributes.erase(NewAttributes.begin() + I);
2605         --E;
2606         continue;
2607       }
2608     }
2609
2610     S.Diag(NewAttribute->getLocation(),
2611            diag::warn_attribute_precede_definition);
2612     S.Diag(Def->getLocation(), diag::note_previous_definition);
2613     NewAttributes.erase(NewAttributes.begin() + I);
2614     --E;
2615   }
2616 }
2617
2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620                                AvailabilityMergeKind AMK) {
2621   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622     UsedAttr *NewAttr = OldAttr->clone(Context);
2623     NewAttr->setInherited(true);
2624     New->addAttr(NewAttr);
2625   }
2626
2627   if (!Old->hasAttrs() && !New->hasAttrs())
2628     return;
2629
2630   // Attributes declared post-definition are currently ignored.
2631   checkNewAttributesAfterDef(*this, New, Old);
2632
2633   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635       if (OldA->getLabel() != NewA->getLabel()) {
2636         // This redeclaration changes __asm__ label.
2637         Diag(New->getLocation(), diag::err_different_asm_label);
2638         Diag(OldA->getLocation(), diag::note_previous_declaration);
2639       }
2640     } else if (Old->isUsed()) {
2641       // This redeclaration adds an __asm__ label to a declaration that has
2642       // already been ODR-used.
2643       Diag(New->getLocation(), diag::err_late_asm_label_name)
2644         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2645     }
2646   }
2647
2648   // Re-declaration cannot add abi_tag's.
2649   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653                       NewTag) == OldAbiTagAttr->tags_end()) {
2654           Diag(NewAbiTagAttr->getLocation(),
2655                diag::err_new_abi_tag_on_redeclaration)
2656               << NewTag;
2657           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2658         }
2659       }
2660     } else {
2661       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662       Diag(Old->getLocation(), diag::note_previous_declaration);
2663     }
2664   }
2665
2666   // This redeclaration adds a section attribute.
2667   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668     if (auto *VD = dyn_cast<VarDecl>(New)) {
2669       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671         Diag(Old->getLocation(), diag::note_previous_declaration);
2672       }
2673     }
2674   }
2675
2676   // Redeclaration adds code-seg attribute.
2677   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2678   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2679       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2680     Diag(New->getLocation(), diag::warn_mismatched_section)
2681          << 0 /*codeseg*/;
2682     Diag(Old->getLocation(), diag::note_previous_declaration);
2683   }
2684
2685   if (!Old->hasAttrs())
2686     return;
2687
2688   bool foundAny = New->hasAttrs();
2689
2690   // Ensure that any moving of objects within the allocated map is done before
2691   // we process them.
2692   if (!foundAny) New->setAttrs(AttrVec());
2693
2694   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2695     // Ignore deprecated/unavailable/availability attributes if requested.
2696     AvailabilityMergeKind LocalAMK = AMK_None;
2697     if (isa<DeprecatedAttr>(I) ||
2698         isa<UnavailableAttr>(I) ||
2699         isa<AvailabilityAttr>(I)) {
2700       switch (AMK) {
2701       case AMK_None:
2702         continue;
2703
2704       case AMK_Redeclaration:
2705       case AMK_Override:
2706       case AMK_ProtocolImplementation:
2707         LocalAMK = AMK;
2708         break;
2709       }
2710     }
2711
2712     // Already handled.
2713     if (isa<UsedAttr>(I))
2714       continue;
2715
2716     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2717       foundAny = true;
2718   }
2719
2720   if (mergeAlignedAttrs(*this, New, Old))
2721     foundAny = true;
2722
2723   if (!foundAny) New->dropAttrs();
2724 }
2725
2726 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2727 /// to the new one.
2728 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2729                                      const ParmVarDecl *oldDecl,
2730                                      Sema &S) {
2731   // C++11 [dcl.attr.depend]p2:
2732   //   The first declaration of a function shall specify the
2733   //   carries_dependency attribute for its declarator-id if any declaration
2734   //   of the function specifies the carries_dependency attribute.
2735   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2736   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2737     S.Diag(CDA->getLocation(),
2738            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2739     // Find the first declaration of the parameter.
2740     // FIXME: Should we build redeclaration chains for function parameters?
2741     const FunctionDecl *FirstFD =
2742       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2743     const ParmVarDecl *FirstVD =
2744       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2745     S.Diag(FirstVD->getLocation(),
2746            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2747   }
2748
2749   if (!oldDecl->hasAttrs())
2750     return;
2751
2752   bool foundAny = newDecl->hasAttrs();
2753
2754   // Ensure that any moving of objects within the allocated map is
2755   // done before we process them.
2756   if (!foundAny) newDecl->setAttrs(AttrVec());
2757
2758   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2759     if (!DeclHasAttr(newDecl, I)) {
2760       InheritableAttr *newAttr =
2761         cast<InheritableParamAttr>(I->clone(S.Context));
2762       newAttr->setInherited(true);
2763       newDecl->addAttr(newAttr);
2764       foundAny = true;
2765     }
2766   }
2767
2768   if (!foundAny) newDecl->dropAttrs();
2769 }
2770
2771 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2772                                 const ParmVarDecl *OldParam,
2773                                 Sema &S) {
2774   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2775     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2776       if (*Oldnullability != *Newnullability) {
2777         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2778           << DiagNullabilityKind(
2779                *Newnullability,
2780                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2781                 != 0))
2782           << DiagNullabilityKind(
2783                *Oldnullability,
2784                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2785                 != 0));
2786         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2787       }
2788     } else {
2789       QualType NewT = NewParam->getType();
2790       NewT = S.Context.getAttributedType(
2791                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2792                          NewT, NewT);
2793       NewParam->setType(NewT);
2794     }
2795   }
2796 }
2797
2798 namespace {
2799
2800 /// Used in MergeFunctionDecl to keep track of function parameters in
2801 /// C.
2802 struct GNUCompatibleParamWarning {
2803   ParmVarDecl *OldParm;
2804   ParmVarDecl *NewParm;
2805   QualType PromotedType;
2806 };
2807
2808 } // end anonymous namespace
2809
2810 /// getSpecialMember - get the special member enum for a method.
2811 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2812   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2813     if (Ctor->isDefaultConstructor())
2814       return Sema::CXXDefaultConstructor;
2815
2816     if (Ctor->isCopyConstructor())
2817       return Sema::CXXCopyConstructor;
2818
2819     if (Ctor->isMoveConstructor())
2820       return Sema::CXXMoveConstructor;
2821   } else if (isa<CXXDestructorDecl>(MD)) {
2822     return Sema::CXXDestructor;
2823   } else if (MD->isCopyAssignmentOperator()) {
2824     return Sema::CXXCopyAssignment;
2825   } else if (MD->isMoveAssignmentOperator()) {
2826     return Sema::CXXMoveAssignment;
2827   }
2828
2829   return Sema::CXXInvalid;
2830 }
2831
2832 // Determine whether the previous declaration was a definition, implicit
2833 // declaration, or a declaration.
2834 template <typename T>
2835 static std::pair<diag::kind, SourceLocation>
2836 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2837   diag::kind PrevDiag;
2838   SourceLocation OldLocation = Old->getLocation();
2839   if (Old->isThisDeclarationADefinition())
2840     PrevDiag = diag::note_previous_definition;
2841   else if (Old->isImplicit()) {
2842     PrevDiag = diag::note_previous_implicit_declaration;
2843     if (OldLocation.isInvalid())
2844       OldLocation = New->getLocation();
2845   } else
2846     PrevDiag = diag::note_previous_declaration;
2847   return std::make_pair(PrevDiag, OldLocation);
2848 }
2849
2850 /// canRedefineFunction - checks if a function can be redefined. Currently,
2851 /// only extern inline functions can be redefined, and even then only in
2852 /// GNU89 mode.
2853 static bool canRedefineFunction(const FunctionDecl *FD,
2854                                 const LangOptions& LangOpts) {
2855   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2856           !LangOpts.CPlusPlus &&
2857           FD->isInlineSpecified() &&
2858           FD->getStorageClass() == SC_Extern);
2859 }
2860
2861 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2862   const AttributedType *AT = T->getAs<AttributedType>();
2863   while (AT && !AT->isCallingConv())
2864     AT = AT->getModifiedType()->getAs<AttributedType>();
2865   return AT;
2866 }
2867
2868 template <typename T>
2869 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2870   const DeclContext *DC = Old->getDeclContext();
2871   if (DC->isRecord())
2872     return false;
2873
2874   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2875   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2876     return true;
2877   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2878     return true;
2879   return false;
2880 }
2881
2882 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2883 static bool isExternC(VarTemplateDecl *) { return false; }
2884
2885 /// Check whether a redeclaration of an entity introduced by a
2886 /// using-declaration is valid, given that we know it's not an overload
2887 /// (nor a hidden tag declaration).
2888 template<typename ExpectedDecl>
2889 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2890                                    ExpectedDecl *New) {
2891   // C++11 [basic.scope.declarative]p4:
2892   //   Given a set of declarations in a single declarative region, each of
2893   //   which specifies the same unqualified name,
2894   //   -- they shall all refer to the same entity, or all refer to functions
2895   //      and function templates; or
2896   //   -- exactly one declaration shall declare a class name or enumeration
2897   //      name that is not a typedef name and the other declarations shall all
2898   //      refer to the same variable or enumerator, or all refer to functions
2899   //      and function templates; in this case the class name or enumeration
2900   //      name is hidden (3.3.10).
2901
2902   // C++11 [namespace.udecl]p14:
2903   //   If a function declaration in namespace scope or block scope has the
2904   //   same name and the same parameter-type-list as a function introduced
2905   //   by a using-declaration, and the declarations do not declare the same
2906   //   function, the program is ill-formed.
2907
2908   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2909   if (Old &&
2910       !Old->getDeclContext()->getRedeclContext()->Equals(
2911           New->getDeclContext()->getRedeclContext()) &&
2912       !(isExternC(Old) && isExternC(New)))
2913     Old = nullptr;
2914
2915   if (!Old) {
2916     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2917     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2918     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2919     return true;
2920   }
2921   return false;
2922 }
2923
2924 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2925                                             const FunctionDecl *B) {
2926   assert(A->getNumParams() == B->getNumParams());
2927
2928   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2929     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2930     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2931     if (AttrA == AttrB)
2932       return true;
2933     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2934   };
2935
2936   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2937 }
2938
2939 /// If necessary, adjust the semantic declaration context for a qualified
2940 /// declaration to name the correct inline namespace within the qualifier.
2941 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2942                                                DeclaratorDecl *OldD) {
2943   // The only case where we need to update the DeclContext is when
2944   // redeclaration lookup for a qualified name finds a declaration
2945   // in an inline namespace within the context named by the qualifier:
2946   //
2947   //   inline namespace N { int f(); }
2948   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2949   //
2950   // For unqualified declarations, the semantic context *can* change
2951   // along the redeclaration chain (for local extern declarations,
2952   // extern "C" declarations, and friend declarations in particular).
2953   if (!NewD->getQualifier())
2954     return;
2955
2956   // NewD is probably already in the right context.
2957   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2958   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2959   if (NamedDC->Equals(SemaDC))
2960     return;
2961
2962   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2963           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2964          "unexpected context for redeclaration");
2965
2966   auto *LexDC = NewD->getLexicalDeclContext();
2967   auto FixSemaDC = [=](NamedDecl *D) {
2968     if (!D)
2969       return;
2970     D->setDeclContext(SemaDC);
2971     D->setLexicalDeclContext(LexDC);
2972   };
2973
2974   FixSemaDC(NewD);
2975   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2976     FixSemaDC(FD->getDescribedFunctionTemplate());
2977   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2978     FixSemaDC(VD->getDescribedVarTemplate());
2979 }
2980
2981 /// MergeFunctionDecl - We just parsed a function 'New' from
2982 /// declarator D which has the same name and scope as a previous
2983 /// declaration 'Old'.  Figure out how to resolve this situation,
2984 /// merging decls or emitting diagnostics as appropriate.
2985 ///
2986 /// In C++, New and Old must be declarations that are not
2987 /// overloaded. Use IsOverload to determine whether New and Old are
2988 /// overloaded, and to select the Old declaration that New should be
2989 /// merged with.
2990 ///
2991 /// Returns true if there was an error, false otherwise.
2992 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2993                              Scope *S, bool MergeTypeWithOld) {
2994   // Verify the old decl was also a function.
2995   FunctionDecl *Old = OldD->getAsFunction();
2996   if (!Old) {
2997     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2998       if (New->getFriendObjectKind()) {
2999         Diag(New->getLocation(), diag::err_using_decl_friend);
3000         Diag(Shadow->getTargetDecl()->getLocation(),
3001              diag::note_using_decl_target);
3002         Diag(Shadow->getUsingDecl()->getLocation(),
3003              diag::note_using_decl) << 0;
3004         return true;
3005       }
3006
3007       // Check whether the two declarations might declare the same function.
3008       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3009         return true;
3010       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3011     } else {
3012       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3013         << New->getDeclName();
3014       notePreviousDefinition(OldD, New->getLocation());
3015       return true;
3016     }
3017   }
3018
3019   // If the old declaration is invalid, just give up here.
3020   if (Old->isInvalidDecl())
3021     return true;
3022
3023   // Disallow redeclaration of some builtins.
3024   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3025     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3026     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3027         << Old << Old->getType();
3028     return true;
3029   }
3030
3031   diag::kind PrevDiag;
3032   SourceLocation OldLocation;
3033   std::tie(PrevDiag, OldLocation) =
3034       getNoteDiagForInvalidRedeclaration(Old, New);
3035
3036   // Don't complain about this if we're in GNU89 mode and the old function
3037   // is an extern inline function.
3038   // Don't complain about specializations. They are not supposed to have
3039   // storage classes.
3040   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3041       New->getStorageClass() == SC_Static &&
3042       Old->hasExternalFormalLinkage() &&
3043       !New->getTemplateSpecializationInfo() &&
3044       !canRedefineFunction(Old, getLangOpts())) {
3045     if (getLangOpts().MicrosoftExt) {
3046       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3047       Diag(OldLocation, PrevDiag);
3048     } else {
3049       Diag(New->getLocation(), diag::err_static_non_static) << New;
3050       Diag(OldLocation, PrevDiag);
3051       return true;
3052     }
3053   }
3054
3055   if (New->hasAttr<InternalLinkageAttr>() &&
3056       !Old->hasAttr<InternalLinkageAttr>()) {
3057     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3058         << New->getDeclName();
3059     notePreviousDefinition(Old, New->getLocation());
3060     New->dropAttr<InternalLinkageAttr>();
3061   }
3062
3063   if (CheckRedeclarationModuleOwnership(New, Old))
3064     return true;
3065
3066   if (!getLangOpts().CPlusPlus) {
3067     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3068     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3069       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3070         << New << OldOvl;
3071
3072       // Try our best to find a decl that actually has the overloadable
3073       // attribute for the note. In most cases (e.g. programs with only one
3074       // broken declaration/definition), this won't matter.
3075       //
3076       // FIXME: We could do this if we juggled some extra state in
3077       // OverloadableAttr, rather than just removing it.
3078       const Decl *DiagOld = Old;
3079       if (OldOvl) {
3080         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3081           const auto *A = D->getAttr<OverloadableAttr>();
3082           return A && !A->isImplicit();
3083         });
3084         // If we've implicitly added *all* of the overloadable attrs to this
3085         // chain, emitting a "previous redecl" note is pointless.
3086         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3087       }
3088
3089       if (DiagOld)
3090         Diag(DiagOld->getLocation(),
3091              diag::note_attribute_overloadable_prev_overload)
3092           << OldOvl;
3093
3094       if (OldOvl)
3095         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3096       else
3097         New->dropAttr<OverloadableAttr>();
3098     }
3099   }
3100
3101   // If a function is first declared with a calling convention, but is later
3102   // declared or defined without one, all following decls assume the calling
3103   // convention of the first.
3104   //
3105   // It's OK if a function is first declared without a calling convention,
3106   // but is later declared or defined with the default calling convention.
3107   //
3108   // To test if either decl has an explicit calling convention, we look for
3109   // AttributedType sugar nodes on the type as written.  If they are missing or
3110   // were canonicalized away, we assume the calling convention was implicit.
3111   //
3112   // Note also that we DO NOT return at this point, because we still have
3113   // other tests to run.
3114   QualType OldQType = Context.getCanonicalType(Old->getType());
3115   QualType NewQType = Context.getCanonicalType(New->getType());
3116   const FunctionType *OldType = cast<FunctionType>(OldQType);
3117   const FunctionType *NewType = cast<FunctionType>(NewQType);
3118   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3119   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3120   bool RequiresAdjustment = false;
3121
3122   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3123     FunctionDecl *First = Old->getFirstDecl();
3124     const FunctionType *FT =
3125         First->getType().getCanonicalType()->castAs<FunctionType>();
3126     FunctionType::ExtInfo FI = FT->getExtInfo();
3127     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3128     if (!NewCCExplicit) {
3129       // Inherit the CC from the previous declaration if it was specified
3130       // there but not here.
3131       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3132       RequiresAdjustment = true;
3133     } else {
3134       // Calling conventions aren't compatible, so complain.
3135       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3136       Diag(New->getLocation(), diag::err_cconv_change)
3137         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3138         << !FirstCCExplicit
3139         << (!FirstCCExplicit ? "" :
3140             FunctionType::getNameForCallConv(FI.getCC()));
3141
3142       // Put the note on the first decl, since it is the one that matters.
3143       Diag(First->getLocation(), diag::note_previous_declaration);
3144       return true;
3145     }
3146   }
3147
3148   // FIXME: diagnose the other way around?
3149   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3150     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3151     RequiresAdjustment = true;
3152   }
3153
3154   // Merge regparm attribute.
3155   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3156       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3157     if (NewTypeInfo.getHasRegParm()) {
3158       Diag(New->getLocation(), diag::err_regparm_mismatch)
3159         << NewType->getRegParmType()
3160         << OldType->getRegParmType();
3161       Diag(OldLocation, diag::note_previous_declaration);
3162       return true;
3163     }
3164
3165     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3166     RequiresAdjustment = true;
3167   }
3168
3169   // Merge ns_returns_retained attribute.
3170   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3171     if (NewTypeInfo.getProducesResult()) {
3172       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3173           << "'ns_returns_retained'";
3174       Diag(OldLocation, diag::note_previous_declaration);
3175       return true;
3176     }
3177
3178     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3179     RequiresAdjustment = true;
3180   }
3181
3182   if (OldTypeInfo.getNoCallerSavedRegs() !=
3183       NewTypeInfo.getNoCallerSavedRegs()) {
3184     if (NewTypeInfo.getNoCallerSavedRegs()) {
3185       AnyX86NoCallerSavedRegistersAttr *Attr =
3186         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3187       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3188       Diag(OldLocation, diag::note_previous_declaration);
3189       return true;
3190     }
3191
3192     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3193     RequiresAdjustment = true;
3194   }
3195
3196   if (RequiresAdjustment) {
3197     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3198     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3199     New->setType(QualType(AdjustedType, 0));
3200     NewQType = Context.getCanonicalType(New->getType());
3201     NewType = cast<FunctionType>(NewQType);
3202   }
3203
3204   // If this redeclaration makes the function inline, we may need to add it to
3205   // UndefinedButUsed.
3206   if (!Old->isInlined() && New->isInlined() &&
3207       !New->hasAttr<GNUInlineAttr>() &&
3208       !getLangOpts().GNUInline &&
3209       Old->isUsed(false) &&
3210       !Old->isDefined() && !New->isThisDeclarationADefinition())
3211     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3212                                            SourceLocation()));
3213
3214   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3215   // about it.
3216   if (New->hasAttr<GNUInlineAttr>() &&
3217       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3218     UndefinedButUsed.erase(Old->getCanonicalDecl());
3219   }
3220
3221   // If pass_object_size params don't match up perfectly, this isn't a valid
3222   // redeclaration.
3223   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3224       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3225     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3226         << New->getDeclName();
3227     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3228     return true;
3229   }
3230
3231   if (getLangOpts().CPlusPlus) {
3232     // C++1z [over.load]p2
3233     //   Certain function declarations cannot be overloaded:
3234     //     -- Function declarations that differ only in the return type,
3235     //        the exception specification, or both cannot be overloaded.
3236
3237     // Check the exception specifications match. This may recompute the type of
3238     // both Old and New if it resolved exception specifications, so grab the
3239     // types again after this. Because this updates the type, we do this before
3240     // any of the other checks below, which may update the "de facto" NewQType
3241     // but do not necessarily update the type of New.
3242     if (CheckEquivalentExceptionSpec(Old, New))
3243       return true;
3244     OldQType = Context.getCanonicalType(Old->getType());
3245     NewQType = Context.getCanonicalType(New->getType());
3246
3247     // Go back to the type source info to compare the declared return types,
3248     // per C++1y [dcl.type.auto]p13:
3249     //   Redeclarations or specializations of a function or function template
3250     //   with a declared return type that uses a placeholder type shall also
3251     //   use that placeholder, not a deduced type.
3252     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3253     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3254     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3255         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3256                                        OldDeclaredReturnType)) {
3257       QualType ResQT;
3258       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3259           OldDeclaredReturnType->isObjCObjectPointerType())
3260         // FIXME: This does the wrong thing for a deduced return type.
3261         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3262       if (ResQT.isNull()) {
3263         if (New->isCXXClassMember() && New->isOutOfLine())
3264           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3265               << New << New->getReturnTypeSourceRange();
3266         else
3267           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3268               << New->getReturnTypeSourceRange();
3269         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3270                                     << Old->getReturnTypeSourceRange();
3271         return true;
3272       }
3273       else
3274         NewQType = ResQT;
3275     }
3276
3277     QualType OldReturnType = OldType->getReturnType();
3278     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3279     if (OldReturnType != NewReturnType) {
3280       // If this function has a deduced return type and has already been
3281       // defined, copy the deduced value from the old declaration.
3282       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3283       if (OldAT && OldAT->isDeduced()) {
3284         New->setType(
3285             SubstAutoType(New->getType(),
3286                           OldAT->isDependentType() ? Context.DependentTy
3287                                                    : OldAT->getDeducedType()));
3288         NewQType = Context.getCanonicalType(
3289             SubstAutoType(NewQType,
3290                           OldAT->isDependentType() ? Context.DependentTy
3291                                                    : OldAT->getDeducedType()));
3292       }
3293     }
3294
3295     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3296     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3297     if (OldMethod && NewMethod) {
3298       // Preserve triviality.
3299       NewMethod->setTrivial(OldMethod->isTrivial());
3300
3301       // MSVC allows explicit template specialization at class scope:
3302       // 2 CXXMethodDecls referring to the same function will be injected.
3303       // We don't want a redeclaration error.
3304       bool IsClassScopeExplicitSpecialization =
3305                               OldMethod->isFunctionTemplateSpecialization() &&
3306                               NewMethod->isFunctionTemplateSpecialization();
3307       bool isFriend = NewMethod->getFriendObjectKind();
3308
3309       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3310           !IsClassScopeExplicitSpecialization) {
3311         //    -- Member function declarations with the same name and the
3312         //       same parameter types cannot be overloaded if any of them
3313         //       is a static member function declaration.
3314         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3315           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3316           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3317           return true;
3318         }
3319
3320         // C++ [class.mem]p1:
3321         //   [...] A member shall not be declared twice in the
3322         //   member-specification, except that a nested class or member
3323         //   class template can be declared and then later defined.
3324         if (!inTemplateInstantiation()) {
3325           unsigned NewDiag;
3326           if (isa<CXXConstructorDecl>(OldMethod))
3327             NewDiag = diag::err_constructor_redeclared;
3328           else if (isa<CXXDestructorDecl>(NewMethod))
3329             NewDiag = diag::err_destructor_redeclared;
3330           else if (isa<CXXConversionDecl>(NewMethod))
3331             NewDiag = diag::err_conv_function_redeclared;
3332           else
3333             NewDiag = diag::err_member_redeclared;
3334
3335           Diag(New->getLocation(), NewDiag);
3336         } else {
3337           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3338             << New << New->getType();
3339         }
3340         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3341         return true;
3342
3343       // Complain if this is an explicit declaration of a special
3344       // member that was initially declared implicitly.
3345       //
3346       // As an exception, it's okay to befriend such methods in order
3347       // to permit the implicit constructor/destructor/operator calls.
3348       } else if (OldMethod->isImplicit()) {
3349         if (isFriend) {
3350           NewMethod->setImplicit();
3351         } else {
3352           Diag(NewMethod->getLocation(),
3353                diag::err_definition_of_implicitly_declared_member)
3354             << New << getSpecialMember(OldMethod);
3355           return true;
3356         }
3357       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3358         Diag(NewMethod->getLocation(),
3359              diag::err_definition_of_explicitly_defaulted_member)
3360           << getSpecialMember(OldMethod);
3361         return true;
3362       }
3363     }
3364
3365     // C++11 [dcl.attr.noreturn]p1:
3366     //   The first declaration of a function shall specify the noreturn
3367     //   attribute if any declaration of that function specifies the noreturn
3368     //   attribute.
3369     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3370     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3371       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3372       Diag(Old->getFirstDecl()->getLocation(),
3373            diag::note_noreturn_missing_first_decl);
3374     }
3375
3376     // C++11 [dcl.attr.depend]p2:
3377     //   The first declaration of a function shall specify the
3378     //   carries_dependency attribute for its declarator-id if any declaration
3379     //   of the function specifies the carries_dependency attribute.
3380     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3381     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3382       Diag(CDA->getLocation(),
3383            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3384       Diag(Old->getFirstDecl()->getLocation(),
3385            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3386     }
3387
3388     // (C++98 8.3.5p3):
3389     //   All declarations for a function shall agree exactly in both the
3390     //   return type and the parameter-type-list.
3391     // We also want to respect all the extended bits except noreturn.
3392
3393     // noreturn should now match unless the old type info didn't have it.
3394     QualType OldQTypeForComparison = OldQType;
3395     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3396       auto *OldType = OldQType->castAs<FunctionProtoType>();
3397       const FunctionType *OldTypeForComparison
3398         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3399       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3400       assert(OldQTypeForComparison.isCanonical());
3401     }
3402
3403     if (haveIncompatibleLanguageLinkages(Old, New)) {
3404       // As a special case, retain the language linkage from previous
3405       // declarations of a friend function as an extension.
3406       //
3407       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3408       // and is useful because there's otherwise no way to specify language
3409       // linkage within class scope.
3410       //
3411       // Check cautiously as the friend object kind isn't yet complete.
3412       if (New->getFriendObjectKind() != Decl::FOK_None) {
3413         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3414         Diag(OldLocation, PrevDiag);
3415       } else {
3416         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3417         Diag(OldLocation, PrevDiag);
3418         return true;
3419       }
3420     }
3421
3422     if (OldQTypeForComparison == NewQType)
3423       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3424
3425     // If the types are imprecise (due to dependent constructs in friends or
3426     // local extern declarations), it's OK if they differ. We'll check again
3427     // during instantiation.
3428     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3429       return false;
3430
3431     // Fall through for conflicting redeclarations and redefinitions.
3432   }
3433
3434   // C: Function types need to be compatible, not identical. This handles
3435   // duplicate function decls like "void f(int); void f(enum X);" properly.
3436   if (!getLangOpts().CPlusPlus &&
3437       Context.typesAreCompatible(OldQType, NewQType)) {
3438     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3439     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3440     const FunctionProtoType *OldProto = nullptr;
3441     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3442         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3443       // The old declaration provided a function prototype, but the
3444       // new declaration does not. Merge in the prototype.
3445       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3446       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3447       NewQType =
3448           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3449                                   OldProto->getExtProtoInfo());
3450       New->setType(NewQType);
3451       New->setHasInheritedPrototype();
3452
3453       // Synthesize parameters with the same types.
3454       SmallVector<ParmVarDecl*, 16> Params;
3455       for (const auto &ParamType : OldProto->param_types()) {
3456         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3457                                                  SourceLocation(), nullptr,
3458                                                  ParamType, /*TInfo=*/nullptr,
3459                                                  SC_None, nullptr);
3460         Param->setScopeInfo(0, Params.size());
3461         Param->setImplicit();
3462         Params.push_back(Param);
3463       }
3464
3465       New->setParams(Params);
3466     }
3467
3468     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3469   }
3470
3471   // GNU C permits a K&R definition to follow a prototype declaration
3472   // if the declared types of the parameters in the K&R definition
3473   // match the types in the prototype declaration, even when the
3474   // promoted types of the parameters from the K&R definition differ
3475   // from the types in the prototype. GCC then keeps the types from
3476   // the prototype.
3477   //
3478   // If a variadic prototype is followed by a non-variadic K&R definition,
3479   // the K&R definition becomes variadic.  This is sort of an edge case, but
3480   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3481   // C99 6.9.1p8.
3482   if (!getLangOpts().CPlusPlus &&
3483       Old->hasPrototype() && !New->hasPrototype() &&
3484       New->getType()->getAs<FunctionProtoType>() &&
3485       Old->getNumParams() == New->getNumParams()) {
3486     SmallVector<QualType, 16> ArgTypes;
3487     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3488     const FunctionProtoType *OldProto
3489       = Old->getType()->getAs<FunctionProtoType>();
3490     const FunctionProtoType *NewProto
3491       = New->getType()->getAs<FunctionProtoType>();
3492
3493     // Determine whether this is the GNU C extension.
3494     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3495                                                NewProto->getReturnType());
3496     bool LooseCompatible = !MergedReturn.isNull();
3497     for (unsigned Idx = 0, End = Old->getNumParams();
3498          LooseCompatible && Idx != End; ++Idx) {
3499       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3500       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3501       if (Context.typesAreCompatible(OldParm->getType(),
3502                                      NewProto->getParamType(Idx))) {
3503         ArgTypes.push_back(NewParm->getType());
3504       } else if (Context.typesAreCompatible(OldParm->getType(),
3505                                             NewParm->getType(),
3506                                             /*CompareUnqualified=*/true)) {
3507         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3508                                            NewProto->getParamType(Idx) };
3509         Warnings.push_back(Warn);
3510         ArgTypes.push_back(NewParm->getType());
3511       } else
3512         LooseCompatible = false;
3513     }
3514
3515     if (LooseCompatible) {
3516       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3517         Diag(Warnings[Warn].NewParm->getLocation(),
3518              diag::ext_param_promoted_not_compatible_with_prototype)
3519           << Warnings[Warn].PromotedType
3520           << Warnings[Warn].OldParm->getType();
3521         if (Warnings[Warn].OldParm->getLocation().isValid())
3522           Diag(Warnings[Warn].OldParm->getLocation(),
3523                diag::note_previous_declaration);
3524       }
3525
3526       if (MergeTypeWithOld)
3527         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3528                                              OldProto->getExtProtoInfo()));
3529       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3530     }
3531
3532     // Fall through to diagnose conflicting types.
3533   }
3534
3535   // A function that has already been declared has been redeclared or
3536   // defined with a different type; show an appropriate diagnostic.
3537
3538   // If the previous declaration was an implicitly-generated builtin
3539   // declaration, then at the very least we should use a specialized note.
3540   unsigned BuiltinID;
3541   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3542     // If it's actually a library-defined builtin function like 'malloc'
3543     // or 'printf', just warn about the incompatible redeclaration.
3544     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3545       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3546       Diag(OldLocation, diag::note_previous_builtin_declaration)
3547         << Old << Old->getType();
3548
3549       // If this is a global redeclaration, just forget hereafter
3550       // about the "builtin-ness" of the function.
3551       //
3552       // Doing this for local extern declarations is problematic.  If
3553       // the builtin declaration remains visible, a second invalid
3554       // local declaration will produce a hard error; if it doesn't
3555       // remain visible, a single bogus local redeclaration (which is
3556       // actually only a warning) could break all the downstream code.
3557       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3558         New->getIdentifier()->revertBuiltin();
3559
3560       return false;
3561     }
3562
3563     PrevDiag = diag::note_previous_builtin_declaration;
3564   }
3565
3566   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3567   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3568   return true;
3569 }
3570
3571 /// Completes the merge of two function declarations that are
3572 /// known to be compatible.
3573 ///
3574 /// This routine handles the merging of attributes and other
3575 /// properties of function declarations from the old declaration to
3576 /// the new declaration, once we know that New is in fact a
3577 /// redeclaration of Old.
3578 ///
3579 /// \returns false
3580 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3581                                         Scope *S, bool MergeTypeWithOld) {
3582   // Merge the attributes
3583   mergeDeclAttributes(New, Old);
3584
3585   // Merge "pure" flag.
3586   if (Old->isPure())
3587     New->setPure();
3588
3589   // Merge "used" flag.
3590   if (Old->getMostRecentDecl()->isUsed(false))
3591     New->setIsUsed();
3592
3593   // Merge attributes from the parameters.  These can mismatch with K&R
3594   // declarations.
3595   if (New->getNumParams() == Old->getNumParams())
3596       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3597         ParmVarDecl *NewParam = New->getParamDecl(i);
3598         ParmVarDecl *OldParam = Old->getParamDecl(i);
3599         mergeParamDeclAttributes(NewParam, OldParam, *this);
3600         mergeParamDeclTypes(NewParam, OldParam, *this);
3601       }
3602
3603   if (getLangOpts().CPlusPlus)
3604     return MergeCXXFunctionDecl(New, Old, S);
3605
3606   // Merge the function types so the we get the composite types for the return
3607   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3608   // was visible.
3609   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3610   if (!Merged.isNull() && MergeTypeWithOld)
3611     New->setType(Merged);
3612
3613   return false;
3614 }
3615
3616 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3617                                 ObjCMethodDecl *oldMethod) {
3618   // Merge the attributes, including deprecated/unavailable
3619   AvailabilityMergeKind MergeKind =
3620     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3621       ? AMK_ProtocolImplementation
3622       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3623                                                        : AMK_Override;
3624
3625   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3626
3627   // Merge attributes from the parameters.
3628   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3629                                        oe = oldMethod->param_end();
3630   for (ObjCMethodDecl::param_iterator
3631          ni = newMethod->param_begin(), ne = newMethod->param_end();
3632        ni != ne && oi != oe; ++ni, ++oi)
3633     mergeParamDeclAttributes(*ni, *oi, *this);
3634
3635   CheckObjCMethodOverride(newMethod, oldMethod);
3636 }
3637
3638 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3639   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3640
3641   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3642          ? diag::err_redefinition_different_type
3643          : diag::err_redeclaration_different_type)
3644     << New->getDeclName() << New->getType() << Old->getType();
3645
3646   diag::kind PrevDiag;
3647   SourceLocation OldLocation;
3648   std::tie(PrevDiag, OldLocation)
3649     = getNoteDiagForInvalidRedeclaration(Old, New);
3650   S.Diag(OldLocation, PrevDiag);
3651   New->setInvalidDecl();
3652 }
3653
3654 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3655 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3656 /// emitting diagnostics as appropriate.
3657 ///
3658 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3659 /// to here in AddInitializerToDecl. We can't check them before the initializer
3660 /// is attached.
3661 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3662                              bool MergeTypeWithOld) {
3663   if (New->isInvalidDecl() || Old->isInvalidDecl())
3664     return;
3665
3666   QualType MergedT;
3667   if (getLangOpts().CPlusPlus) {
3668     if (New->getType()->isUndeducedType()) {
3669       // We don't know what the new type is until the initializer is attached.
3670       return;
3671     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3672       // These could still be something that needs exception specs checked.
3673       return MergeVarDeclExceptionSpecs(New, Old);
3674     }
3675     // C++ [basic.link]p10:
3676     //   [...] the types specified by all declarations referring to a given
3677     //   object or function shall be identical, except that declarations for an
3678     //   array object can specify array types that differ by the presence or
3679     //   absence of a major array bound (8.3.4).
3680     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3681       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3682       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3683
3684       // We are merging a variable declaration New into Old. If it has an array
3685       // bound, and that bound differs from Old's bound, we should diagnose the
3686       // mismatch.
3687       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3688         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3689              PrevVD = PrevVD->getPreviousDecl()) {
3690           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3691           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3692             continue;
3693
3694           if (!Context.hasSameType(NewArray, PrevVDTy))
3695             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3696         }
3697       }
3698
3699       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3700         if (Context.hasSameType(OldArray->getElementType(),
3701                                 NewArray->getElementType()))
3702           MergedT = New->getType();
3703       }
3704       // FIXME: Check visibility. New is hidden but has a complete type. If New
3705       // has no array bound, it should not inherit one from Old, if Old is not
3706       // visible.
3707       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3708         if (Context.hasSameType(OldArray->getElementType(),
3709                                 NewArray->getElementType()))
3710           MergedT = Old->getType();
3711       }
3712     }
3713     else if (New->getType()->isObjCObjectPointerType() &&
3714                Old->getType()->isObjCObjectPointerType()) {
3715       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3716                                               Old->getType());
3717     }
3718   } else {
3719     // C 6.2.7p2:
3720     //   All declarations that refer to the same object or function shall have
3721     //   compatible type.
3722     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3723   }
3724   if (MergedT.isNull()) {
3725     // It's OK if we couldn't merge types if either type is dependent, for a
3726     // block-scope variable. In other cases (static data members of class
3727     // templates, variable templates, ...), we require the types to be
3728     // equivalent.
3729     // FIXME: The C++ standard doesn't say anything about this.
3730     if ((New->getType()->isDependentType() ||
3731          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3732       // If the old type was dependent, we can't merge with it, so the new type
3733       // becomes dependent for now. We'll reproduce the original type when we
3734       // instantiate the TypeSourceInfo for the variable.
3735       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3736         New->setType(Context.DependentTy);
3737       return;
3738     }
3739     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3740   }
3741
3742   // Don't actually update the type on the new declaration if the old
3743   // declaration was an extern declaration in a different scope.
3744   if (MergeTypeWithOld)
3745     New->setType(MergedT);
3746 }
3747
3748 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3749                                   LookupResult &Previous) {
3750   // C11 6.2.7p4:
3751   //   For an identifier with internal or external linkage declared
3752   //   in a scope in which a prior declaration of that identifier is
3753   //   visible, if the prior declaration specifies internal or
3754   //   external linkage, the type of the identifier at the later
3755   //   declaration becomes the composite type.
3756   //
3757   // If the variable isn't visible, we do not merge with its type.
3758   if (Previous.isShadowed())
3759     return false;
3760
3761   if (S.getLangOpts().CPlusPlus) {
3762     // C++11 [dcl.array]p3:
3763     //   If there is a preceding declaration of the entity in the same
3764     //   scope in which the bound was specified, an omitted array bound
3765     //   is taken to be the same as in that earlier declaration.
3766     return NewVD->isPreviousDeclInSameBlockScope() ||
3767            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3768             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3769   } else {
3770     // If the old declaration was function-local, don't merge with its
3771     // type unless we're in the same function.
3772     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3773            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3774   }
3775 }
3776
3777 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3778 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3779 /// situation, merging decls or emitting diagnostics as appropriate.
3780 ///
3781 /// Tentative definition rules (C99 6.9.2p2) are checked by
3782 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3783 /// definitions here, since the initializer hasn't been attached.
3784 ///
3785 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3786   // If the new decl is already invalid, don't do any other checking.
3787   if (New->isInvalidDecl())
3788     return;
3789
3790   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3791     return;
3792
3793   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3794
3795   // Verify the old decl was also a variable or variable template.
3796   VarDecl *Old = nullptr;
3797   VarTemplateDecl *OldTemplate = nullptr;
3798   if (Previous.isSingleResult()) {
3799     if (NewTemplate) {
3800       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3801       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3802
3803       if (auto *Shadow =
3804               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3805         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3806           return New->setInvalidDecl();
3807     } else {
3808       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3809
3810       if (auto *Shadow =
3811               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3812         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3813           return New->setInvalidDecl();
3814     }
3815   }
3816   if (!Old) {
3817     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3818         << New->getDeclName();
3819     notePreviousDefinition(Previous.getRepresentativeDecl(),
3820                            New->getLocation());
3821     return New->setInvalidDecl();
3822   }
3823
3824   // Ensure the template parameters are compatible.
3825   if (NewTemplate &&
3826       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3827                                       OldTemplate->getTemplateParameters(),
3828                                       /*Complain=*/true, TPL_TemplateMatch))
3829     return New->setInvalidDecl();
3830
3831   // C++ [class.mem]p1:
3832   //   A member shall not be declared twice in the member-specification [...]
3833   //
3834   // Here, we need only consider static data members.
3835   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3836     Diag(New->getLocation(), diag::err_duplicate_member)
3837       << New->getIdentifier();
3838     Diag(Old->getLocation(), diag::note_previous_declaration);
3839     New->setInvalidDecl();
3840   }
3841
3842   mergeDeclAttributes(New, Old);
3843   // Warn if an already-declared variable is made a weak_import in a subsequent
3844   // declaration
3845   if (New->hasAttr<WeakImportAttr>() &&
3846       Old->getStorageClass() == SC_None &&
3847       !Old->hasAttr<WeakImportAttr>()) {
3848     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3849     notePreviousDefinition(Old, New->getLocation());
3850     // Remove weak_import attribute on new declaration.
3851     New->dropAttr<WeakImportAttr>();
3852   }
3853
3854   if (New->hasAttr<InternalLinkageAttr>() &&
3855       !Old->hasAttr<InternalLinkageAttr>()) {
3856     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3857         << New->getDeclName();
3858     notePreviousDefinition(Old, New->getLocation());
3859     New->dropAttr<InternalLinkageAttr>();
3860   }
3861
3862   // Merge the types.
3863   VarDecl *MostRecent = Old->getMostRecentDecl();
3864   if (MostRecent != Old) {
3865     MergeVarDeclTypes(New, MostRecent,
3866                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3867     if (New->isInvalidDecl())
3868       return;
3869   }
3870
3871   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3872   if (New->isInvalidDecl())
3873     return;
3874
3875   diag::kind PrevDiag;
3876   SourceLocation OldLocation;
3877   std::tie(PrevDiag, OldLocation) =
3878       getNoteDiagForInvalidRedeclaration(Old, New);
3879
3880   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3881   if (New->getStorageClass() == SC_Static &&
3882       !New->isStaticDataMember() &&
3883       Old->hasExternalFormalLinkage()) {
3884     if (getLangOpts().MicrosoftExt) {
3885       Diag(New->getLocation(), diag::ext_static_non_static)
3886           << New->getDeclName();
3887       Diag(OldLocation, PrevDiag);
3888     } else {
3889       Diag(New->getLocation(), diag::err_static_non_static)
3890           << New->getDeclName();
3891       Diag(OldLocation, PrevDiag);
3892       return New->setInvalidDecl();
3893     }
3894   }
3895   // C99 6.2.2p4:
3896   //   For an identifier declared with the storage-class specifier
3897   //   extern in a scope in which a prior declaration of that
3898   //   identifier is visible,23) if the prior declaration specifies
3899   //   internal or external linkage, the linkage of the identifier at
3900   //   the later declaration is the same as the linkage specified at
3901   //   the prior declaration. If no prior declaration is visible, or
3902   //   if the prior declaration specifies no linkage, then the
3903   //   identifier has external linkage.
3904   if (New->hasExternalStorage() && Old->hasLinkage())
3905     /* Okay */;
3906   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3907            !New->isStaticDataMember() &&
3908            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3909     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3910     Diag(OldLocation, PrevDiag);
3911     return New->setInvalidDecl();
3912   }
3913
3914   // Check if extern is followed by non-extern and vice-versa.
3915   if (New->hasExternalStorage() &&
3916       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3917     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3918     Diag(OldLocation, PrevDiag);
3919     return New->setInvalidDecl();
3920   }
3921   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3922       !New->hasExternalStorage()) {
3923     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3924     Diag(OldLocation, PrevDiag);
3925     return New->setInvalidDecl();
3926   }
3927
3928   if (CheckRedeclarationModuleOwnership(New, Old))
3929     return;
3930
3931   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3932
3933   // FIXME: The test for external storage here seems wrong? We still
3934   // need to check for mismatches.
3935   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3936       // Don't complain about out-of-line definitions of static members.
3937       !(Old->getLexicalDeclContext()->isRecord() &&
3938         !New->getLexicalDeclContext()->isRecord())) {
3939     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3940     Diag(OldLocation, PrevDiag);
3941     return New->setInvalidDecl();
3942   }
3943
3944   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3945     if (VarDecl *Def = Old->getDefinition()) {
3946       // C++1z [dcl.fcn.spec]p4:
3947       //   If the definition of a variable appears in a translation unit before
3948       //   its first declaration as inline, the program is ill-formed.
3949       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3950       Diag(Def->getLocation(), diag::note_previous_definition);
3951     }
3952   }
3953
3954   // If this redeclaration makes the variable inline, we may need to add it to
3955   // UndefinedButUsed.
3956   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3957       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3958     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3959                                            SourceLocation()));
3960
3961   if (New->getTLSKind() != Old->getTLSKind()) {
3962     if (!Old->getTLSKind()) {
3963       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3964       Diag(OldLocation, PrevDiag);
3965     } else if (!New->getTLSKind()) {
3966       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3967       Diag(OldLocation, PrevDiag);
3968     } else {
3969       // Do not allow redeclaration to change the variable between requiring
3970       // static and dynamic initialization.
3971       // FIXME: GCC allows this, but uses the TLS keyword on the first
3972       // declaration to determine the kind. Do we need to be compatible here?
3973       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3974         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3975       Diag(OldLocation, PrevDiag);
3976     }
3977   }
3978
3979   // C++ doesn't have tentative definitions, so go right ahead and check here.
3980   if (getLangOpts().CPlusPlus &&
3981       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3982     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3983         Old->getCanonicalDecl()->isConstexpr()) {
3984       // This definition won't be a definition any more once it's been merged.
3985       Diag(New->getLocation(),
3986            diag::warn_deprecated_redundant_constexpr_static_def);
3987     } else if (VarDecl *Def = Old->getDefinition()) {
3988       if (checkVarDeclRedefinition(Def, New))
3989         return;
3990     }
3991   }
3992
3993   if (haveIncompatibleLanguageLinkages(Old, New)) {
3994     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3995     Diag(OldLocation, PrevDiag);
3996     New->setInvalidDecl();
3997     return;
3998   }
3999
4000   // Merge "used" flag.
4001   if (Old->getMostRecentDecl()->isUsed(false))
4002     New->setIsUsed();
4003
4004   // Keep a chain of previous declarations.
4005   New->setPreviousDecl(Old);
4006   if (NewTemplate)
4007     NewTemplate->setPreviousDecl(OldTemplate);
4008   adjustDeclContextForDeclaratorDecl(New, Old);
4009
4010   // Inherit access appropriately.
4011   New->setAccess(Old->getAccess());
4012   if (NewTemplate)
4013     NewTemplate->setAccess(New->getAccess());
4014
4015   if (Old->isInline())
4016     New->setImplicitlyInline();
4017 }
4018
4019 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4020   SourceManager &SrcMgr = getSourceManager();
4021   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4022   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4023   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4024   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4025   auto &HSI = PP.getHeaderSearchInfo();
4026   StringRef HdrFilename =
4027       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4028
4029   auto noteFromModuleOrInclude = [&](Module *Mod,
4030                                      SourceLocation IncLoc) -> bool {
4031     // Redefinition errors with modules are common with non modular mapped
4032     // headers, example: a non-modular header H in module A that also gets
4033     // included directly in a TU. Pointing twice to the same header/definition
4034     // is confusing, try to get better diagnostics when modules is on.
4035     if (IncLoc.isValid()) {
4036       if (Mod) {
4037         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4038             << HdrFilename.str() << Mod->getFullModuleName();
4039         if (!Mod->DefinitionLoc.isInvalid())
4040           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4041               << Mod->getFullModuleName();
4042       } else {
4043         Diag(IncLoc, diag::note_redefinition_include_same_file)
4044             << HdrFilename.str();
4045       }
4046       return true;
4047     }
4048
4049     return false;
4050   };
4051
4052   // Is it the same file and same offset? Provide more information on why
4053   // this leads to a redefinition error.
4054   bool EmittedDiag = false;
4055   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4056     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4057     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4058     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4059     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4060
4061     // If the header has no guards, emit a note suggesting one.
4062     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4063       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4064
4065     if (EmittedDiag)
4066       return;
4067   }
4068
4069   // Redefinition coming from different files or couldn't do better above.
4070   if (Old->getLocation().isValid())
4071     Diag(Old->getLocation(), diag::note_previous_definition);
4072 }
4073
4074 /// We've just determined that \p Old and \p New both appear to be definitions
4075 /// of the same variable. Either diagnose or fix the problem.
4076 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4077   if (!hasVisibleDefinition(Old) &&
4078       (New->getFormalLinkage() == InternalLinkage ||
4079        New->isInline() ||
4080        New->getDescribedVarTemplate() ||
4081        New->getNumTemplateParameterLists() ||
4082        New->getDeclContext()->isDependentContext())) {
4083     // The previous definition is hidden, and multiple definitions are
4084     // permitted (in separate TUs). Demote this to a declaration.
4085     New->demoteThisDefinitionToDeclaration();
4086
4087     // Make the canonical definition visible.
4088     if (auto *OldTD = Old->getDescribedVarTemplate())
4089       makeMergedDefinitionVisible(OldTD);
4090     makeMergedDefinitionVisible(Old);
4091     return false;
4092   } else {
4093     Diag(New->getLocation(), diag::err_redefinition) << New;
4094     notePreviousDefinition(Old, New->getLocation());
4095     New->setInvalidDecl();
4096     return true;
4097   }
4098 }
4099
4100 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4101 /// no declarator (e.g. "struct foo;") is parsed.
4102 Decl *
4103 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4104                                  RecordDecl *&AnonRecord) {
4105   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4106                                     AnonRecord);
4107 }
4108
4109 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4110 // disambiguate entities defined in different scopes.
4111 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4112 // compatibility.
4113 // We will pick our mangling number depending on which version of MSVC is being
4114 // targeted.
4115 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4116   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4117              ? S->getMSCurManglingNumber()
4118              : S->getMSLastManglingNumber();
4119 }
4120
4121 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4122   if (!Context.getLangOpts().CPlusPlus)
4123     return;
4124
4125   if (isa<CXXRecordDecl>(Tag->getParent())) {
4126     // If this tag is the direct child of a class, number it if
4127     // it is anonymous.
4128     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4129       return;
4130     MangleNumberingContext &MCtx =
4131         Context.getManglingNumberContext(Tag->getParent());
4132     Context.setManglingNumber(
4133         Tag, MCtx.getManglingNumber(
4134                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4135     return;
4136   }
4137
4138   // If this tag isn't a direct child of a class, number it if it is local.
4139   Decl *ManglingContextDecl;
4140   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4141           Tag->getDeclContext(), ManglingContextDecl)) {
4142     Context.setManglingNumber(
4143         Tag, MCtx->getManglingNumber(
4144                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4145   }
4146 }
4147
4148 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4149                                         TypedefNameDecl *NewTD) {
4150   if (TagFromDeclSpec->isInvalidDecl())
4151     return;
4152
4153   // Do nothing if the tag already has a name for linkage purposes.
4154   if (TagFromDeclSpec->hasNameForLinkage())
4155     return;
4156
4157   // A well-formed anonymous tag must always be a TUK_Definition.
4158   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4159
4160   // The type must match the tag exactly;  no qualifiers allowed.
4161   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4162                            Context.getTagDeclType(TagFromDeclSpec))) {
4163     if (getLangOpts().CPlusPlus)
4164       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4165     return;
4166   }
4167
4168   // If we've already computed linkage for the anonymous tag, then
4169   // adding a typedef name for the anonymous decl can change that
4170   // linkage, which might be a serious problem.  Diagnose this as
4171   // unsupported and ignore the typedef name.  TODO: we should
4172   // pursue this as a language defect and establish a formal rule
4173   // for how to handle it.
4174   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4175     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4176
4177     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4178     tagLoc = getLocForEndOfToken(tagLoc);
4179
4180     llvm::SmallString<40> textToInsert;
4181     textToInsert += ' ';
4182     textToInsert += NewTD->getIdentifier()->getName();
4183     Diag(tagLoc, diag::note_typedef_changes_linkage)
4184         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4185     return;
4186   }
4187
4188   // Otherwise, set this is the anon-decl typedef for the tag.
4189   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4190 }
4191
4192 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4193   switch (T) {
4194   case DeclSpec::TST_class:
4195     return 0;
4196   case DeclSpec::TST_struct:
4197     return 1;
4198   case DeclSpec::TST_interface:
4199     return 2;
4200   case DeclSpec::TST_union:
4201     return 3;
4202   case DeclSpec::TST_enum:
4203     return 4;
4204   default:
4205     llvm_unreachable("unexpected type specifier");
4206   }
4207 }
4208
4209 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4210 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4211 /// parameters to cope with template friend declarations.
4212 Decl *
4213 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4214                                  MultiTemplateParamsArg TemplateParams,
4215                                  bool IsExplicitInstantiation,
4216                                  RecordDecl *&AnonRecord) {
4217   Decl *TagD = nullptr;
4218   TagDecl *Tag = nullptr;
4219   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4220       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4221       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4222       DS.getTypeSpecType() == DeclSpec::TST_union ||
4223       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4224     TagD = DS.getRepAsDecl();
4225
4226     if (!TagD) // We probably had an error
4227       return nullptr;
4228
4229     // Note that the above type specs guarantee that the
4230     // type rep is a Decl, whereas in many of the others
4231     // it's a Type.
4232     if (isa<TagDecl>(TagD))
4233       Tag = cast<TagDecl>(TagD);
4234     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4235       Tag = CTD->getTemplatedDecl();
4236   }
4237
4238   if (Tag) {
4239     handleTagNumbering(Tag, S);
4240     Tag->setFreeStanding();
4241     if (Tag->isInvalidDecl())
4242       return Tag;
4243   }
4244
4245   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4246     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4247     // or incomplete types shall not be restrict-qualified."
4248     if (TypeQuals & DeclSpec::TQ_restrict)
4249       Diag(DS.getRestrictSpecLoc(),
4250            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4251            << DS.getSourceRange();
4252   }
4253
4254   if (DS.isInlineSpecified())
4255     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4256         << getLangOpts().CPlusPlus17;
4257
4258   if (DS.isConstexprSpecified()) {
4259     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4260     // and definitions of functions and variables.
4261     if (Tag)
4262       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4263           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4264     else
4265       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4266     // Don't emit warnings after this error.
4267     return TagD;
4268   }
4269
4270   DiagnoseFunctionSpecifiers(DS);
4271
4272   if (DS.isFriendSpecified()) {
4273     // If we're dealing with a decl but not a TagDecl, assume that
4274     // whatever routines created it handled the friendship aspect.
4275     if (TagD && !Tag)
4276       return nullptr;
4277     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4278   }
4279
4280   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4281   bool IsExplicitSpecialization =
4282     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4283   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4284       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4285       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4286     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4287     // nested-name-specifier unless it is an explicit instantiation
4288     // or an explicit specialization.
4289     //
4290     // FIXME: We allow class template partial specializations here too, per the
4291     // obvious intent of DR1819.
4292     //
4293     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4294     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4295         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4296     return nullptr;
4297   }
4298
4299   // Track whether this decl-specifier declares anything.
4300   bool DeclaresAnything = true;
4301
4302   // Handle anonymous struct definitions.
4303   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4304     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4305         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4306       if (getLangOpts().CPlusPlus ||
4307           Record->getDeclContext()->isRecord()) {
4308         // If CurContext is a DeclContext that can contain statements,
4309         // RecursiveASTVisitor won't visit the decls that
4310         // BuildAnonymousStructOrUnion() will put into CurContext.
4311         // Also store them here so that they can be part of the
4312         // DeclStmt that gets created in this case.
4313         // FIXME: Also return the IndirectFieldDecls created by
4314         // BuildAnonymousStructOr union, for the same reason?
4315         if (CurContext->isFunctionOrMethod())
4316           AnonRecord = Record;
4317         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4318                                            Context.getPrintingPolicy());
4319       }
4320
4321       DeclaresAnything = false;
4322     }
4323   }
4324
4325   // C11 6.7.2.1p2:
4326   //   A struct-declaration that does not declare an anonymous structure or
4327   //   anonymous union shall contain a struct-declarator-list.
4328   //
4329   // This rule also existed in C89 and C99; the grammar for struct-declaration
4330   // did not permit a struct-declaration without a struct-declarator-list.
4331   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4332       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4333     // Check for Microsoft C extension: anonymous struct/union member.
4334     // Handle 2 kinds of anonymous struct/union:
4335     //   struct STRUCT;
4336     //   union UNION;
4337     // and
4338     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4339     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4340     if ((Tag && Tag->getDeclName()) ||
4341         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4342       RecordDecl *Record = nullptr;
4343       if (Tag)
4344         Record = dyn_cast<RecordDecl>(Tag);
4345       else if (const RecordType *RT =
4346                    DS.getRepAsType().get()->getAsStructureType())
4347         Record = RT->getDecl();
4348       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4349         Record = UT->getDecl();
4350
4351       if (Record && getLangOpts().MicrosoftExt) {
4352         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4353           << Record->isUnion() << DS.getSourceRange();
4354         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4355       }
4356
4357       DeclaresAnything = false;
4358     }
4359   }
4360
4361   // Skip all the checks below if we have a type error.
4362   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4363       (TagD && TagD->isInvalidDecl()))
4364     return TagD;
4365
4366   if (getLangOpts().CPlusPlus &&
4367       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4368     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4369       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4370           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4371         DeclaresAnything = false;
4372
4373   if (!DS.isMissingDeclaratorOk()) {
4374     // Customize diagnostic for a typedef missing a name.
4375     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4376       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4377         << DS.getSourceRange();
4378     else
4379       DeclaresAnything = false;
4380   }
4381
4382   if (DS.isModulePrivateSpecified() &&
4383       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4384     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4385       << Tag->getTagKind()
4386       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4387
4388   ActOnDocumentableDecl(TagD);
4389
4390   // C 6.7/2:
4391   //   A declaration [...] shall declare at least a declarator [...], a tag,
4392   //   or the members of an enumeration.
4393   // C++ [dcl.dcl]p3:
4394   //   [If there are no declarators], and except for the declaration of an
4395   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4396   //   names into the program, or shall redeclare a name introduced by a
4397   //   previous declaration.
4398   if (!DeclaresAnything) {
4399     // In C, we allow this as a (popular) extension / bug. Don't bother
4400     // producing further diagnostics for redundant qualifiers after this.
4401     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4402     return TagD;
4403   }
4404
4405   // C++ [dcl.stc]p1:
4406   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4407   //   init-declarator-list of the declaration shall not be empty.
4408   // C++ [dcl.fct.spec]p1:
4409   //   If a cv-qualifier appears in a decl-specifier-seq, the
4410   //   init-declarator-list of the declaration shall not be empty.
4411   //
4412   // Spurious qualifiers here appear to be valid in C.
4413   unsigned DiagID = diag::warn_standalone_specifier;
4414   if (getLangOpts().CPlusPlus)
4415     DiagID = diag::ext_standalone_specifier;
4416
4417   // Note that a linkage-specification sets a storage class, but
4418   // 'extern "C" struct foo;' is actually valid and not theoretically
4419   // useless.
4420   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4421     if (SCS == DeclSpec::SCS_mutable)
4422       // Since mutable is not a viable storage class specifier in C, there is
4423       // no reason to treat it as an extension. Instead, diagnose as an error.
4424       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4425     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4426       Diag(DS.getStorageClassSpecLoc(), DiagID)
4427         << DeclSpec::getSpecifierName(SCS);
4428   }
4429
4430   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4431     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4432       << DeclSpec::getSpecifierName(TSCS);
4433   if (DS.getTypeQualifiers()) {
4434     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4435       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4436     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4437       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4438     // Restrict is covered above.
4439     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4440       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4441     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4442       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4443   }
4444
4445   // Warn about ignored type attributes, for example:
4446   // __attribute__((aligned)) struct A;
4447   // Attributes should be placed after tag to apply to type declaration.
4448   if (!DS.getAttributes().empty()) {
4449     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4450     if (TypeSpecType == DeclSpec::TST_class ||
4451         TypeSpecType == DeclSpec::TST_struct ||
4452         TypeSpecType == DeclSpec::TST_interface ||
4453         TypeSpecType == DeclSpec::TST_union ||
4454         TypeSpecType == DeclSpec::TST_enum) {
4455       for (const ParsedAttr &AL : DS.getAttributes())
4456         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4457             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4458     }
4459   }
4460
4461   return TagD;
4462 }
4463
4464 /// We are trying to inject an anonymous member into the given scope;
4465 /// check if there's an existing declaration that can't be overloaded.
4466 ///
4467 /// \return true if this is a forbidden redeclaration
4468 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4469                                          Scope *S,
4470                                          DeclContext *Owner,
4471                                          DeclarationName Name,
4472                                          SourceLocation NameLoc,
4473                                          bool IsUnion) {
4474   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4475                  Sema::ForVisibleRedeclaration);
4476   if (!SemaRef.LookupName(R, S)) return false;
4477
4478   // Pick a representative declaration.
4479   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4480   assert(PrevDecl && "Expected a non-null Decl");
4481
4482   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4483     return false;
4484
4485   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4486     << IsUnion << Name;
4487   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4488
4489   return true;
4490 }
4491
4492 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4493 /// anonymous struct or union AnonRecord into the owning context Owner
4494 /// and scope S. This routine will be invoked just after we realize
4495 /// that an unnamed union or struct is actually an anonymous union or
4496 /// struct, e.g.,
4497 ///
4498 /// @code
4499 /// union {
4500 ///   int i;
4501 ///   float f;
4502 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4503 ///    // f into the surrounding scope.x
4504 /// @endcode
4505 ///
4506 /// This routine is recursive, injecting the names of nested anonymous
4507 /// structs/unions into the owning context and scope as well.
4508 static bool
4509 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4510                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4511                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4512   bool Invalid = false;
4513
4514   // Look every FieldDecl and IndirectFieldDecl with a name.
4515   for (auto *D : AnonRecord->decls()) {
4516     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4517         cast<NamedDecl>(D)->getDeclName()) {
4518       ValueDecl *VD = cast<ValueDecl>(D);
4519       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4520                                        VD->getLocation(),
4521                                        AnonRecord->isUnion())) {
4522         // C++ [class.union]p2:
4523         //   The names of the members of an anonymous union shall be
4524         //   distinct from the names of any other entity in the
4525         //   scope in which the anonymous union is declared.
4526         Invalid = true;
4527       } else {
4528         // C++ [class.union]p2:
4529         //   For the purpose of name lookup, after the anonymous union
4530         //   definition, the members of the anonymous union are
4531         //   considered to have been defined in the scope in which the
4532         //   anonymous union is declared.
4533         unsigned OldChainingSize = Chaining.size();
4534         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4535           Chaining.append(IF->chain_begin(), IF->chain_end());
4536         else
4537           Chaining.push_back(VD);
4538
4539         assert(Chaining.size() >= 2);
4540         NamedDecl **NamedChain =
4541           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4542         for (unsigned i = 0; i < Chaining.size(); i++)
4543           NamedChain[i] = Chaining[i];
4544
4545         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4546             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4547             VD->getType(), {NamedChain, Chaining.size()});
4548
4549         for (const auto *Attr : VD->attrs())
4550           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4551
4552         IndirectField->setAccess(AS);
4553         IndirectField->setImplicit();
4554         SemaRef.PushOnScopeChains(IndirectField, S);
4555
4556         // That includes picking up the appropriate access specifier.
4557         if (AS != AS_none) IndirectField->setAccess(AS);
4558
4559         Chaining.resize(OldChainingSize);
4560       }
4561     }
4562   }
4563
4564   return Invalid;
4565 }
4566
4567 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4568 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4569 /// illegal input values are mapped to SC_None.
4570 static StorageClass
4571 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4572   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4573   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4574          "Parser allowed 'typedef' as storage class VarDecl.");
4575   switch (StorageClassSpec) {
4576   case DeclSpec::SCS_unspecified:    return SC_None;
4577   case DeclSpec::SCS_extern:
4578     if (DS.isExternInLinkageSpec())
4579       return SC_None;
4580     return SC_Extern;
4581   case DeclSpec::SCS_static:         return SC_Static;
4582   case DeclSpec::SCS_auto:           return SC_Auto;
4583   case DeclSpec::SCS_register:       return SC_Register;
4584   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4585     // Illegal SCSs map to None: error reporting is up to the caller.
4586   case DeclSpec::SCS_mutable:        // Fall through.
4587   case DeclSpec::SCS_typedef:        return SC_None;
4588   }
4589   llvm_unreachable("unknown storage class specifier");
4590 }
4591
4592 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4593   assert(Record->hasInClassInitializer());
4594
4595   for (const auto *I : Record->decls()) {
4596     const auto *FD = dyn_cast<FieldDecl>(I);
4597     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4598       FD = IFD->getAnonField();
4599     if (FD && FD->hasInClassInitializer())
4600       return FD->getLocation();
4601   }
4602
4603   llvm_unreachable("couldn't find in-class initializer");
4604 }
4605
4606 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4607                                       SourceLocation DefaultInitLoc) {
4608   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4609     return;
4610
4611   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4612   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4613 }
4614
4615 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4616                                       CXXRecordDecl *AnonUnion) {
4617   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4618     return;
4619
4620   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4621 }
4622
4623 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4624 /// anonymous structure or union. Anonymous unions are a C++ feature
4625 /// (C++ [class.union]) and a C11 feature; anonymous structures
4626 /// are a C11 feature and GNU C++ extension.
4627 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4628                                         AccessSpecifier AS,
4629                                         RecordDecl *Record,
4630                                         const PrintingPolicy &Policy) {
4631   DeclContext *Owner = Record->getDeclContext();
4632
4633   // Diagnose whether this anonymous struct/union is an extension.
4634   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4635     Diag(Record->getLocation(), diag::ext_anonymous_union);
4636   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4637     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4638   else if (!Record->isUnion() && !getLangOpts().C11)
4639     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4640
4641   // C and C++ require different kinds of checks for anonymous
4642   // structs/unions.
4643   bool Invalid = false;
4644   if (getLangOpts().CPlusPlus) {
4645     const char *PrevSpec = nullptr;
4646     unsigned DiagID;
4647     if (Record->isUnion()) {
4648       // C++ [class.union]p6:
4649       // C++17 [class.union.anon]p2:
4650       //   Anonymous unions declared in a named namespace or in the
4651       //   global namespace shall be declared static.
4652       DeclContext *OwnerScope = Owner->getRedeclContext();
4653       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4654           (OwnerScope->isTranslationUnit() ||
4655            (OwnerScope->isNamespace() &&
4656             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4657         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4658           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4659
4660         // Recover by adding 'static'.
4661         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4662                                PrevSpec, DiagID, Policy);
4663       }
4664       // C++ [class.union]p6:
4665       //   A storage class is not allowed in a declaration of an
4666       //   anonymous union in a class scope.
4667       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4668                isa<RecordDecl>(Owner)) {
4669         Diag(DS.getStorageClassSpecLoc(),
4670              diag::err_anonymous_union_with_storage_spec)
4671           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4672
4673         // Recover by removing the storage specifier.
4674         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4675                                SourceLocation(),
4676                                PrevSpec, DiagID, Context.getPrintingPolicy());
4677       }
4678     }
4679
4680     // Ignore const/volatile/restrict qualifiers.
4681     if (DS.getTypeQualifiers()) {
4682       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4683         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4684           << Record->isUnion() << "const"
4685           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4686       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4687         Diag(DS.getVolatileSpecLoc(),
4688              diag::ext_anonymous_struct_union_qualified)
4689           << Record->isUnion() << "volatile"
4690           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4691       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4692         Diag(DS.getRestrictSpecLoc(),
4693              diag::ext_anonymous_struct_union_qualified)
4694           << Record->isUnion() << "restrict"
4695           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4696       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4697         Diag(DS.getAtomicSpecLoc(),
4698              diag::ext_anonymous_struct_union_qualified)
4699           << Record->isUnion() << "_Atomic"
4700           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4701       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4702         Diag(DS.getUnalignedSpecLoc(),
4703              diag::ext_anonymous_struct_union_qualified)
4704           << Record->isUnion() << "__unaligned"
4705           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4706
4707       DS.ClearTypeQualifiers();
4708     }
4709
4710     // C++ [class.union]p2:
4711     //   The member-specification of an anonymous union shall only
4712     //   define non-static data members. [Note: nested types and
4713     //   functions cannot be declared within an anonymous union. ]
4714     for (auto *Mem : Record->decls()) {
4715       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4716         // C++ [class.union]p3:
4717         //   An anonymous union shall not have private or protected
4718         //   members (clause 11).
4719         assert(FD->getAccess() != AS_none);
4720         if (FD->getAccess() != AS_public) {
4721           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4722             << Record->isUnion() << (FD->getAccess() == AS_protected);
4723           Invalid = true;
4724         }
4725
4726         // C++ [class.union]p1
4727         //   An object of a class with a non-trivial constructor, a non-trivial
4728         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4729         //   assignment operator cannot be a member of a union, nor can an
4730         //   array of such objects.
4731         if (CheckNontrivialField(FD))
4732           Invalid = true;
4733       } else if (Mem->isImplicit()) {
4734         // Any implicit members are fine.
4735       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4736         // This is a type that showed up in an
4737         // elaborated-type-specifier inside the anonymous struct or
4738         // union, but which actually declares a type outside of the
4739         // anonymous struct or union. It's okay.
4740       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4741         if (!MemRecord->isAnonymousStructOrUnion() &&
4742             MemRecord->getDeclName()) {
4743           // Visual C++ allows type definition in anonymous struct or union.
4744           if (getLangOpts().MicrosoftExt)
4745             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4746               << Record->isUnion();
4747           else {
4748             // This is a nested type declaration.
4749             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4750               << Record->isUnion();
4751             Invalid = true;
4752           }
4753         } else {
4754           // This is an anonymous type definition within another anonymous type.
4755           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4756           // not part of standard C++.
4757           Diag(MemRecord->getLocation(),
4758                diag::ext_anonymous_record_with_anonymous_type)
4759             << Record->isUnion();
4760         }
4761       } else if (isa<AccessSpecDecl>(Mem)) {
4762         // Any access specifier is fine.
4763       } else if (isa<StaticAssertDecl>(Mem)) {
4764         // In C++1z, static_assert declarations are also fine.
4765       } else {
4766         // We have something that isn't a non-static data
4767         // member. Complain about it.
4768         unsigned DK = diag::err_anonymous_record_bad_member;
4769         if (isa<TypeDecl>(Mem))
4770           DK = diag::err_anonymous_record_with_type;
4771         else if (isa<FunctionDecl>(Mem))
4772           DK = diag::err_anonymous_record_with_function;
4773         else if (isa<VarDecl>(Mem))
4774           DK = diag::err_anonymous_record_with_static;
4775
4776         // Visual C++ allows type definition in anonymous struct or union.
4777         if (getLangOpts().MicrosoftExt &&
4778             DK == diag::err_anonymous_record_with_type)
4779           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4780             << Record->isUnion();
4781         else {
4782           Diag(Mem->getLocation(), DK) << Record->isUnion();
4783           Invalid = true;
4784         }
4785       }
4786     }
4787
4788     // C++11 [class.union]p8 (DR1460):
4789     //   At most one variant member of a union may have a
4790     //   brace-or-equal-initializer.
4791     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4792         Owner->isRecord())
4793       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4794                                 cast<CXXRecordDecl>(Record));
4795   }
4796
4797   if (!Record->isUnion() && !Owner->isRecord()) {
4798     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4799       << getLangOpts().CPlusPlus;
4800     Invalid = true;
4801   }
4802
4803   // Mock up a declarator.
4804   Declarator Dc(DS, DeclaratorContext::MemberContext);
4805   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4806   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4807
4808   // Create a declaration for this anonymous struct/union.
4809   NamedDecl *Anon = nullptr;
4810   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4811     Anon = FieldDecl::Create(Context, OwningClass,
4812                              DS.getLocStart(),
4813                              Record->getLocation(),
4814                              /*IdentifierInfo=*/nullptr,
4815                              Context.getTypeDeclType(Record),
4816                              TInfo,
4817                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4818                              /*InitStyle=*/ICIS_NoInit);
4819     Anon->setAccess(AS);
4820     if (getLangOpts().CPlusPlus)
4821       FieldCollector->Add(cast<FieldDecl>(Anon));
4822   } else {
4823     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4824     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4825     if (SCSpec == DeclSpec::SCS_mutable) {
4826       // mutable can only appear on non-static class members, so it's always
4827       // an error here
4828       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4829       Invalid = true;
4830       SC = SC_None;
4831     }
4832
4833     Anon = VarDecl::Create(Context, Owner,
4834                            DS.getLocStart(),
4835                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4836                            Context.getTypeDeclType(Record),
4837                            TInfo, SC);
4838
4839     // Default-initialize the implicit variable. This initialization will be
4840     // trivial in almost all cases, except if a union member has an in-class
4841     // initializer:
4842     //   union { int n = 0; };
4843     ActOnUninitializedDecl(Anon);
4844   }
4845   Anon->setImplicit();
4846
4847   // Mark this as an anonymous struct/union type.
4848   Record->setAnonymousStructOrUnion(true);
4849
4850   // Add the anonymous struct/union object to the current
4851   // context. We'll be referencing this object when we refer to one of
4852   // its members.
4853   Owner->addDecl(Anon);
4854
4855   // Inject the members of the anonymous struct/union into the owning
4856   // context and into the identifier resolver chain for name lookup
4857   // purposes.
4858   SmallVector<NamedDecl*, 2> Chain;
4859   Chain.push_back(Anon);
4860
4861   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4862     Invalid = true;
4863
4864   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4865     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4866       Decl *ManglingContextDecl;
4867       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4868               NewVD->getDeclContext(), ManglingContextDecl)) {
4869         Context.setManglingNumber(
4870             NewVD, MCtx->getManglingNumber(
4871                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4872         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4873       }
4874     }
4875   }
4876
4877   if (Invalid)
4878     Anon->setInvalidDecl();
4879
4880   return Anon;
4881 }
4882
4883 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4884 /// Microsoft C anonymous structure.
4885 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4886 /// Example:
4887 ///
4888 /// struct A { int a; };
4889 /// struct B { struct A; int b; };
4890 ///
4891 /// void foo() {
4892 ///   B var;
4893 ///   var.a = 3;
4894 /// }
4895 ///
4896 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4897                                            RecordDecl *Record) {
4898   assert(Record && "expected a record!");
4899
4900   // Mock up a declarator.
4901   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4902   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4903   assert(TInfo && "couldn't build declarator info for anonymous struct");
4904
4905   auto *ParentDecl = cast<RecordDecl>(CurContext);
4906   QualType RecTy = Context.getTypeDeclType(Record);
4907
4908   // Create a declaration for this anonymous struct.
4909   NamedDecl *Anon = FieldDecl::Create(Context,
4910                              ParentDecl,
4911                              DS.getLocStart(),
4912                              DS.getLocStart(),
4913                              /*IdentifierInfo=*/nullptr,
4914                              RecTy,
4915                              TInfo,
4916                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4917                              /*InitStyle=*/ICIS_NoInit);
4918   Anon->setImplicit();
4919
4920   // Add the anonymous struct object to the current context.
4921   CurContext->addDecl(Anon);
4922
4923   // Inject the members of the anonymous struct into the current
4924   // context and into the identifier resolver chain for name lookup
4925   // purposes.
4926   SmallVector<NamedDecl*, 2> Chain;
4927   Chain.push_back(Anon);
4928
4929   RecordDecl *RecordDef = Record->getDefinition();
4930   if (RequireCompleteType(Anon->getLocation(), RecTy,
4931                           diag::err_field_incomplete) ||
4932       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4933                                           AS_none, Chain)) {
4934     Anon->setInvalidDecl();
4935     ParentDecl->setInvalidDecl();
4936   }
4937
4938   return Anon;
4939 }
4940
4941 /// GetNameForDeclarator - Determine the full declaration name for the
4942 /// given Declarator.
4943 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4944   return GetNameFromUnqualifiedId(D.getName());
4945 }
4946
4947 /// Retrieves the declaration name from a parsed unqualified-id.
4948 DeclarationNameInfo
4949 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4950   DeclarationNameInfo NameInfo;
4951   NameInfo.setLoc(Name.StartLocation);
4952
4953   switch (Name.getKind()) {
4954
4955   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4956   case UnqualifiedIdKind::IK_Identifier:
4957     NameInfo.setName(Name.Identifier);
4958     NameInfo.setLoc(Name.StartLocation);
4959     return NameInfo;
4960
4961   case UnqualifiedIdKind::IK_DeductionGuideName: {
4962     // C++ [temp.deduct.guide]p3:
4963     //   The simple-template-id shall name a class template specialization.
4964     //   The template-name shall be the same identifier as the template-name
4965     //   of the simple-template-id.
4966     // These together intend to imply that the template-name shall name a
4967     // class template.
4968     // FIXME: template<typename T> struct X {};
4969     //        template<typename T> using Y = X<T>;
4970     //        Y(int) -> Y<int>;
4971     //   satisfies these rules but does not name a class template.
4972     TemplateName TN = Name.TemplateName.get().get();
4973     auto *Template = TN.getAsTemplateDecl();
4974     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4975       Diag(Name.StartLocation,
4976            diag::err_deduction_guide_name_not_class_template)
4977         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4978       if (Template)
4979         Diag(Template->getLocation(), diag::note_template_decl_here);
4980       return DeclarationNameInfo();
4981     }
4982
4983     NameInfo.setName(
4984         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4985     NameInfo.setLoc(Name.StartLocation);
4986     return NameInfo;
4987   }
4988
4989   case UnqualifiedIdKind::IK_OperatorFunctionId:
4990     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4991                                            Name.OperatorFunctionId.Operator));
4992     NameInfo.setLoc(Name.StartLocation);
4993     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4994       = Name.OperatorFunctionId.SymbolLocations[0];
4995     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4996       = Name.EndLocation.getRawEncoding();
4997     return NameInfo;
4998
4999   case UnqualifiedIdKind::IK_LiteralOperatorId:
5000     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5001                                                            Name.Identifier));
5002     NameInfo.setLoc(Name.StartLocation);
5003     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5004     return NameInfo;
5005
5006   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5007     TypeSourceInfo *TInfo;
5008     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5009     if (Ty.isNull())
5010       return DeclarationNameInfo();
5011     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5012                                                Context.getCanonicalType(Ty)));
5013     NameInfo.setLoc(Name.StartLocation);
5014     NameInfo.setNamedTypeInfo(TInfo);
5015     return NameInfo;
5016   }
5017
5018   case UnqualifiedIdKind::IK_ConstructorName: {
5019     TypeSourceInfo *TInfo;
5020     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5021     if (Ty.isNull())
5022       return DeclarationNameInfo();
5023     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5024                                               Context.getCanonicalType(Ty)));
5025     NameInfo.setLoc(Name.StartLocation);
5026     NameInfo.setNamedTypeInfo(TInfo);
5027     return NameInfo;
5028   }
5029
5030   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5031     // In well-formed code, we can only have a constructor
5032     // template-id that refers to the current context, so go there
5033     // to find the actual type being constructed.
5034     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5035     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5036       return DeclarationNameInfo();
5037
5038     // Determine the type of the class being constructed.
5039     QualType CurClassType = Context.getTypeDeclType(CurClass);
5040
5041     // FIXME: Check two things: that the template-id names the same type as
5042     // CurClassType, and that the template-id does not occur when the name
5043     // was qualified.
5044
5045     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5046                                     Context.getCanonicalType(CurClassType)));
5047     NameInfo.setLoc(Name.StartLocation);
5048     // FIXME: should we retrieve TypeSourceInfo?
5049     NameInfo.setNamedTypeInfo(nullptr);
5050     return NameInfo;
5051   }
5052
5053   case UnqualifiedIdKind::IK_DestructorName: {
5054     TypeSourceInfo *TInfo;
5055     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5056     if (Ty.isNull())
5057       return DeclarationNameInfo();
5058     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5059                                               Context.getCanonicalType(Ty)));
5060     NameInfo.setLoc(Name.StartLocation);
5061     NameInfo.setNamedTypeInfo(TInfo);
5062     return NameInfo;
5063   }
5064
5065   case UnqualifiedIdKind::IK_TemplateId: {
5066     TemplateName TName = Name.TemplateId->Template.get();
5067     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5068     return Context.getNameForTemplate(TName, TNameLoc);
5069   }
5070
5071   } // switch (Name.getKind())
5072
5073   llvm_unreachable("Unknown name kind");
5074 }
5075
5076 static QualType getCoreType(QualType Ty) {
5077   do {
5078     if (Ty->isPointerType() || Ty->isReferenceType())
5079       Ty = Ty->getPointeeType();
5080     else if (Ty->isArrayType())
5081       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5082     else
5083       return Ty.withoutLocalFastQualifiers();
5084   } while (true);
5085 }
5086
5087 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5088 /// and Definition have "nearly" matching parameters. This heuristic is
5089 /// used to improve diagnostics in the case where an out-of-line function
5090 /// definition doesn't match any declaration within the class or namespace.
5091 /// Also sets Params to the list of indices to the parameters that differ
5092 /// between the declaration and the definition. If hasSimilarParameters
5093 /// returns true and Params is empty, then all of the parameters match.
5094 static bool hasSimilarParameters(ASTContext &Context,
5095                                      FunctionDecl *Declaration,
5096                                      FunctionDecl *Definition,
5097                                      SmallVectorImpl<unsigned> &Params) {
5098   Params.clear();
5099   if (Declaration->param_size() != Definition->param_size())
5100     return false;
5101   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5102     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5103     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5104
5105     // The parameter types are identical
5106     if (Context.hasSameType(DefParamTy, DeclParamTy))
5107       continue;
5108
5109     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5110     QualType DefParamBaseTy = getCoreType(DefParamTy);
5111     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5112     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5113
5114     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5115         (DeclTyName && DeclTyName == DefTyName))
5116       Params.push_back(Idx);
5117     else  // The two parameters aren't even close
5118       return false;
5119   }
5120
5121   return true;
5122 }
5123
5124 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5125 /// declarator needs to be rebuilt in the current instantiation.
5126 /// Any bits of declarator which appear before the name are valid for
5127 /// consideration here.  That's specifically the type in the decl spec
5128 /// and the base type in any member-pointer chunks.
5129 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5130                                                     DeclarationName Name) {
5131   // The types we specifically need to rebuild are:
5132   //   - typenames, typeofs, and decltypes
5133   //   - types which will become injected class names
5134   // Of course, we also need to rebuild any type referencing such a
5135   // type.  It's safest to just say "dependent", but we call out a
5136   // few cases here.
5137
5138   DeclSpec &DS = D.getMutableDeclSpec();
5139   switch (DS.getTypeSpecType()) {
5140   case DeclSpec::TST_typename:
5141   case DeclSpec::TST_typeofType:
5142   case DeclSpec::TST_underlyingType:
5143   case DeclSpec::TST_atomic: {
5144     // Grab the type from the parser.
5145     TypeSourceInfo *TSI = nullptr;
5146     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5147     if (T.isNull() || !T->isDependentType()) break;
5148
5149     // Make sure there's a type source info.  This isn't really much
5150     // of a waste; most dependent types should have type source info
5151     // attached already.
5152     if (!TSI)
5153       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5154
5155     // Rebuild the type in the current instantiation.
5156     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5157     if (!TSI) return true;
5158
5159     // Store the new type back in the decl spec.
5160     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5161     DS.UpdateTypeRep(LocType);
5162     break;
5163   }
5164
5165   case DeclSpec::TST_decltype:
5166   case DeclSpec::TST_typeofExpr: {
5167     Expr *E = DS.getRepAsExpr();
5168     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5169     if (Result.isInvalid()) return true;
5170     DS.UpdateExprRep(Result.get());
5171     break;
5172   }
5173
5174   default:
5175     // Nothing to do for these decl specs.
5176     break;
5177   }
5178
5179   // It doesn't matter what order we do this in.
5180   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5181     DeclaratorChunk &Chunk = D.getTypeObject(I);
5182
5183     // The only type information in the declarator which can come
5184     // before the declaration name is the base type of a member
5185     // pointer.
5186     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5187       continue;
5188
5189     // Rebuild the scope specifier in-place.
5190     CXXScopeSpec &SS = Chunk.Mem.Scope();
5191     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5192       return true;
5193   }
5194
5195   return false;
5196 }
5197
5198 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5199   D.setFunctionDefinitionKind(FDK_Declaration);
5200   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5201
5202   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5203       Dcl && Dcl->getDeclContext()->isFileContext())
5204     Dcl->setTopLevelDeclInObjCContainer();
5205
5206   if (getLangOpts().OpenCL)
5207     setCurrentOpenCLExtensionForDecl(Dcl);
5208
5209   return Dcl;
5210 }
5211
5212 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5213 ///   If T is the name of a class, then each of the following shall have a
5214 ///   name different from T:
5215 ///     - every static data member of class T;
5216 ///     - every member function of class T
5217 ///     - every member of class T that is itself a type;
5218 /// \returns true if the declaration name violates these rules.
5219 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5220                                    DeclarationNameInfo NameInfo) {
5221   DeclarationName Name = NameInfo.getName();
5222
5223   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5224   while (Record && Record->isAnonymousStructOrUnion())
5225     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5226   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5227     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5228     return true;
5229   }
5230
5231   return false;
5232 }
5233
5234 /// Diagnose a declaration whose declarator-id has the given
5235 /// nested-name-specifier.
5236 ///
5237 /// \param SS The nested-name-specifier of the declarator-id.
5238 ///
5239 /// \param DC The declaration context to which the nested-name-specifier
5240 /// resolves.
5241 ///
5242 /// \param Name The name of the entity being declared.
5243 ///
5244 /// \param Loc The location of the name of the entity being declared.
5245 ///
5246 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5247 /// we're declaring an explicit / partial specialization / instantiation.
5248 ///
5249 /// \returns true if we cannot safely recover from this error, false otherwise.
5250 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5251                                         DeclarationName Name,
5252                                         SourceLocation Loc, bool IsTemplateId) {
5253   DeclContext *Cur = CurContext;
5254   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5255     Cur = Cur->getParent();
5256
5257   // If the user provided a superfluous scope specifier that refers back to the
5258   // class in which the entity is already declared, diagnose and ignore it.
5259   //
5260   // class X {
5261   //   void X::f();
5262   // };
5263   //
5264   // Note, it was once ill-formed to give redundant qualification in all
5265   // contexts, but that rule was removed by DR482.
5266   if (Cur->Equals(DC)) {
5267     if (Cur->isRecord()) {
5268       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5269                                       : diag::err_member_extra_qualification)
5270         << Name << FixItHint::CreateRemoval(SS.getRange());
5271       SS.clear();
5272     } else {
5273       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5274     }
5275     return false;
5276   }
5277
5278   // Check whether the qualifying scope encloses the scope of the original
5279   // declaration. For a template-id, we perform the checks in
5280   // CheckTemplateSpecializationScope.
5281   if (!Cur->Encloses(DC) && !IsTemplateId) {
5282     if (Cur->isRecord())
5283       Diag(Loc, diag::err_member_qualification)
5284         << Name << SS.getRange();
5285     else if (isa<TranslationUnitDecl>(DC))
5286       Diag(Loc, diag::err_invalid_declarator_global_scope)
5287         << Name << SS.getRange();
5288     else if (isa<FunctionDecl>(Cur))
5289       Diag(Loc, diag::err_invalid_declarator_in_function)
5290         << Name << SS.getRange();
5291     else if (isa<BlockDecl>(Cur))
5292       Diag(Loc, diag::err_invalid_declarator_in_block)
5293         << Name << SS.getRange();
5294     else
5295       Diag(Loc, diag::err_invalid_declarator_scope)
5296       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5297
5298     return true;
5299   }
5300
5301   if (Cur->isRecord()) {
5302     // Cannot qualify members within a class.
5303     Diag(Loc, diag::err_member_qualification)
5304       << Name << SS.getRange();
5305     SS.clear();
5306
5307     // C++ constructors and destructors with incorrect scopes can break
5308     // our AST invariants by having the wrong underlying types. If
5309     // that's the case, then drop this declaration entirely.
5310     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5311          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5312         !Context.hasSameType(Name.getCXXNameType(),
5313                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5314       return true;
5315
5316     return false;
5317   }
5318
5319   // C++11 [dcl.meaning]p1:
5320   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5321   //   not begin with a decltype-specifer"
5322   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5323   while (SpecLoc.getPrefix())
5324     SpecLoc = SpecLoc.getPrefix();
5325   if (dyn_cast_or_null<DecltypeType>(
5326         SpecLoc.getNestedNameSpecifier()->getAsType()))
5327     Diag(Loc, diag::err_decltype_in_declarator)
5328       << SpecLoc.getTypeLoc().getSourceRange();
5329
5330   return false;
5331 }
5332
5333 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5334                                   MultiTemplateParamsArg TemplateParamLists) {
5335   // TODO: consider using NameInfo for diagnostic.
5336   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5337   DeclarationName Name = NameInfo.getName();
5338
5339   // All of these full declarators require an identifier.  If it doesn't have
5340   // one, the ParsedFreeStandingDeclSpec action should be used.
5341   if (D.isDecompositionDeclarator()) {
5342     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5343   } else if (!Name) {
5344     if (!D.isInvalidType())  // Reject this if we think it is valid.
5345       Diag(D.getDeclSpec().getLocStart(),
5346            diag::err_declarator_need_ident)
5347         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5348     return nullptr;
5349   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5350     return nullptr;
5351
5352   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5353   // we find one that is.
5354   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5355          (S->getFlags() & Scope::TemplateParamScope) != 0)
5356     S = S->getParent();
5357
5358   DeclContext *DC = CurContext;
5359   if (D.getCXXScopeSpec().isInvalid())
5360     D.setInvalidType();
5361   else if (D.getCXXScopeSpec().isSet()) {
5362     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5363                                         UPPC_DeclarationQualifier))
5364       return nullptr;
5365
5366     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5367     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5368     if (!DC || isa<EnumDecl>(DC)) {
5369       // If we could not compute the declaration context, it's because the
5370       // declaration context is dependent but does not refer to a class,
5371       // class template, or class template partial specialization. Complain
5372       // and return early, to avoid the coming semantic disaster.
5373       Diag(D.getIdentifierLoc(),
5374            diag::err_template_qualified_declarator_no_match)
5375         << D.getCXXScopeSpec().getScopeRep()
5376         << D.getCXXScopeSpec().getRange();
5377       return nullptr;
5378     }
5379     bool IsDependentContext = DC->isDependentContext();
5380
5381     if (!IsDependentContext &&
5382         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5383       return nullptr;
5384
5385     // If a class is incomplete, do not parse entities inside it.
5386     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5387       Diag(D.getIdentifierLoc(),
5388            diag::err_member_def_undefined_record)
5389         << Name << DC << D.getCXXScopeSpec().getRange();
5390       return nullptr;
5391     }
5392     if (!D.getDeclSpec().isFriendSpecified()) {
5393       if (diagnoseQualifiedDeclaration(
5394               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5395               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5396         if (DC->isRecord())
5397           return nullptr;
5398
5399         D.setInvalidType();
5400       }
5401     }
5402
5403     // Check whether we need to rebuild the type of the given
5404     // declaration in the current instantiation.
5405     if (EnteringContext && IsDependentContext &&
5406         TemplateParamLists.size() != 0) {
5407       ContextRAII SavedContext(*this, DC);
5408       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5409         D.setInvalidType();
5410     }
5411   }
5412
5413   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5414   QualType R = TInfo->getType();
5415
5416   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5417                                       UPPC_DeclarationType))
5418     D.setInvalidType();
5419
5420   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5421                         forRedeclarationInCurContext());
5422
5423   // See if this is a redefinition of a variable in the same scope.
5424   if (!D.getCXXScopeSpec().isSet()) {
5425     bool IsLinkageLookup = false;
5426     bool CreateBuiltins = false;
5427
5428     // If the declaration we're planning to build will be a function
5429     // or object with linkage, then look for another declaration with
5430     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5431     //
5432     // If the declaration we're planning to build will be declared with
5433     // external linkage in the translation unit, create any builtin with
5434     // the same name.
5435     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5436       /* Do nothing*/;
5437     else if (CurContext->isFunctionOrMethod() &&
5438              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5439               R->isFunctionType())) {
5440       IsLinkageLookup = true;
5441       CreateBuiltins =
5442           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5443     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5444                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5445       CreateBuiltins = true;
5446
5447     if (IsLinkageLookup) {
5448       Previous.clear(LookupRedeclarationWithLinkage);
5449       Previous.setRedeclarationKind(ForExternalRedeclaration);
5450     }
5451
5452     LookupName(Previous, S, CreateBuiltins);
5453   } else { // Something like "int foo::x;"
5454     LookupQualifiedName(Previous, DC);
5455
5456     // C++ [dcl.meaning]p1:
5457     //   When the declarator-id is qualified, the declaration shall refer to a
5458     //  previously declared member of the class or namespace to which the
5459     //  qualifier refers (or, in the case of a namespace, of an element of the
5460     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5461     //  thereof; [...]
5462     //
5463     // Note that we already checked the context above, and that we do not have
5464     // enough information to make sure that Previous contains the declaration
5465     // we want to match. For example, given:
5466     //
5467     //   class X {
5468     //     void f();
5469     //     void f(float);
5470     //   };
5471     //
5472     //   void X::f(int) { } // ill-formed
5473     //
5474     // In this case, Previous will point to the overload set
5475     // containing the two f's declared in X, but neither of them
5476     // matches.
5477
5478     // C++ [dcl.meaning]p1:
5479     //   [...] the member shall not merely have been introduced by a
5480     //   using-declaration in the scope of the class or namespace nominated by
5481     //   the nested-name-specifier of the declarator-id.
5482     RemoveUsingDecls(Previous);
5483   }
5484
5485   if (Previous.isSingleResult() &&
5486       Previous.getFoundDecl()->isTemplateParameter()) {
5487     // Maybe we will complain about the shadowed template parameter.
5488     if (!D.isInvalidType())
5489       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5490                                       Previous.getFoundDecl());
5491
5492     // Just pretend that we didn't see the previous declaration.
5493     Previous.clear();
5494   }
5495
5496   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5497     // Forget that the previous declaration is the injected-class-name.
5498     Previous.clear();
5499
5500   // In C++, the previous declaration we find might be a tag type
5501   // (class or enum). In this case, the new declaration will hide the
5502   // tag type. Note that this applies to functions, function templates, and
5503   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5504   if (Previous.isSingleTagDecl() &&
5505       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5506       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5507     Previous.clear();
5508
5509   // Check that there are no default arguments other than in the parameters
5510   // of a function declaration (C++ only).
5511   if (getLangOpts().CPlusPlus)
5512     CheckExtraCXXDefaultArguments(D);
5513
5514   NamedDecl *New;
5515
5516   bool AddToScope = true;
5517   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5518     if (TemplateParamLists.size()) {
5519       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5520       return nullptr;
5521     }
5522
5523     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5524   } else if (R->isFunctionType()) {
5525     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5526                                   TemplateParamLists,
5527                                   AddToScope);
5528   } else {
5529     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5530                                   AddToScope);
5531   }
5532
5533   if (!New)
5534     return nullptr;
5535
5536   // If this has an identifier and is not a function template specialization,
5537   // add it to the scope stack.
5538   if (New->getDeclName() && AddToScope) {
5539     // Only make a locally-scoped extern declaration visible if it is the first
5540     // declaration of this entity. Qualified lookup for such an entity should
5541     // only find this declaration if there is no visible declaration of it.
5542     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5543     PushOnScopeChains(New, S, AddToContext);
5544     if (!AddToContext)
5545       CurContext->addHiddenDecl(New);
5546   }
5547
5548   if (isInOpenMPDeclareTargetContext())
5549     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5550
5551   return New;
5552 }
5553
5554 /// Helper method to turn variable array types into constant array
5555 /// types in certain situations which would otherwise be errors (for
5556 /// GCC compatibility).
5557 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5558                                                     ASTContext &Context,
5559                                                     bool &SizeIsNegative,
5560                                                     llvm::APSInt &Oversized) {
5561   // This method tries to turn a variable array into a constant
5562   // array even when the size isn't an ICE.  This is necessary
5563   // for compatibility with code that depends on gcc's buggy
5564   // constant expression folding, like struct {char x[(int)(char*)2];}
5565   SizeIsNegative = false;
5566   Oversized = 0;
5567
5568   if (T->isDependentType())
5569     return QualType();
5570
5571   QualifierCollector Qs;
5572   const Type *Ty = Qs.strip(T);
5573
5574   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5575     QualType Pointee = PTy->getPointeeType();
5576     QualType FixedType =
5577         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5578                                             Oversized);
5579     if (FixedType.isNull()) return FixedType;
5580     FixedType = Context.getPointerType(FixedType);
5581     return Qs.apply(Context, FixedType);
5582   }
5583   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5584     QualType Inner = PTy->getInnerType();
5585     QualType FixedType =
5586         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5587                                             Oversized);
5588     if (FixedType.isNull()) return FixedType;
5589     FixedType = Context.getParenType(FixedType);
5590     return Qs.apply(Context, FixedType);
5591   }
5592
5593   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5594   if (!VLATy)
5595     return QualType();
5596   // FIXME: We should probably handle this case
5597   if (VLATy->getElementType()->isVariablyModifiedType())
5598     return QualType();
5599
5600   llvm::APSInt Res;
5601   if (!VLATy->getSizeExpr() ||
5602       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5603     return QualType();
5604
5605   // Check whether the array size is negative.
5606   if (Res.isSigned() && Res.isNegative()) {
5607     SizeIsNegative = true;
5608     return QualType();
5609   }
5610
5611   // Check whether the array is too large to be addressed.
5612   unsigned ActiveSizeBits
5613     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5614                                               Res);
5615   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5616     Oversized = Res;
5617     return QualType();
5618   }
5619
5620   return Context.getConstantArrayType(VLATy->getElementType(),
5621                                       Res, ArrayType::Normal, 0);
5622 }
5623
5624 static void
5625 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5626   SrcTL = SrcTL.getUnqualifiedLoc();
5627   DstTL = DstTL.getUnqualifiedLoc();
5628   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5629     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5630     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5631                                       DstPTL.getPointeeLoc());
5632     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5633     return;
5634   }
5635   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5636     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5637     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5638                                       DstPTL.getInnerLoc());
5639     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5640     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5641     return;
5642   }
5643   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5644   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5645   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5646   TypeLoc DstElemTL = DstATL.getElementLoc();
5647   DstElemTL.initializeFullCopy(SrcElemTL);
5648   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5649   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5650   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5651 }
5652
5653 /// Helper method to turn variable array types into constant array
5654 /// types in certain situations which would otherwise be errors (for
5655 /// GCC compatibility).
5656 static TypeSourceInfo*
5657 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5658                                               ASTContext &Context,
5659                                               bool &SizeIsNegative,
5660                                               llvm::APSInt &Oversized) {
5661   QualType FixedTy
5662     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5663                                           SizeIsNegative, Oversized);
5664   if (FixedTy.isNull())
5665     return nullptr;
5666   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5667   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5668                                     FixedTInfo->getTypeLoc());
5669   return FixedTInfo;
5670 }
5671
5672 /// Register the given locally-scoped extern "C" declaration so
5673 /// that it can be found later for redeclarations. We include any extern "C"
5674 /// declaration that is not visible in the translation unit here, not just
5675 /// function-scope declarations.
5676 void
5677 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5678   if (!getLangOpts().CPlusPlus &&
5679       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5680     // Don't need to track declarations in the TU in C.
5681     return;
5682
5683   // Note that we have a locally-scoped external with this name.
5684   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5685 }
5686
5687 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5688   // FIXME: We can have multiple results via __attribute__((overloadable)).
5689   auto Result = Context.getExternCContextDecl()->lookup(Name);
5690   return Result.empty() ? nullptr : *Result.begin();
5691 }
5692
5693 /// Diagnose function specifiers on a declaration of an identifier that
5694 /// does not identify a function.
5695 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5696   // FIXME: We should probably indicate the identifier in question to avoid
5697   // confusion for constructs like "virtual int a(), b;"
5698   if (DS.isVirtualSpecified())
5699     Diag(DS.getVirtualSpecLoc(),
5700          diag::err_virtual_non_function);
5701
5702   if (DS.isExplicitSpecified())
5703     Diag(DS.getExplicitSpecLoc(),
5704          diag::err_explicit_non_function);
5705
5706   if (DS.isNoreturnSpecified())
5707     Diag(DS.getNoreturnSpecLoc(),
5708          diag::err_noreturn_non_function);
5709 }
5710
5711 NamedDecl*
5712 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5713                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5714   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5715   if (D.getCXXScopeSpec().isSet()) {
5716     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5717       << D.getCXXScopeSpec().getRange();
5718     D.setInvalidType();
5719     // Pretend we didn't see the scope specifier.
5720     DC = CurContext;
5721     Previous.clear();
5722   }
5723
5724   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5725
5726   if (D.getDeclSpec().isInlineSpecified())
5727     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5728         << getLangOpts().CPlusPlus17;
5729   if (D.getDeclSpec().isConstexprSpecified())
5730     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5731       << 1;
5732
5733   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5734     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5735       Diag(D.getName().StartLocation,
5736            diag::err_deduction_guide_invalid_specifier)
5737           << "typedef";
5738     else
5739       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5740           << D.getName().getSourceRange();
5741     return nullptr;
5742   }
5743
5744   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5745   if (!NewTD) return nullptr;
5746
5747   // Handle attributes prior to checking for duplicates in MergeVarDecl
5748   ProcessDeclAttributes(S, NewTD, D);
5749
5750   CheckTypedefForVariablyModifiedType(S, NewTD);
5751
5752   bool Redeclaration = D.isRedeclaration();
5753   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5754   D.setRedeclaration(Redeclaration);
5755   return ND;
5756 }
5757
5758 void
5759 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5760   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5761   // then it shall have block scope.
5762   // Note that variably modified types must be fixed before merging the decl so
5763   // that redeclarations will match.
5764   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5765   QualType T = TInfo->getType();
5766   if (T->isVariablyModifiedType()) {
5767     setFunctionHasBranchProtectedScope();
5768
5769     if (S->getFnParent() == nullptr) {
5770       bool SizeIsNegative;
5771       llvm::APSInt Oversized;
5772       TypeSourceInfo *FixedTInfo =
5773         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5774                                                       SizeIsNegative,
5775                                                       Oversized);
5776       if (FixedTInfo) {
5777         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5778         NewTD->setTypeSourceInfo(FixedTInfo);
5779       } else {
5780         if (SizeIsNegative)
5781           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5782         else if (T->isVariableArrayType())
5783           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5784         else if (Oversized.getBoolValue())
5785           Diag(NewTD->getLocation(), diag::err_array_too_large)
5786             << Oversized.toString(10);
5787         else
5788           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5789         NewTD->setInvalidDecl();
5790       }
5791     }
5792   }
5793 }
5794
5795 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5796 /// declares a typedef-name, either using the 'typedef' type specifier or via
5797 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5798 NamedDecl*
5799 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5800                            LookupResult &Previous, bool &Redeclaration) {
5801
5802   // Find the shadowed declaration before filtering for scope.
5803   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5804
5805   // Merge the decl with the existing one if appropriate. If the decl is
5806   // in an outer scope, it isn't the same thing.
5807   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5808                        /*AllowInlineNamespace*/false);
5809   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5810   if (!Previous.empty()) {
5811     Redeclaration = true;
5812     MergeTypedefNameDecl(S, NewTD, Previous);
5813   }
5814
5815   if (ShadowedDecl && !Redeclaration)
5816     CheckShadow(NewTD, ShadowedDecl, Previous);
5817
5818   // If this is the C FILE type, notify the AST context.
5819   if (IdentifierInfo *II = NewTD->getIdentifier())
5820     if (!NewTD->isInvalidDecl() &&
5821         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5822       if (II->isStr("FILE"))
5823         Context.setFILEDecl(NewTD);
5824       else if (II->isStr("jmp_buf"))
5825         Context.setjmp_bufDecl(NewTD);
5826       else if (II->isStr("sigjmp_buf"))
5827         Context.setsigjmp_bufDecl(NewTD);
5828       else if (II->isStr("ucontext_t"))
5829         Context.setucontext_tDecl(NewTD);
5830     }
5831
5832   return NewTD;
5833 }
5834
5835 /// Determines whether the given declaration is an out-of-scope
5836 /// previous declaration.
5837 ///
5838 /// This routine should be invoked when name lookup has found a
5839 /// previous declaration (PrevDecl) that is not in the scope where a
5840 /// new declaration by the same name is being introduced. If the new
5841 /// declaration occurs in a local scope, previous declarations with
5842 /// linkage may still be considered previous declarations (C99
5843 /// 6.2.2p4-5, C++ [basic.link]p6).
5844 ///
5845 /// \param PrevDecl the previous declaration found by name
5846 /// lookup
5847 ///
5848 /// \param DC the context in which the new declaration is being
5849 /// declared.
5850 ///
5851 /// \returns true if PrevDecl is an out-of-scope previous declaration
5852 /// for a new delcaration with the same name.
5853 static bool
5854 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5855                                 ASTContext &Context) {
5856   if (!PrevDecl)
5857     return false;
5858
5859   if (!PrevDecl->hasLinkage())
5860     return false;
5861
5862   if (Context.getLangOpts().CPlusPlus) {
5863     // C++ [basic.link]p6:
5864     //   If there is a visible declaration of an entity with linkage
5865     //   having the same name and type, ignoring entities declared
5866     //   outside the innermost enclosing namespace scope, the block
5867     //   scope declaration declares that same entity and receives the
5868     //   linkage of the previous declaration.
5869     DeclContext *OuterContext = DC->getRedeclContext();
5870     if (!OuterContext->isFunctionOrMethod())
5871       // This rule only applies to block-scope declarations.
5872       return false;
5873
5874     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5875     if (PrevOuterContext->isRecord())
5876       // We found a member function: ignore it.
5877       return false;
5878
5879     // Find the innermost enclosing namespace for the new and
5880     // previous declarations.
5881     OuterContext = OuterContext->getEnclosingNamespaceContext();
5882     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5883
5884     // The previous declaration is in a different namespace, so it
5885     // isn't the same function.
5886     if (!OuterContext->Equals(PrevOuterContext))
5887       return false;
5888   }
5889
5890   return true;
5891 }
5892
5893 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5894   CXXScopeSpec &SS = D.getCXXScopeSpec();
5895   if (!SS.isSet()) return;
5896   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5897 }
5898
5899 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5900   QualType type = decl->getType();
5901   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5902   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5903     // Various kinds of declaration aren't allowed to be __autoreleasing.
5904     unsigned kind = -1U;
5905     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5906       if (var->hasAttr<BlocksAttr>())
5907         kind = 0; // __block
5908       else if (!var->hasLocalStorage())
5909         kind = 1; // global
5910     } else if (isa<ObjCIvarDecl>(decl)) {
5911       kind = 3; // ivar
5912     } else if (isa<FieldDecl>(decl)) {
5913       kind = 2; // field
5914     }
5915
5916     if (kind != -1U) {
5917       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5918         << kind;
5919     }
5920   } else if (lifetime == Qualifiers::OCL_None) {
5921     // Try to infer lifetime.
5922     if (!type->isObjCLifetimeType())
5923       return false;
5924
5925     lifetime = type->getObjCARCImplicitLifetime();
5926     type = Context.getLifetimeQualifiedType(type, lifetime);
5927     decl->setType(type);
5928   }
5929
5930   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5931     // Thread-local variables cannot have lifetime.
5932     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5933         var->getTLSKind()) {
5934       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5935         << var->getType();
5936       return true;
5937     }
5938   }
5939
5940   return false;
5941 }
5942
5943 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5944   // Ensure that an auto decl is deduced otherwise the checks below might cache
5945   // the wrong linkage.
5946   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5947
5948   // 'weak' only applies to declarations with external linkage.
5949   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5950     if (!ND.isExternallyVisible()) {
5951       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5952       ND.dropAttr<WeakAttr>();
5953     }
5954   }
5955   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5956     if (ND.isExternallyVisible()) {
5957       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5958       ND.dropAttr<WeakRefAttr>();
5959       ND.dropAttr<AliasAttr>();
5960     }
5961   }
5962
5963   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5964     if (VD->hasInit()) {
5965       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5966         assert(VD->isThisDeclarationADefinition() &&
5967                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5968         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5969         VD->dropAttr<AliasAttr>();
5970       }
5971     }
5972   }
5973
5974   // 'selectany' only applies to externally visible variable declarations.
5975   // It does not apply to functions.
5976   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5977     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5978       S.Diag(Attr->getLocation(),
5979              diag::err_attribute_selectany_non_extern_data);
5980       ND.dropAttr<SelectAnyAttr>();
5981     }
5982   }
5983
5984   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5985     // dll attributes require external linkage. Static locals may have external
5986     // linkage but still cannot be explicitly imported or exported.
5987     auto *VD = dyn_cast<VarDecl>(&ND);
5988     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5989       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5990         << &ND << Attr;
5991       ND.setInvalidDecl();
5992     }
5993   }
5994
5995   // Virtual functions cannot be marked as 'notail'.
5996   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5997     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5998       if (MD->isVirtual()) {
5999         S.Diag(ND.getLocation(),
6000                diag::err_invalid_attribute_on_virtual_function)
6001             << Attr;
6002         ND.dropAttr<NotTailCalledAttr>();
6003       }
6004
6005   // Check the attributes on the function type, if any.
6006   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6007     // Don't declare this variable in the second operand of the for-statement;
6008     // GCC miscompiles that by ending its lifetime before evaluating the
6009     // third operand. See gcc.gnu.org/PR86769.
6010     AttributedTypeLoc ATL;
6011     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6012          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6013          TL = ATL.getModifiedLoc()) {
6014       // The [[lifetimebound]] attribute can be applied to the implicit object
6015       // parameter of a non-static member function (other than a ctor or dtor)
6016       // by applying it to the function type.
6017       if (ATL.getAttrKind() == AttributedType::attr_lifetimebound) {
6018         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6019         if (!MD || MD->isStatic()) {
6020           S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_no_object_param)
6021               << !MD << ATL.getLocalSourceRange();
6022         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6023           S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_ctor_dtor)
6024               << isa<CXXDestructorDecl>(MD) << ATL.getLocalSourceRange();
6025         }
6026       }
6027     }
6028   }
6029 }
6030
6031 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6032                                            NamedDecl *NewDecl,
6033                                            bool IsSpecialization,
6034                                            bool IsDefinition) {
6035   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6036     return;
6037
6038   bool IsTemplate = false;
6039   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6040     OldDecl = OldTD->getTemplatedDecl();
6041     IsTemplate = true;
6042     if (!IsSpecialization)
6043       IsDefinition = false;
6044   }
6045   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6046     NewDecl = NewTD->getTemplatedDecl();
6047     IsTemplate = true;
6048   }
6049
6050   if (!OldDecl || !NewDecl)
6051     return;
6052
6053   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6054   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6055   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6056   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6057
6058   // dllimport and dllexport are inheritable attributes so we have to exclude
6059   // inherited attribute instances.
6060   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6061                     (NewExportAttr && !NewExportAttr->isInherited());
6062
6063   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6064   // the only exception being explicit specializations.
6065   // Implicitly generated declarations are also excluded for now because there
6066   // is no other way to switch these to use dllimport or dllexport.
6067   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6068
6069   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6070     // Allow with a warning for free functions and global variables.
6071     bool JustWarn = false;
6072     if (!OldDecl->isCXXClassMember()) {
6073       auto *VD = dyn_cast<VarDecl>(OldDecl);
6074       if (VD && !VD->getDescribedVarTemplate())
6075         JustWarn = true;
6076       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6077       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6078         JustWarn = true;
6079     }
6080
6081     // We cannot change a declaration that's been used because IR has already
6082     // been emitted. Dllimported functions will still work though (modulo
6083     // address equality) as they can use the thunk.
6084     if (OldDecl->isUsed())
6085       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6086         JustWarn = false;
6087
6088     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6089                                : diag::err_attribute_dll_redeclaration;
6090     S.Diag(NewDecl->getLocation(), DiagID)
6091         << NewDecl
6092         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6093     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6094     if (!JustWarn) {
6095       NewDecl->setInvalidDecl();
6096       return;
6097     }
6098   }
6099
6100   // A redeclaration is not allowed to drop a dllimport attribute, the only
6101   // exceptions being inline function definitions (except for function
6102   // templates), local extern declarations, qualified friend declarations or
6103   // special MSVC extension: in the last case, the declaration is treated as if
6104   // it were marked dllexport.
6105   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6106   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6107   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6108     // Ignore static data because out-of-line definitions are diagnosed
6109     // separately.
6110     IsStaticDataMember = VD->isStaticDataMember();
6111     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6112                    VarDecl::DeclarationOnly;
6113   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6114     IsInline = FD->isInlined();
6115     IsQualifiedFriend = FD->getQualifier() &&
6116                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6117   }
6118
6119   if (OldImportAttr && !HasNewAttr &&
6120       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6121       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6122     if (IsMicrosoft && IsDefinition) {
6123       S.Diag(NewDecl->getLocation(),
6124              diag::warn_redeclaration_without_import_attribute)
6125           << NewDecl;
6126       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6127       NewDecl->dropAttr<DLLImportAttr>();
6128       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6129           NewImportAttr->getRange(), S.Context,
6130           NewImportAttr->getSpellingListIndex()));
6131     } else {
6132       S.Diag(NewDecl->getLocation(),
6133              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6134           << NewDecl << OldImportAttr;
6135       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6136       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6137       OldDecl->dropAttr<DLLImportAttr>();
6138       NewDecl->dropAttr<DLLImportAttr>();
6139     }
6140   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6141     // In MinGW, seeing a function declared inline drops the dllimport
6142     // attribute.
6143     OldDecl->dropAttr<DLLImportAttr>();
6144     NewDecl->dropAttr<DLLImportAttr>();
6145     S.Diag(NewDecl->getLocation(),
6146            diag::warn_dllimport_dropped_from_inline_function)
6147         << NewDecl << OldImportAttr;
6148   }
6149
6150   // A specialization of a class template member function is processed here
6151   // since it's a redeclaration. If the parent class is dllexport, the
6152   // specialization inherits that attribute. This doesn't happen automatically
6153   // since the parent class isn't instantiated until later.
6154   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6155     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6156         !NewImportAttr && !NewExportAttr) {
6157       if (const DLLExportAttr *ParentExportAttr =
6158               MD->getParent()->getAttr<DLLExportAttr>()) {
6159         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6160         NewAttr->setInherited(true);
6161         NewDecl->addAttr(NewAttr);
6162       }
6163     }
6164   }
6165 }
6166
6167 /// Given that we are within the definition of the given function,
6168 /// will that definition behave like C99's 'inline', where the
6169 /// definition is discarded except for optimization purposes?
6170 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6171   // Try to avoid calling GetGVALinkageForFunction.
6172
6173   // All cases of this require the 'inline' keyword.
6174   if (!FD->isInlined()) return false;
6175
6176   // This is only possible in C++ with the gnu_inline attribute.
6177   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6178     return false;
6179
6180   // Okay, go ahead and call the relatively-more-expensive function.
6181   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6182 }
6183
6184 /// Determine whether a variable is extern "C" prior to attaching
6185 /// an initializer. We can't just call isExternC() here, because that
6186 /// will also compute and cache whether the declaration is externally
6187 /// visible, which might change when we attach the initializer.
6188 ///
6189 /// This can only be used if the declaration is known to not be a
6190 /// redeclaration of an internal linkage declaration.
6191 ///
6192 /// For instance:
6193 ///
6194 ///   auto x = []{};
6195 ///
6196 /// Attaching the initializer here makes this declaration not externally
6197 /// visible, because its type has internal linkage.
6198 ///
6199 /// FIXME: This is a hack.
6200 template<typename T>
6201 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6202   if (S.getLangOpts().CPlusPlus) {
6203     // In C++, the overloadable attribute negates the effects of extern "C".
6204     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6205       return false;
6206
6207     // So do CUDA's host/device attributes.
6208     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6209                                  D->template hasAttr<CUDAHostAttr>()))
6210       return false;
6211   }
6212   return D->isExternC();
6213 }
6214
6215 static bool shouldConsiderLinkage(const VarDecl *VD) {
6216   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6217   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6218     return VD->hasExternalStorage();
6219   if (DC->isFileContext())
6220     return true;
6221   if (DC->isRecord())
6222     return false;
6223   llvm_unreachable("Unexpected context");
6224 }
6225
6226 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6227   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6228   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6229       isa<OMPDeclareReductionDecl>(DC))
6230     return true;
6231   if (DC->isRecord())
6232     return false;
6233   llvm_unreachable("Unexpected context");
6234 }
6235
6236 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6237                           ParsedAttr::Kind Kind) {
6238   // Check decl attributes on the DeclSpec.
6239   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6240     return true;
6241
6242   // Walk the declarator structure, checking decl attributes that were in a type
6243   // position to the decl itself.
6244   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6245     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6246       return true;
6247   }
6248
6249   // Finally, check attributes on the decl itself.
6250   return PD.getAttributes().hasAttribute(Kind);
6251 }
6252
6253 /// Adjust the \c DeclContext for a function or variable that might be a
6254 /// function-local external declaration.
6255 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6256   if (!DC->isFunctionOrMethod())
6257     return false;
6258
6259   // If this is a local extern function or variable declared within a function
6260   // template, don't add it into the enclosing namespace scope until it is
6261   // instantiated; it might have a dependent type right now.
6262   if (DC->isDependentContext())
6263     return true;
6264
6265   // C++11 [basic.link]p7:
6266   //   When a block scope declaration of an entity with linkage is not found to
6267   //   refer to some other declaration, then that entity is a member of the
6268   //   innermost enclosing namespace.
6269   //
6270   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6271   // semantically-enclosing namespace, not a lexically-enclosing one.
6272   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6273     DC = DC->getParent();
6274   return true;
6275 }
6276
6277 /// Returns true if given declaration has external C language linkage.
6278 static bool isDeclExternC(const Decl *D) {
6279   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6280     return FD->isExternC();
6281   if (const auto *VD = dyn_cast<VarDecl>(D))
6282     return VD->isExternC();
6283
6284   llvm_unreachable("Unknown type of decl!");
6285 }
6286
6287 NamedDecl *Sema::ActOnVariableDeclarator(
6288     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6289     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6290     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6291   QualType R = TInfo->getType();
6292   DeclarationName Name = GetNameForDeclarator(D).getName();
6293
6294   IdentifierInfo *II = Name.getAsIdentifierInfo();
6295
6296   if (D.isDecompositionDeclarator()) {
6297     // Take the name of the first declarator as our name for diagnostic
6298     // purposes.
6299     auto &Decomp = D.getDecompositionDeclarator();
6300     if (!Decomp.bindings().empty()) {
6301       II = Decomp.bindings()[0].Name;
6302       Name = II;
6303     }
6304   } else if (!II) {
6305     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6306     return nullptr;
6307   }
6308
6309   if (getLangOpts().OpenCL) {
6310     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6311     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6312     // argument.
6313     if (R->isImageType() || R->isPipeType()) {
6314       Diag(D.getIdentifierLoc(),
6315            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6316           << R;
6317       D.setInvalidType();
6318       return nullptr;
6319     }
6320
6321     // OpenCL v1.2 s6.9.r:
6322     // The event type cannot be used to declare a program scope variable.
6323     // OpenCL v2.0 s6.9.q:
6324     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6325     if (NULL == S->getParent()) {
6326       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6327         Diag(D.getIdentifierLoc(),
6328              diag::err_invalid_type_for_program_scope_var) << R;
6329         D.setInvalidType();
6330         return nullptr;
6331       }
6332     }
6333
6334     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6335     QualType NR = R;
6336     while (NR->isPointerType()) {
6337       if (NR->isFunctionPointerType()) {
6338         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6339         D.setInvalidType();
6340         break;
6341       }
6342       NR = NR->getPointeeType();
6343     }
6344
6345     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6346       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6347       // half array type (unless the cl_khr_fp16 extension is enabled).
6348       if (Context.getBaseElementType(R)->isHalfType()) {
6349         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6350         D.setInvalidType();
6351       }
6352     }
6353
6354     if (R->isSamplerT()) {
6355       // OpenCL v1.2 s6.9.b p4:
6356       // The sampler type cannot be used with the __local and __global address
6357       // space qualifiers.
6358       if (R.getAddressSpace() == LangAS::opencl_local ||
6359           R.getAddressSpace() == LangAS::opencl_global) {
6360         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6361       }
6362
6363       // OpenCL v1.2 s6.12.14.1:
6364       // A global sampler must be declared with either the constant address
6365       // space qualifier or with the const qualifier.
6366       if (DC->isTranslationUnit() &&
6367           !(R.getAddressSpace() == LangAS::opencl_constant ||
6368           R.isConstQualified())) {
6369         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6370         D.setInvalidType();
6371       }
6372     }
6373
6374     // OpenCL v1.2 s6.9.r:
6375     // The event type cannot be used with the __local, __constant and __global
6376     // address space qualifiers.
6377     if (R->isEventT()) {
6378       if (R.getAddressSpace() != LangAS::opencl_private) {
6379         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6380         D.setInvalidType();
6381       }
6382     }
6383
6384     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6385     // supported.  OpenCL C does not support thread_local either, and
6386     // also reject all other thread storage class specifiers.
6387     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6388     if (TSC != TSCS_unspecified) {
6389       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6390       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6391            diag::err_opencl_unknown_type_specifier)
6392           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6393           << DeclSpec::getSpecifierName(TSC) << 1;
6394       D.setInvalidType();
6395       return nullptr;
6396     }
6397   }
6398
6399   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6400   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6401
6402   // dllimport globals without explicit storage class are treated as extern. We
6403   // have to change the storage class this early to get the right DeclContext.
6404   if (SC == SC_None && !DC->isRecord() &&
6405       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6406       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6407     SC = SC_Extern;
6408
6409   DeclContext *OriginalDC = DC;
6410   bool IsLocalExternDecl = SC == SC_Extern &&
6411                            adjustContextForLocalExternDecl(DC);
6412
6413   if (SCSpec == DeclSpec::SCS_mutable) {
6414     // mutable can only appear on non-static class members, so it's always
6415     // an error here
6416     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6417     D.setInvalidType();
6418     SC = SC_None;
6419   }
6420
6421   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6422       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6423                               D.getDeclSpec().getStorageClassSpecLoc())) {
6424     // In C++11, the 'register' storage class specifier is deprecated.
6425     // Suppress the warning in system macros, it's used in macros in some
6426     // popular C system headers, such as in glibc's htonl() macro.
6427     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6428          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6429                                    : diag::warn_deprecated_register)
6430       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6431   }
6432
6433   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6434
6435   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6436     // C99 6.9p2: The storage-class specifiers auto and register shall not
6437     // appear in the declaration specifiers in an external declaration.
6438     // Global Register+Asm is a GNU extension we support.
6439     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6440       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6441       D.setInvalidType();
6442     }
6443   }
6444
6445   bool IsMemberSpecialization = false;
6446   bool IsVariableTemplateSpecialization = false;
6447   bool IsPartialSpecialization = false;
6448   bool IsVariableTemplate = false;
6449   VarDecl *NewVD = nullptr;
6450   VarTemplateDecl *NewTemplate = nullptr;
6451   TemplateParameterList *TemplateParams = nullptr;
6452   if (!getLangOpts().CPlusPlus) {
6453     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6454                             D.getIdentifierLoc(), II,
6455                             R, TInfo, SC);
6456
6457     if (R->getContainedDeducedType())
6458       ParsingInitForAutoVars.insert(NewVD);
6459
6460     if (D.isInvalidType())
6461       NewVD->setInvalidDecl();
6462   } else {
6463     bool Invalid = false;
6464
6465     if (DC->isRecord() && !CurContext->isRecord()) {
6466       // This is an out-of-line definition of a static data member.
6467       switch (SC) {
6468       case SC_None:
6469         break;
6470       case SC_Static:
6471         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6472              diag::err_static_out_of_line)
6473           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6474         break;
6475       case SC_Auto:
6476       case SC_Register:
6477       case SC_Extern:
6478         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6479         // to names of variables declared in a block or to function parameters.
6480         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6481         // of class members
6482
6483         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6484              diag::err_storage_class_for_static_member)
6485           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6486         break;
6487       case SC_PrivateExtern:
6488         llvm_unreachable("C storage class in c++!");
6489       }
6490     }
6491
6492     if (SC == SC_Static && CurContext->isRecord()) {
6493       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6494         if (RD->isLocalClass())
6495           Diag(D.getIdentifierLoc(),
6496                diag::err_static_data_member_not_allowed_in_local_class)
6497             << Name << RD->getDeclName();
6498
6499         // C++98 [class.union]p1: If a union contains a static data member,
6500         // the program is ill-formed. C++11 drops this restriction.
6501         if (RD->isUnion())
6502           Diag(D.getIdentifierLoc(),
6503                getLangOpts().CPlusPlus11
6504                  ? diag::warn_cxx98_compat_static_data_member_in_union
6505                  : diag::ext_static_data_member_in_union) << Name;
6506         // We conservatively disallow static data members in anonymous structs.
6507         else if (!RD->getDeclName())
6508           Diag(D.getIdentifierLoc(),
6509                diag::err_static_data_member_not_allowed_in_anon_struct)
6510             << Name << RD->isUnion();
6511       }
6512     }
6513
6514     // Match up the template parameter lists with the scope specifier, then
6515     // determine whether we have a template or a template specialization.
6516     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6517         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6518         D.getCXXScopeSpec(),
6519         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6520             ? D.getName().TemplateId
6521             : nullptr,
6522         TemplateParamLists,
6523         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6524
6525     if (TemplateParams) {
6526       if (!TemplateParams->size() &&
6527           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6528         // There is an extraneous 'template<>' for this variable. Complain
6529         // about it, but allow the declaration of the variable.
6530         Diag(TemplateParams->getTemplateLoc(),
6531              diag::err_template_variable_noparams)
6532           << II
6533           << SourceRange(TemplateParams->getTemplateLoc(),
6534                          TemplateParams->getRAngleLoc());
6535         TemplateParams = nullptr;
6536       } else {
6537         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6538           // This is an explicit specialization or a partial specialization.
6539           // FIXME: Check that we can declare a specialization here.
6540           IsVariableTemplateSpecialization = true;
6541           IsPartialSpecialization = TemplateParams->size() > 0;
6542         } else { // if (TemplateParams->size() > 0)
6543           // This is a template declaration.
6544           IsVariableTemplate = true;
6545
6546           // Check that we can declare a template here.
6547           if (CheckTemplateDeclScope(S, TemplateParams))
6548             return nullptr;
6549
6550           // Only C++1y supports variable templates (N3651).
6551           Diag(D.getIdentifierLoc(),
6552                getLangOpts().CPlusPlus14
6553                    ? diag::warn_cxx11_compat_variable_template
6554                    : diag::ext_variable_template);
6555         }
6556       }
6557     } else {
6558       assert((Invalid ||
6559               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6560              "should have a 'template<>' for this decl");
6561     }
6562
6563     if (IsVariableTemplateSpecialization) {
6564       SourceLocation TemplateKWLoc =
6565           TemplateParamLists.size() > 0
6566               ? TemplateParamLists[0]->getTemplateLoc()
6567               : SourceLocation();
6568       DeclResult Res = ActOnVarTemplateSpecialization(
6569           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6570           IsPartialSpecialization);
6571       if (Res.isInvalid())
6572         return nullptr;
6573       NewVD = cast<VarDecl>(Res.get());
6574       AddToScope = false;
6575     } else if (D.isDecompositionDeclarator()) {
6576       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6577                                         D.getIdentifierLoc(), R, TInfo, SC,
6578                                         Bindings);
6579     } else
6580       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6581                               D.getIdentifierLoc(), II, R, TInfo, SC);
6582
6583     // If this is supposed to be a variable template, create it as such.
6584     if (IsVariableTemplate) {
6585       NewTemplate =
6586           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6587                                   TemplateParams, NewVD);
6588       NewVD->setDescribedVarTemplate(NewTemplate);
6589     }
6590
6591     // If this decl has an auto type in need of deduction, make a note of the
6592     // Decl so we can diagnose uses of it in its own initializer.
6593     if (R->getContainedDeducedType())
6594       ParsingInitForAutoVars.insert(NewVD);
6595
6596     if (D.isInvalidType() || Invalid) {
6597       NewVD->setInvalidDecl();
6598       if (NewTemplate)
6599         NewTemplate->setInvalidDecl();
6600     }
6601
6602     SetNestedNameSpecifier(NewVD, D);
6603
6604     // If we have any template parameter lists that don't directly belong to
6605     // the variable (matching the scope specifier), store them.
6606     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6607     if (TemplateParamLists.size() > VDTemplateParamLists)
6608       NewVD->setTemplateParameterListsInfo(
6609           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6610
6611     if (D.getDeclSpec().isConstexprSpecified()) {
6612       NewVD->setConstexpr(true);
6613       // C++1z [dcl.spec.constexpr]p1:
6614       //   A static data member declared with the constexpr specifier is
6615       //   implicitly an inline variable.
6616       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6617         NewVD->setImplicitlyInline();
6618     }
6619   }
6620
6621   if (D.getDeclSpec().isInlineSpecified()) {
6622     if (!getLangOpts().CPlusPlus) {
6623       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6624           << 0;
6625     } else if (CurContext->isFunctionOrMethod()) {
6626       // 'inline' is not allowed on block scope variable declaration.
6627       Diag(D.getDeclSpec().getInlineSpecLoc(),
6628            diag::err_inline_declaration_block_scope) << Name
6629         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6630     } else {
6631       Diag(D.getDeclSpec().getInlineSpecLoc(),
6632            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6633                                      : diag::ext_inline_variable);
6634       NewVD->setInlineSpecified();
6635     }
6636   }
6637
6638   // Set the lexical context. If the declarator has a C++ scope specifier, the
6639   // lexical context will be different from the semantic context.
6640   NewVD->setLexicalDeclContext(CurContext);
6641   if (NewTemplate)
6642     NewTemplate->setLexicalDeclContext(CurContext);
6643
6644   if (IsLocalExternDecl) {
6645     if (D.isDecompositionDeclarator())
6646       for (auto *B : Bindings)
6647         B->setLocalExternDecl();
6648     else
6649       NewVD->setLocalExternDecl();
6650   }
6651
6652   bool EmitTLSUnsupportedError = false;
6653   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6654     // C++11 [dcl.stc]p4:
6655     //   When thread_local is applied to a variable of block scope the
6656     //   storage-class-specifier static is implied if it does not appear
6657     //   explicitly.
6658     // Core issue: 'static' is not implied if the variable is declared
6659     //   'extern'.
6660     if (NewVD->hasLocalStorage() &&
6661         (SCSpec != DeclSpec::SCS_unspecified ||
6662          TSCS != DeclSpec::TSCS_thread_local ||
6663          !DC->isFunctionOrMethod()))
6664       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6665            diag::err_thread_non_global)
6666         << DeclSpec::getSpecifierName(TSCS);
6667     else if (!Context.getTargetInfo().isTLSSupported()) {
6668       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6669         // Postpone error emission until we've collected attributes required to
6670         // figure out whether it's a host or device variable and whether the
6671         // error should be ignored.
6672         EmitTLSUnsupportedError = true;
6673         // We still need to mark the variable as TLS so it shows up in AST with
6674         // proper storage class for other tools to use even if we're not going
6675         // to emit any code for it.
6676         NewVD->setTSCSpec(TSCS);
6677       } else
6678         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6679              diag::err_thread_unsupported);
6680     } else
6681       NewVD->setTSCSpec(TSCS);
6682   }
6683
6684   // C99 6.7.4p3
6685   //   An inline definition of a function with external linkage shall
6686   //   not contain a definition of a modifiable object with static or
6687   //   thread storage duration...
6688   // We only apply this when the function is required to be defined
6689   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6690   // that a local variable with thread storage duration still has to
6691   // be marked 'static'.  Also note that it's possible to get these
6692   // semantics in C++ using __attribute__((gnu_inline)).
6693   if (SC == SC_Static && S->getFnParent() != nullptr &&
6694       !NewVD->getType().isConstQualified()) {
6695     FunctionDecl *CurFD = getCurFunctionDecl();
6696     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6697       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6698            diag::warn_static_local_in_extern_inline);
6699       MaybeSuggestAddingStaticToDecl(CurFD);
6700     }
6701   }
6702
6703   if (D.getDeclSpec().isModulePrivateSpecified()) {
6704     if (IsVariableTemplateSpecialization)
6705       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6706           << (IsPartialSpecialization ? 1 : 0)
6707           << FixItHint::CreateRemoval(
6708                  D.getDeclSpec().getModulePrivateSpecLoc());
6709     else if (IsMemberSpecialization)
6710       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6711         << 2
6712         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6713     else if (NewVD->hasLocalStorage())
6714       Diag(NewVD->getLocation(), diag::err_module_private_local)
6715         << 0 << NewVD->getDeclName()
6716         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6717         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6718     else {
6719       NewVD->setModulePrivate();
6720       if (NewTemplate)
6721         NewTemplate->setModulePrivate();
6722       for (auto *B : Bindings)
6723         B->setModulePrivate();
6724     }
6725   }
6726
6727   // Handle attributes prior to checking for duplicates in MergeVarDecl
6728   ProcessDeclAttributes(S, NewVD, D);
6729
6730   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6731     if (EmitTLSUnsupportedError &&
6732         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6733          (getLangOpts().OpenMPIsDevice &&
6734           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6735       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6736            diag::err_thread_unsupported);
6737     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6738     // storage [duration]."
6739     if (SC == SC_None && S->getFnParent() != nullptr &&
6740         (NewVD->hasAttr<CUDASharedAttr>() ||
6741          NewVD->hasAttr<CUDAConstantAttr>())) {
6742       NewVD->setStorageClass(SC_Static);
6743     }
6744   }
6745
6746   // Ensure that dllimport globals without explicit storage class are treated as
6747   // extern. The storage class is set above using parsed attributes. Now we can
6748   // check the VarDecl itself.
6749   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6750          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6751          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6752
6753   // In auto-retain/release, infer strong retension for variables of
6754   // retainable type.
6755   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6756     NewVD->setInvalidDecl();
6757
6758   // Handle GNU asm-label extension (encoded as an attribute).
6759   if (Expr *E = (Expr*)D.getAsmLabel()) {
6760     // The parser guarantees this is a string.
6761     StringLiteral *SE = cast<StringLiteral>(E);
6762     StringRef Label = SE->getString();
6763     if (S->getFnParent() != nullptr) {
6764       switch (SC) {
6765       case SC_None:
6766       case SC_Auto:
6767         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6768         break;
6769       case SC_Register:
6770         // Local Named register
6771         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6772             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6773           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6774         break;
6775       case SC_Static:
6776       case SC_Extern:
6777       case SC_PrivateExtern:
6778         break;
6779       }
6780     } else if (SC == SC_Register) {
6781       // Global Named register
6782       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6783         const auto &TI = Context.getTargetInfo();
6784         bool HasSizeMismatch;
6785
6786         if (!TI.isValidGCCRegisterName(Label))
6787           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6788         else if (!TI.validateGlobalRegisterVariable(Label,
6789                                                     Context.getTypeSize(R),
6790                                                     HasSizeMismatch))
6791           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6792         else if (HasSizeMismatch)
6793           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6794       }
6795
6796       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6797         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6798         NewVD->setInvalidDecl(true);
6799       }
6800     }
6801
6802     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6803                                                 Context, Label, 0));
6804   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6805     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6806       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6807     if (I != ExtnameUndeclaredIdentifiers.end()) {
6808       if (isDeclExternC(NewVD)) {
6809         NewVD->addAttr(I->second);
6810         ExtnameUndeclaredIdentifiers.erase(I);
6811       } else
6812         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6813             << /*Variable*/1 << NewVD;
6814     }
6815   }
6816
6817   // Find the shadowed declaration before filtering for scope.
6818   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6819                                 ? getShadowedDeclaration(NewVD, Previous)
6820                                 : nullptr;
6821
6822   // Don't consider existing declarations that are in a different
6823   // scope and are out-of-semantic-context declarations (if the new
6824   // declaration has linkage).
6825   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6826                        D.getCXXScopeSpec().isNotEmpty() ||
6827                        IsMemberSpecialization ||
6828                        IsVariableTemplateSpecialization);
6829
6830   // Check whether the previous declaration is in the same block scope. This
6831   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6832   if (getLangOpts().CPlusPlus &&
6833       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6834     NewVD->setPreviousDeclInSameBlockScope(
6835         Previous.isSingleResult() && !Previous.isShadowed() &&
6836         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6837
6838   if (!getLangOpts().CPlusPlus) {
6839     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6840   } else {
6841     // If this is an explicit specialization of a static data member, check it.
6842     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6843         CheckMemberSpecialization(NewVD, Previous))
6844       NewVD->setInvalidDecl();
6845
6846     // Merge the decl with the existing one if appropriate.
6847     if (!Previous.empty()) {
6848       if (Previous.isSingleResult() &&
6849           isa<FieldDecl>(Previous.getFoundDecl()) &&
6850           D.getCXXScopeSpec().isSet()) {
6851         // The user tried to define a non-static data member
6852         // out-of-line (C++ [dcl.meaning]p1).
6853         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6854           << D.getCXXScopeSpec().getRange();
6855         Previous.clear();
6856         NewVD->setInvalidDecl();
6857       }
6858     } else if (D.getCXXScopeSpec().isSet()) {
6859       // No previous declaration in the qualifying scope.
6860       Diag(D.getIdentifierLoc(), diag::err_no_member)
6861         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6862         << D.getCXXScopeSpec().getRange();
6863       NewVD->setInvalidDecl();
6864     }
6865
6866     if (!IsVariableTemplateSpecialization)
6867       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6868
6869     if (NewTemplate) {
6870       VarTemplateDecl *PrevVarTemplate =
6871           NewVD->getPreviousDecl()
6872               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6873               : nullptr;
6874
6875       // Check the template parameter list of this declaration, possibly
6876       // merging in the template parameter list from the previous variable
6877       // template declaration.
6878       if (CheckTemplateParameterList(
6879               TemplateParams,
6880               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6881                               : nullptr,
6882               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6883                DC->isDependentContext())
6884                   ? TPC_ClassTemplateMember
6885                   : TPC_VarTemplate))
6886         NewVD->setInvalidDecl();
6887
6888       // If we are providing an explicit specialization of a static variable
6889       // template, make a note of that.
6890       if (PrevVarTemplate &&
6891           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6892         PrevVarTemplate->setMemberSpecialization();
6893     }
6894   }
6895
6896   // Diagnose shadowed variables iff this isn't a redeclaration.
6897   if (ShadowedDecl && !D.isRedeclaration())
6898     CheckShadow(NewVD, ShadowedDecl, Previous);
6899
6900   ProcessPragmaWeak(S, NewVD);
6901
6902   // If this is the first declaration of an extern C variable, update
6903   // the map of such variables.
6904   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6905       isIncompleteDeclExternC(*this, NewVD))
6906     RegisterLocallyScopedExternCDecl(NewVD, S);
6907
6908   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6909     Decl *ManglingContextDecl;
6910     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6911             NewVD->getDeclContext(), ManglingContextDecl)) {
6912       Context.setManglingNumber(
6913           NewVD, MCtx->getManglingNumber(
6914                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6915       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6916     }
6917   }
6918
6919   // Special handling of variable named 'main'.
6920   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6921       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6922       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6923
6924     // C++ [basic.start.main]p3
6925     // A program that declares a variable main at global scope is ill-formed.
6926     if (getLangOpts().CPlusPlus)
6927       Diag(D.getLocStart(), diag::err_main_global_variable);
6928
6929     // In C, and external-linkage variable named main results in undefined
6930     // behavior.
6931     else if (NewVD->hasExternalFormalLinkage())
6932       Diag(D.getLocStart(), diag::warn_main_redefined);
6933   }
6934
6935   if (D.isRedeclaration() && !Previous.empty()) {
6936     NamedDecl *Prev = Previous.getRepresentativeDecl();
6937     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6938                                    D.isFunctionDefinition());
6939   }
6940
6941   if (NewTemplate) {
6942     if (NewVD->isInvalidDecl())
6943       NewTemplate->setInvalidDecl();
6944     ActOnDocumentableDecl(NewTemplate);
6945     return NewTemplate;
6946   }
6947
6948   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6949     CompleteMemberSpecialization(NewVD, Previous);
6950
6951   return NewVD;
6952 }
6953
6954 /// Enum describing the %select options in diag::warn_decl_shadow.
6955 enum ShadowedDeclKind {
6956   SDK_Local,
6957   SDK_Global,
6958   SDK_StaticMember,
6959   SDK_Field,
6960   SDK_Typedef,
6961   SDK_Using
6962 };
6963
6964 /// Determine what kind of declaration we're shadowing.
6965 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6966                                                 const DeclContext *OldDC) {
6967   if (isa<TypeAliasDecl>(ShadowedDecl))
6968     return SDK_Using;
6969   else if (isa<TypedefDecl>(ShadowedDecl))
6970     return SDK_Typedef;
6971   else if (isa<RecordDecl>(OldDC))
6972     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6973
6974   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6975 }
6976
6977 /// Return the location of the capture if the given lambda captures the given
6978 /// variable \p VD, or an invalid source location otherwise.
6979 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6980                                          const VarDecl *VD) {
6981   for (const Capture &Capture : LSI->Captures) {
6982     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6983       return Capture.getLocation();
6984   }
6985   return SourceLocation();
6986 }
6987
6988 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6989                                      const LookupResult &R) {
6990   // Only diagnose if we're shadowing an unambiguous field or variable.
6991   if (R.getResultKind() != LookupResult::Found)
6992     return false;
6993
6994   // Return false if warning is ignored.
6995   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6996 }
6997
6998 /// Return the declaration shadowed by the given variable \p D, or null
6999 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7000 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7001                                         const LookupResult &R) {
7002   if (!shouldWarnIfShadowedDecl(Diags, R))
7003     return nullptr;
7004
7005   // Don't diagnose declarations at file scope.
7006   if (D->hasGlobalStorage())
7007     return nullptr;
7008
7009   NamedDecl *ShadowedDecl = R.getFoundDecl();
7010   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7011              ? ShadowedDecl
7012              : nullptr;
7013 }
7014
7015 /// Return the declaration shadowed by the given typedef \p D, or null
7016 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7017 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7018                                         const LookupResult &R) {
7019   // Don't warn if typedef declaration is part of a class
7020   if (D->getDeclContext()->isRecord())
7021     return nullptr;
7022
7023   if (!shouldWarnIfShadowedDecl(Diags, R))
7024     return nullptr;
7025
7026   NamedDecl *ShadowedDecl = R.getFoundDecl();
7027   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7028 }
7029
7030 /// Diagnose variable or built-in function shadowing.  Implements
7031 /// -Wshadow.
7032 ///
7033 /// This method is called whenever a VarDecl is added to a "useful"
7034 /// scope.
7035 ///
7036 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7037 /// \param R the lookup of the name
7038 ///
7039 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7040                        const LookupResult &R) {
7041   DeclContext *NewDC = D->getDeclContext();
7042
7043   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7044     // Fields are not shadowed by variables in C++ static methods.
7045     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7046       if (MD->isStatic())
7047         return;
7048
7049     // Fields shadowed by constructor parameters are a special case. Usually
7050     // the constructor initializes the field with the parameter.
7051     if (isa<CXXConstructorDecl>(NewDC))
7052       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7053         // Remember that this was shadowed so we can either warn about its
7054         // modification or its existence depending on warning settings.
7055         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7056         return;
7057       }
7058   }
7059
7060   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7061     if (shadowedVar->isExternC()) {
7062       // For shadowing external vars, make sure that we point to the global
7063       // declaration, not a locally scoped extern declaration.
7064       for (auto I : shadowedVar->redecls())
7065         if (I->isFileVarDecl()) {
7066           ShadowedDecl = I;
7067           break;
7068         }
7069     }
7070
7071   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7072
7073   unsigned WarningDiag = diag::warn_decl_shadow;
7074   SourceLocation CaptureLoc;
7075   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7076       isa<CXXMethodDecl>(NewDC)) {
7077     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7078       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7079         if (RD->getLambdaCaptureDefault() == LCD_None) {
7080           // Try to avoid warnings for lambdas with an explicit capture list.
7081           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7082           // Warn only when the lambda captures the shadowed decl explicitly.
7083           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7084           if (CaptureLoc.isInvalid())
7085             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7086         } else {
7087           // Remember that this was shadowed so we can avoid the warning if the
7088           // shadowed decl isn't captured and the warning settings allow it.
7089           cast<LambdaScopeInfo>(getCurFunction())
7090               ->ShadowingDecls.push_back(
7091                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7092           return;
7093         }
7094       }
7095
7096       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7097         // A variable can't shadow a local variable in an enclosing scope, if
7098         // they are separated by a non-capturing declaration context.
7099         for (DeclContext *ParentDC = NewDC;
7100              ParentDC && !ParentDC->Equals(OldDC);
7101              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7102           // Only block literals, captured statements, and lambda expressions
7103           // can capture; other scopes don't.
7104           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7105               !isLambdaCallOperator(ParentDC)) {
7106             return;
7107           }
7108         }
7109       }
7110     }
7111   }
7112
7113   // Only warn about certain kinds of shadowing for class members.
7114   if (NewDC && NewDC->isRecord()) {
7115     // In particular, don't warn about shadowing non-class members.
7116     if (!OldDC->isRecord())
7117       return;
7118
7119     // TODO: should we warn about static data members shadowing
7120     // static data members from base classes?
7121
7122     // TODO: don't diagnose for inaccessible shadowed members.
7123     // This is hard to do perfectly because we might friend the
7124     // shadowing context, but that's just a false negative.
7125   }
7126
7127
7128   DeclarationName Name = R.getLookupName();
7129
7130   // Emit warning and note.
7131   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7132     return;
7133   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7134   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7135   if (!CaptureLoc.isInvalid())
7136     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7137         << Name << /*explicitly*/ 1;
7138   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7139 }
7140
7141 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7142 /// when these variables are captured by the lambda.
7143 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7144   for (const auto &Shadow : LSI->ShadowingDecls) {
7145     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7146     // Try to avoid the warning when the shadowed decl isn't captured.
7147     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7148     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7149     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7150                                        ? diag::warn_decl_shadow_uncaptured_local
7151                                        : diag::warn_decl_shadow)
7152         << Shadow.VD->getDeclName()
7153         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7154     if (!CaptureLoc.isInvalid())
7155       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7156           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7157     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7158   }
7159 }
7160
7161 /// Check -Wshadow without the advantage of a previous lookup.
7162 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7163   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7164     return;
7165
7166   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7167                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7168   LookupName(R, S);
7169   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7170     CheckShadow(D, ShadowedDecl, R);
7171 }
7172
7173 /// Check if 'E', which is an expression that is about to be modified, refers
7174 /// to a constructor parameter that shadows a field.
7175 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7176   // Quickly ignore expressions that can't be shadowing ctor parameters.
7177   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7178     return;
7179   E = E->IgnoreParenImpCasts();
7180   auto *DRE = dyn_cast<DeclRefExpr>(E);
7181   if (!DRE)
7182     return;
7183   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7184   auto I = ShadowingDecls.find(D);
7185   if (I == ShadowingDecls.end())
7186     return;
7187   const NamedDecl *ShadowedDecl = I->second;
7188   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7189   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7190   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7191   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7192
7193   // Avoid issuing multiple warnings about the same decl.
7194   ShadowingDecls.erase(I);
7195 }
7196
7197 /// Check for conflict between this global or extern "C" declaration and
7198 /// previous global or extern "C" declarations. This is only used in C++.
7199 template<typename T>
7200 static bool checkGlobalOrExternCConflict(
7201     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7202   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7203   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7204
7205   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7206     // The common case: this global doesn't conflict with any extern "C"
7207     // declaration.
7208     return false;
7209   }
7210
7211   if (Prev) {
7212     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7213       // Both the old and new declarations have C language linkage. This is a
7214       // redeclaration.
7215       Previous.clear();
7216       Previous.addDecl(Prev);
7217       return true;
7218     }
7219
7220     // This is a global, non-extern "C" declaration, and there is a previous
7221     // non-global extern "C" declaration. Diagnose if this is a variable
7222     // declaration.
7223     if (!isa<VarDecl>(ND))
7224       return false;
7225   } else {
7226     // The declaration is extern "C". Check for any declaration in the
7227     // translation unit which might conflict.
7228     if (IsGlobal) {
7229       // We have already performed the lookup into the translation unit.
7230       IsGlobal = false;
7231       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7232            I != E; ++I) {
7233         if (isa<VarDecl>(*I)) {
7234           Prev = *I;
7235           break;
7236         }
7237       }
7238     } else {
7239       DeclContext::lookup_result R =
7240           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7241       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7242            I != E; ++I) {
7243         if (isa<VarDecl>(*I)) {
7244           Prev = *I;
7245           break;
7246         }
7247         // FIXME: If we have any other entity with this name in global scope,
7248         // the declaration is ill-formed, but that is a defect: it breaks the
7249         // 'stat' hack, for instance. Only variables can have mangled name
7250         // clashes with extern "C" declarations, so only they deserve a
7251         // diagnostic.
7252       }
7253     }
7254
7255     if (!Prev)
7256       return false;
7257   }
7258
7259   // Use the first declaration's location to ensure we point at something which
7260   // is lexically inside an extern "C" linkage-spec.
7261   assert(Prev && "should have found a previous declaration to diagnose");
7262   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7263     Prev = FD->getFirstDecl();
7264   else
7265     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7266
7267   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7268     << IsGlobal << ND;
7269   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7270     << IsGlobal;
7271   return false;
7272 }
7273
7274 /// Apply special rules for handling extern "C" declarations. Returns \c true
7275 /// if we have found that this is a redeclaration of some prior entity.
7276 ///
7277 /// Per C++ [dcl.link]p6:
7278 ///   Two declarations [for a function or variable] with C language linkage
7279 ///   with the same name that appear in different scopes refer to the same
7280 ///   [entity]. An entity with C language linkage shall not be declared with
7281 ///   the same name as an entity in global scope.
7282 template<typename T>
7283 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7284                                                   LookupResult &Previous) {
7285   if (!S.getLangOpts().CPlusPlus) {
7286     // In C, when declaring a global variable, look for a corresponding 'extern'
7287     // variable declared in function scope. We don't need this in C++, because
7288     // we find local extern decls in the surrounding file-scope DeclContext.
7289     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7290       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7291         Previous.clear();
7292         Previous.addDecl(Prev);
7293         return true;
7294       }
7295     }
7296     return false;
7297   }
7298
7299   // A declaration in the translation unit can conflict with an extern "C"
7300   // declaration.
7301   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7302     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7303
7304   // An extern "C" declaration can conflict with a declaration in the
7305   // translation unit or can be a redeclaration of an extern "C" declaration
7306   // in another scope.
7307   if (isIncompleteDeclExternC(S,ND))
7308     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7309
7310   // Neither global nor extern "C": nothing to do.
7311   return false;
7312 }
7313
7314 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7315   // If the decl is already known invalid, don't check it.
7316   if (NewVD->isInvalidDecl())
7317     return;
7318
7319   QualType T = NewVD->getType();
7320
7321   // Defer checking an 'auto' type until its initializer is attached.
7322   if (T->isUndeducedType())
7323     return;
7324
7325   if (NewVD->hasAttrs())
7326     CheckAlignasUnderalignment(NewVD);
7327
7328   if (T->isObjCObjectType()) {
7329     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7330       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7331     T = Context.getObjCObjectPointerType(T);
7332     NewVD->setType(T);
7333   }
7334
7335   // Emit an error if an address space was applied to decl with local storage.
7336   // This includes arrays of objects with address space qualifiers, but not
7337   // automatic variables that point to other address spaces.
7338   // ISO/IEC TR 18037 S5.1.2
7339   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7340       T.getAddressSpace() != LangAS::Default) {
7341     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7342     NewVD->setInvalidDecl();
7343     return;
7344   }
7345
7346   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7347   // scope.
7348   if (getLangOpts().OpenCLVersion == 120 &&
7349       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7350       NewVD->isStaticLocal()) {
7351     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7352     NewVD->setInvalidDecl();
7353     return;
7354   }
7355
7356   if (getLangOpts().OpenCL) {
7357     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7358     if (NewVD->hasAttr<BlocksAttr>()) {
7359       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7360       return;
7361     }
7362
7363     if (T->isBlockPointerType()) {
7364       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7365       // can't use 'extern' storage class.
7366       if (!T.isConstQualified()) {
7367         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7368             << 0 /*const*/;
7369         NewVD->setInvalidDecl();
7370         return;
7371       }
7372       if (NewVD->hasExternalStorage()) {
7373         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7374         NewVD->setInvalidDecl();
7375         return;
7376       }
7377     }
7378     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7379     // __constant address space.
7380     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7381     // variables inside a function can also be declared in the global
7382     // address space.
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         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7390         if (getLangOpts().OpenCLVersion == 200)
7391           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7392               << Scope << "global or constant";
7393         else
7394           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7395               << Scope << "constant";
7396         NewVD->setInvalidDecl();
7397         return;
7398       }
7399     } else {
7400       if (T.getAddressSpace() == LangAS::opencl_global) {
7401         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7402             << 1 /*is any function*/ << "global";
7403         NewVD->setInvalidDecl();
7404         return;
7405       }
7406       if (T.getAddressSpace() == LangAS::opencl_constant ||
7407           T.getAddressSpace() == LangAS::opencl_local) {
7408         FunctionDecl *FD = getCurFunctionDecl();
7409         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7410         // in functions.
7411         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7412           if (T.getAddressSpace() == LangAS::opencl_constant)
7413             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7414                 << 0 /*non-kernel only*/ << "constant";
7415           else
7416             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7417                 << 0 /*non-kernel only*/ << "local";
7418           NewVD->setInvalidDecl();
7419           return;
7420         }
7421         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7422         // in the outermost scope of a kernel function.
7423         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7424           if (!getCurScope()->isFunctionScope()) {
7425             if (T.getAddressSpace() == LangAS::opencl_constant)
7426               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7427                   << "constant";
7428             else
7429               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7430                   << "local";
7431             NewVD->setInvalidDecl();
7432             return;
7433           }
7434         }
7435       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7436         // Do not allow other address spaces on automatic variable.
7437         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7438         NewVD->setInvalidDecl();
7439         return;
7440       }
7441     }
7442   }
7443
7444   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7445       && !NewVD->hasAttr<BlocksAttr>()) {
7446     if (getLangOpts().getGC() != LangOptions::NonGC)
7447       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7448     else {
7449       assert(!getLangOpts().ObjCAutoRefCount);
7450       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7451     }
7452   }
7453
7454   bool isVM = T->isVariablyModifiedType();
7455   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7456       NewVD->hasAttr<BlocksAttr>())
7457     setFunctionHasBranchProtectedScope();
7458
7459   if ((isVM && NewVD->hasLinkage()) ||
7460       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7461     bool SizeIsNegative;
7462     llvm::APSInt Oversized;
7463     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7464         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7465     QualType FixedT;
7466     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7467       FixedT = FixedTInfo->getType();
7468     else if (FixedTInfo) {
7469       // Type and type-as-written are canonically different. We need to fix up
7470       // both types separately.
7471       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7472                                                    Oversized);
7473     }
7474     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7475       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7476       // FIXME: This won't give the correct result for
7477       // int a[10][n];
7478       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7479
7480       if (NewVD->isFileVarDecl())
7481         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7482         << SizeRange;
7483       else if (NewVD->isStaticLocal())
7484         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7485         << SizeRange;
7486       else
7487         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7488         << SizeRange;
7489       NewVD->setInvalidDecl();
7490       return;
7491     }
7492
7493     if (!FixedTInfo) {
7494       if (NewVD->isFileVarDecl())
7495         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7496       else
7497         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7498       NewVD->setInvalidDecl();
7499       return;
7500     }
7501
7502     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7503     NewVD->setType(FixedT);
7504     NewVD->setTypeSourceInfo(FixedTInfo);
7505   }
7506
7507   if (T->isVoidType()) {
7508     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7509     //                    of objects and functions.
7510     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7511       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7512         << T;
7513       NewVD->setInvalidDecl();
7514       return;
7515     }
7516   }
7517
7518   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7519     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7520     NewVD->setInvalidDecl();
7521     return;
7522   }
7523
7524   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7525     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7526     NewVD->setInvalidDecl();
7527     return;
7528   }
7529
7530   if (NewVD->isConstexpr() && !T->isDependentType() &&
7531       RequireLiteralType(NewVD->getLocation(), T,
7532                          diag::err_constexpr_var_non_literal)) {
7533     NewVD->setInvalidDecl();
7534     return;
7535   }
7536 }
7537
7538 /// Perform semantic checking on a newly-created variable
7539 /// declaration.
7540 ///
7541 /// This routine performs all of the type-checking required for a
7542 /// variable declaration once it has been built. It is used both to
7543 /// check variables after they have been parsed and their declarators
7544 /// have been translated into a declaration, and to check variables
7545 /// that have been instantiated from a template.
7546 ///
7547 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7548 ///
7549 /// Returns true if the variable declaration is a redeclaration.
7550 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7551   CheckVariableDeclarationType(NewVD);
7552
7553   // If the decl is already known invalid, don't check it.
7554   if (NewVD->isInvalidDecl())
7555     return false;
7556
7557   // If we did not find anything by this name, look for a non-visible
7558   // extern "C" declaration with the same name.
7559   if (Previous.empty() &&
7560       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7561     Previous.setShadowed();
7562
7563   if (!Previous.empty()) {
7564     MergeVarDecl(NewVD, Previous);
7565     return true;
7566   }
7567   return false;
7568 }
7569
7570 namespace {
7571 struct FindOverriddenMethod {
7572   Sema *S;
7573   CXXMethodDecl *Method;
7574
7575   /// Member lookup function that determines whether a given C++
7576   /// method overrides a method in a base class, to be used with
7577   /// CXXRecordDecl::lookupInBases().
7578   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7579     RecordDecl *BaseRecord =
7580         Specifier->getType()->getAs<RecordType>()->getDecl();
7581
7582     DeclarationName Name = Method->getDeclName();
7583
7584     // FIXME: Do we care about other names here too?
7585     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7586       // We really want to find the base class destructor here.
7587       QualType T = S->Context.getTypeDeclType(BaseRecord);
7588       CanQualType CT = S->Context.getCanonicalType(T);
7589
7590       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7591     }
7592
7593     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7594          Path.Decls = Path.Decls.slice(1)) {
7595       NamedDecl *D = Path.Decls.front();
7596       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7597         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7598           return true;
7599       }
7600     }
7601
7602     return false;
7603   }
7604 };
7605
7606 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7607 } // end anonymous namespace
7608
7609 /// Report an error regarding overriding, along with any relevant
7610 /// overridden methods.
7611 ///
7612 /// \param DiagID the primary error to report.
7613 /// \param MD the overriding method.
7614 /// \param OEK which overrides to include as notes.
7615 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7616                             OverrideErrorKind OEK = OEK_All) {
7617   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7618   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7619     // This check (& the OEK parameter) could be replaced by a predicate, but
7620     // without lambdas that would be overkill. This is still nicer than writing
7621     // out the diag loop 3 times.
7622     if ((OEK == OEK_All) ||
7623         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7624         (OEK == OEK_Deleted && O->isDeleted()))
7625       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7626   }
7627 }
7628
7629 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7630 /// and if so, check that it's a valid override and remember it.
7631 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7632   // Look for methods in base classes that this method might override.
7633   CXXBasePaths Paths;
7634   FindOverriddenMethod FOM;
7635   FOM.Method = MD;
7636   FOM.S = this;
7637   bool hasDeletedOverridenMethods = false;
7638   bool hasNonDeletedOverridenMethods = false;
7639   bool AddedAny = false;
7640   if (DC->lookupInBases(FOM, Paths)) {
7641     for (auto *I : Paths.found_decls()) {
7642       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7643         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7644         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7645             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7646             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7647             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7648           hasDeletedOverridenMethods |= OldMD->isDeleted();
7649           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7650           AddedAny = true;
7651         }
7652       }
7653     }
7654   }
7655
7656   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7657     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7658   }
7659   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7660     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7661   }
7662
7663   return AddedAny;
7664 }
7665
7666 namespace {
7667   // Struct for holding all of the extra arguments needed by
7668   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7669   struct ActOnFDArgs {
7670     Scope *S;
7671     Declarator &D;
7672     MultiTemplateParamsArg TemplateParamLists;
7673     bool AddToScope;
7674   };
7675 } // end anonymous namespace
7676
7677 namespace {
7678
7679 // Callback to only accept typo corrections that have a non-zero edit distance.
7680 // Also only accept corrections that have the same parent decl.
7681 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7682  public:
7683   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7684                             CXXRecordDecl *Parent)
7685       : Context(Context), OriginalFD(TypoFD),
7686         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7687
7688   bool ValidateCandidate(const TypoCorrection &candidate) override {
7689     if (candidate.getEditDistance() == 0)
7690       return false;
7691
7692     SmallVector<unsigned, 1> MismatchedParams;
7693     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7694                                           CDeclEnd = candidate.end();
7695          CDecl != CDeclEnd; ++CDecl) {
7696       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7697
7698       if (FD && !FD->hasBody() &&
7699           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7700         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7701           CXXRecordDecl *Parent = MD->getParent();
7702           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7703             return true;
7704         } else if (!ExpectedParent) {
7705           return true;
7706         }
7707       }
7708     }
7709
7710     return false;
7711   }
7712
7713  private:
7714   ASTContext &Context;
7715   FunctionDecl *OriginalFD;
7716   CXXRecordDecl *ExpectedParent;
7717 };
7718
7719 } // end anonymous namespace
7720
7721 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7722   TypoCorrectedFunctionDefinitions.insert(F);
7723 }
7724
7725 /// Generate diagnostics for an invalid function redeclaration.
7726 ///
7727 /// This routine handles generating the diagnostic messages for an invalid
7728 /// function redeclaration, including finding possible similar declarations
7729 /// or performing typo correction if there are no previous declarations with
7730 /// the same name.
7731 ///
7732 /// Returns a NamedDecl iff typo correction was performed and substituting in
7733 /// the new declaration name does not cause new errors.
7734 static NamedDecl *DiagnoseInvalidRedeclaration(
7735     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7736     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7737   DeclarationName Name = NewFD->getDeclName();
7738   DeclContext *NewDC = NewFD->getDeclContext();
7739   SmallVector<unsigned, 1> MismatchedParams;
7740   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7741   TypoCorrection Correction;
7742   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7743   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7744                                    : diag::err_member_decl_does_not_match;
7745   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7746                     IsLocalFriend ? Sema::LookupLocalFriendName
7747                                   : Sema::LookupOrdinaryName,
7748                     Sema::ForVisibleRedeclaration);
7749
7750   NewFD->setInvalidDecl();
7751   if (IsLocalFriend)
7752     SemaRef.LookupName(Prev, S);
7753   else
7754     SemaRef.LookupQualifiedName(Prev, NewDC);
7755   assert(!Prev.isAmbiguous() &&
7756          "Cannot have an ambiguity in previous-declaration lookup");
7757   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7758   if (!Prev.empty()) {
7759     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7760          Func != FuncEnd; ++Func) {
7761       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7762       if (FD &&
7763           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7764         // Add 1 to the index so that 0 can mean the mismatch didn't
7765         // involve a parameter
7766         unsigned ParamNum =
7767             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7768         NearMatches.push_back(std::make_pair(FD, ParamNum));
7769       }
7770     }
7771   // If the qualified name lookup yielded nothing, try typo correction
7772   } else if ((Correction = SemaRef.CorrectTypo(
7773                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7774                   &ExtraArgs.D.getCXXScopeSpec(),
7775                   llvm::make_unique<DifferentNameValidatorCCC>(
7776                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7777                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7778     // Set up everything for the call to ActOnFunctionDeclarator
7779     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7780                               ExtraArgs.D.getIdentifierLoc());
7781     Previous.clear();
7782     Previous.setLookupName(Correction.getCorrection());
7783     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7784                                     CDeclEnd = Correction.end();
7785          CDecl != CDeclEnd; ++CDecl) {
7786       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7787       if (FD && !FD->hasBody() &&
7788           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7789         Previous.addDecl(FD);
7790       }
7791     }
7792     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7793
7794     NamedDecl *Result;
7795     // Retry building the function declaration with the new previous
7796     // declarations, and with errors suppressed.
7797     {
7798       // Trap errors.
7799       Sema::SFINAETrap Trap(SemaRef);
7800
7801       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7802       // pieces need to verify the typo-corrected C++ declaration and hopefully
7803       // eliminate the need for the parameter pack ExtraArgs.
7804       Result = SemaRef.ActOnFunctionDeclarator(
7805           ExtraArgs.S, ExtraArgs.D,
7806           Correction.getCorrectionDecl()->getDeclContext(),
7807           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7808           ExtraArgs.AddToScope);
7809
7810       if (Trap.hasErrorOccurred())
7811         Result = nullptr;
7812     }
7813
7814     if (Result) {
7815       // Determine which correction we picked.
7816       Decl *Canonical = Result->getCanonicalDecl();
7817       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7818            I != E; ++I)
7819         if ((*I)->getCanonicalDecl() == Canonical)
7820           Correction.setCorrectionDecl(*I);
7821
7822       // Let Sema know about the correction.
7823       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7824       SemaRef.diagnoseTypo(
7825           Correction,
7826           SemaRef.PDiag(IsLocalFriend
7827                           ? diag::err_no_matching_local_friend_suggest
7828                           : diag::err_member_decl_does_not_match_suggest)
7829             << Name << NewDC << IsDefinition);
7830       return Result;
7831     }
7832
7833     // Pretend the typo correction never occurred
7834     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7835                               ExtraArgs.D.getIdentifierLoc());
7836     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7837     Previous.clear();
7838     Previous.setLookupName(Name);
7839   }
7840
7841   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7842       << Name << NewDC << IsDefinition << NewFD->getLocation();
7843
7844   bool NewFDisConst = false;
7845   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7846     NewFDisConst = NewMD->isConst();
7847
7848   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7849        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7850        NearMatch != NearMatchEnd; ++NearMatch) {
7851     FunctionDecl *FD = NearMatch->first;
7852     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7853     bool FDisConst = MD && MD->isConst();
7854     bool IsMember = MD || !IsLocalFriend;
7855
7856     // FIXME: These notes are poorly worded for the local friend case.
7857     if (unsigned Idx = NearMatch->second) {
7858       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7859       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7860       if (Loc.isInvalid()) Loc = FD->getLocation();
7861       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7862                                  : diag::note_local_decl_close_param_match)
7863         << Idx << FDParam->getType()
7864         << NewFD->getParamDecl(Idx - 1)->getType();
7865     } else if (FDisConst != NewFDisConst) {
7866       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7867           << NewFDisConst << FD->getSourceRange().getEnd();
7868     } else
7869       SemaRef.Diag(FD->getLocation(),
7870                    IsMember ? diag::note_member_def_close_match
7871                             : diag::note_local_decl_close_match);
7872   }
7873   return nullptr;
7874 }
7875
7876 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7877   switch (D.getDeclSpec().getStorageClassSpec()) {
7878   default: llvm_unreachable("Unknown storage class!");
7879   case DeclSpec::SCS_auto:
7880   case DeclSpec::SCS_register:
7881   case DeclSpec::SCS_mutable:
7882     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7883                  diag::err_typecheck_sclass_func);
7884     D.getMutableDeclSpec().ClearStorageClassSpecs();
7885     D.setInvalidType();
7886     break;
7887   case DeclSpec::SCS_unspecified: break;
7888   case DeclSpec::SCS_extern:
7889     if (D.getDeclSpec().isExternInLinkageSpec())
7890       return SC_None;
7891     return SC_Extern;
7892   case DeclSpec::SCS_static: {
7893     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7894       // C99 6.7.1p5:
7895       //   The declaration of an identifier for a function that has
7896       //   block scope shall have no explicit storage-class specifier
7897       //   other than extern
7898       // See also (C++ [dcl.stc]p4).
7899       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7900                    diag::err_static_block_func);
7901       break;
7902     } else
7903       return SC_Static;
7904   }
7905   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7906   }
7907
7908   // No explicit storage class has already been returned
7909   return SC_None;
7910 }
7911
7912 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7913                                            DeclContext *DC, QualType &R,
7914                                            TypeSourceInfo *TInfo,
7915                                            StorageClass SC,
7916                                            bool &IsVirtualOkay) {
7917   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7918   DeclarationName Name = NameInfo.getName();
7919
7920   FunctionDecl *NewFD = nullptr;
7921   bool isInline = D.getDeclSpec().isInlineSpecified();
7922
7923   if (!SemaRef.getLangOpts().CPlusPlus) {
7924     // Determine whether the function was written with a
7925     // prototype. This true when:
7926     //   - there is a prototype in the declarator, or
7927     //   - the type R of the function is some kind of typedef or other non-
7928     //     attributed reference to a type name (which eventually refers to a
7929     //     function type).
7930     bool HasPrototype =
7931       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7932       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7933
7934     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7935                                  D.getLocStart(), NameInfo, R,
7936                                  TInfo, SC, isInline,
7937                                  HasPrototype, false);
7938     if (D.isInvalidType())
7939       NewFD->setInvalidDecl();
7940
7941     return NewFD;
7942   }
7943
7944   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7945   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7946
7947   // Check that the return type is not an abstract class type.
7948   // For record types, this is done by the AbstractClassUsageDiagnoser once
7949   // the class has been completely parsed.
7950   if (!DC->isRecord() &&
7951       SemaRef.RequireNonAbstractType(
7952           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7953           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7954     D.setInvalidType();
7955
7956   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7957     // This is a C++ constructor declaration.
7958     assert(DC->isRecord() &&
7959            "Constructors can only be declared in a member context");
7960
7961     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7962     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7963                                       D.getLocStart(), NameInfo,
7964                                       R, TInfo, isExplicit, isInline,
7965                                       /*isImplicitlyDeclared=*/false,
7966                                       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 = CXXDestructorDecl::Create(
7974                                         SemaRef.Context, Record,
7975                                         D.getLocStart(),
7976                                         NameInfo, R, TInfo, isInline,
7977                                         /*isImplicitlyDeclared=*/false);
7978
7979       // If the class is complete, then we now create the implicit exception
7980       // specification. If the class is incomplete or dependent, we can't do
7981       // it yet.
7982       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7983           Record->getDefinition() && !Record->isBeingDefined() &&
7984           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7985         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7986       }
7987
7988       IsVirtualOkay = true;
7989       return NewDD;
7990
7991     } else {
7992       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7993       D.setInvalidType();
7994
7995       // Create a FunctionDecl to satisfy the function definition parsing
7996       // code path.
7997       return FunctionDecl::Create(SemaRef.Context, DC,
7998                                   D.getLocStart(),
7999                                   D.getIdentifierLoc(), Name, R, TInfo,
8000                                   SC, isInline,
8001                                   /*hasPrototype=*/true, isConstexpr);
8002     }
8003
8004   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8005     if (!DC->isRecord()) {
8006       SemaRef.Diag(D.getIdentifierLoc(),
8007            diag::err_conv_function_not_member);
8008       return nullptr;
8009     }
8010
8011     SemaRef.CheckConversionDeclarator(D, R, SC);
8012     IsVirtualOkay = true;
8013     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
8014                                      D.getLocStart(), NameInfo,
8015                                      R, TInfo, isInline, isExplicit,
8016                                      isConstexpr, SourceLocation());
8017
8018   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8019     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8020
8021     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
8022                                          isExplicit, NameInfo, R, TInfo,
8023                                          D.getLocEnd());
8024   } else if (DC->isRecord()) {
8025     // If the name of the function is the same as the name of the record,
8026     // then this must be an invalid constructor that has a return type.
8027     // (The parser checks for a return type and makes the declarator a
8028     // constructor if it has no return type).
8029     if (Name.getAsIdentifierInfo() &&
8030         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8031       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8032         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8033         << SourceRange(D.getIdentifierLoc());
8034       return nullptr;
8035     }
8036
8037     // This is a C++ method declaration.
8038     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
8039                                                cast<CXXRecordDecl>(DC),
8040                                                D.getLocStart(), NameInfo, R,
8041                                                TInfo, SC, isInline,
8042                                                isConstexpr, SourceLocation());
8043     IsVirtualOkay = !Ret->isStatic();
8044     return Ret;
8045   } else {
8046     bool isFriend =
8047         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8048     if (!isFriend && SemaRef.CurContext->isRecord())
8049       return nullptr;
8050
8051     // Determine whether the function was written with a
8052     // prototype. This true when:
8053     //   - we're in C++ (where every function has a prototype),
8054     return FunctionDecl::Create(SemaRef.Context, DC,
8055                                 D.getLocStart(),
8056                                 NameInfo, R, TInfo, SC, isInline,
8057                                 true/*HasPrototype*/, isConstexpr);
8058   }
8059 }
8060
8061 enum OpenCLParamType {
8062   ValidKernelParam,
8063   PtrPtrKernelParam,
8064   PtrKernelParam,
8065   InvalidAddrSpacePtrKernelParam,
8066   InvalidKernelParam,
8067   RecordKernelParam
8068 };
8069
8070 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8071   // Size dependent types are just typedefs to normal integer types
8072   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8073   // integers other than by their names.
8074   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8075
8076   // Remove typedefs one by one until we reach a typedef
8077   // for a size dependent type.
8078   QualType DesugaredTy = Ty;
8079   do {
8080     ArrayRef<StringRef> Names(SizeTypeNames);
8081     auto Match =
8082         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8083     if (Names.end() != Match)
8084       return true;
8085
8086     Ty = DesugaredTy;
8087     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8088   } while (DesugaredTy != Ty);
8089
8090   return false;
8091 }
8092
8093 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8094   if (PT->isPointerType()) {
8095     QualType PointeeType = PT->getPointeeType();
8096     if (PointeeType->isPointerType())
8097       return PtrPtrKernelParam;
8098     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8099         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8100         PointeeType.getAddressSpace() == LangAS::Default)
8101       return InvalidAddrSpacePtrKernelParam;
8102     return PtrKernelParam;
8103   }
8104
8105   // OpenCL v1.2 s6.9.k:
8106   // Arguments to kernel functions in a program cannot be declared with the
8107   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8108   // uintptr_t or a struct and/or union that contain fields declared to be one
8109   // of these built-in scalar types.
8110   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8111     return InvalidKernelParam;
8112
8113   if (PT->isImageType())
8114     return PtrKernelParam;
8115
8116   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8117     return InvalidKernelParam;
8118
8119   // OpenCL extension spec v1.2 s9.5:
8120   // This extension adds support for half scalar and vector types as built-in
8121   // types that can be used for arithmetic operations, conversions etc.
8122   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8123     return InvalidKernelParam;
8124
8125   if (PT->isRecordType())
8126     return RecordKernelParam;
8127
8128   // Look into an array argument to check if it has a forbidden type.
8129   if (PT->isArrayType()) {
8130     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8131     // Call ourself to check an underlying type of an array. Since the
8132     // getPointeeOrArrayElementType returns an innermost type which is not an
8133     // array, this recusive call only happens once.
8134     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8135   }
8136
8137   return ValidKernelParam;
8138 }
8139
8140 static void checkIsValidOpenCLKernelParameter(
8141   Sema &S,
8142   Declarator &D,
8143   ParmVarDecl *Param,
8144   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8145   QualType PT = Param->getType();
8146
8147   // Cache the valid types we encounter to avoid rechecking structs that are
8148   // used again
8149   if (ValidTypes.count(PT.getTypePtr()))
8150     return;
8151
8152   switch (getOpenCLKernelParameterType(S, PT)) {
8153   case PtrPtrKernelParam:
8154     // OpenCL v1.2 s6.9.a:
8155     // A kernel function argument cannot be declared as a
8156     // pointer to a pointer type.
8157     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8158     D.setInvalidType();
8159     return;
8160
8161   case InvalidAddrSpacePtrKernelParam:
8162     // OpenCL v1.0 s6.5:
8163     // __kernel function arguments declared to be a pointer of a type can point
8164     // to one of the following address spaces only : __global, __local or
8165     // __constant.
8166     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8167     D.setInvalidType();
8168     return;
8169
8170     // OpenCL v1.2 s6.9.k:
8171     // Arguments to kernel functions in a program cannot be declared with the
8172     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8173     // uintptr_t or a struct and/or union that contain fields declared to be
8174     // one of these built-in scalar types.
8175
8176   case InvalidKernelParam:
8177     // OpenCL v1.2 s6.8 n:
8178     // A kernel function argument cannot be declared
8179     // of event_t type.
8180     // Do not diagnose half type since it is diagnosed as invalid argument
8181     // type for any function elsewhere.
8182     if (!PT->isHalfType()) {
8183       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8184
8185       // Explain what typedefs are involved.
8186       const TypedefType *Typedef = nullptr;
8187       while ((Typedef = PT->getAs<TypedefType>())) {
8188         SourceLocation Loc = Typedef->getDecl()->getLocation();
8189         // SourceLocation may be invalid for a built-in type.
8190         if (Loc.isValid())
8191           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8192         PT = Typedef->desugar();
8193       }
8194     }
8195
8196     D.setInvalidType();
8197     return;
8198
8199   case PtrKernelParam:
8200   case ValidKernelParam:
8201     ValidTypes.insert(PT.getTypePtr());
8202     return;
8203
8204   case RecordKernelParam:
8205     break;
8206   }
8207
8208   // Track nested structs we will inspect
8209   SmallVector<const Decl *, 4> VisitStack;
8210
8211   // Track where we are in the nested structs. Items will migrate from
8212   // VisitStack to HistoryStack as we do the DFS for bad field.
8213   SmallVector<const FieldDecl *, 4> HistoryStack;
8214   HistoryStack.push_back(nullptr);
8215
8216   // At this point we already handled everything except of a RecordType or
8217   // an ArrayType of a RecordType.
8218   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8219   const RecordType *RecTy =
8220       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8221   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8222
8223   VisitStack.push_back(RecTy->getDecl());
8224   assert(VisitStack.back() && "First decl null?");
8225
8226   do {
8227     const Decl *Next = VisitStack.pop_back_val();
8228     if (!Next) {
8229       assert(!HistoryStack.empty());
8230       // Found a marker, we have gone up a level
8231       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8232         ValidTypes.insert(Hist->getType().getTypePtr());
8233
8234       continue;
8235     }
8236
8237     // Adds everything except the original parameter declaration (which is not a
8238     // field itself) to the history stack.
8239     const RecordDecl *RD;
8240     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8241       HistoryStack.push_back(Field);
8242
8243       QualType FieldTy = Field->getType();
8244       // Other field types (known to be valid or invalid) are handled while we
8245       // walk around RecordDecl::fields().
8246       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8247              "Unexpected type.");
8248       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8249
8250       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8251     } else {
8252       RD = cast<RecordDecl>(Next);
8253     }
8254
8255     // Add a null marker so we know when we've gone back up a level
8256     VisitStack.push_back(nullptr);
8257
8258     for (const auto *FD : RD->fields()) {
8259       QualType QT = FD->getType();
8260
8261       if (ValidTypes.count(QT.getTypePtr()))
8262         continue;
8263
8264       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8265       if (ParamType == ValidKernelParam)
8266         continue;
8267
8268       if (ParamType == RecordKernelParam) {
8269         VisitStack.push_back(FD);
8270         continue;
8271       }
8272
8273       // OpenCL v1.2 s6.9.p:
8274       // Arguments to kernel functions that are declared to be a struct or union
8275       // do not allow OpenCL objects to be passed as elements of the struct or
8276       // union.
8277       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8278           ParamType == InvalidAddrSpacePtrKernelParam) {
8279         S.Diag(Param->getLocation(),
8280                diag::err_record_with_pointers_kernel_param)
8281           << PT->isUnionType()
8282           << PT;
8283       } else {
8284         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8285       }
8286
8287       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8288           << OrigRecDecl->getDeclName();
8289
8290       // We have an error, now let's go back up through history and show where
8291       // the offending field came from
8292       for (ArrayRef<const FieldDecl *>::const_iterator
8293                I = HistoryStack.begin() + 1,
8294                E = HistoryStack.end();
8295            I != E; ++I) {
8296         const FieldDecl *OuterField = *I;
8297         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8298           << OuterField->getType();
8299       }
8300
8301       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8302         << QT->isPointerType()
8303         << QT;
8304       D.setInvalidType();
8305       return;
8306     }
8307   } while (!VisitStack.empty());
8308 }
8309
8310 /// Find the DeclContext 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 DeclContext *getTagInjectionContext(DeclContext *DC) {
8314   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8315     DC = DC->getParent();
8316   return DC;
8317 }
8318
8319 /// Find the Scope in which a tag is implicitly declared if we see an
8320 /// elaborated type specifier in the specified context, and lookup finds
8321 /// nothing.
8322 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8323   while (S->isClassScope() ||
8324          (LangOpts.CPlusPlus &&
8325           S->isFunctionPrototypeScope()) ||
8326          ((S->getFlags() & Scope::DeclScope) == 0) ||
8327          (S->getEntity() && S->getEntity()->isTransparentContext()))
8328     S = S->getParent();
8329   return S;
8330 }
8331
8332 NamedDecl*
8333 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8334                               TypeSourceInfo *TInfo, LookupResult &Previous,
8335                               MultiTemplateParamsArg TemplateParamLists,
8336                               bool &AddToScope) {
8337   QualType R = TInfo->getType();
8338
8339   assert(R->isFunctionType());
8340
8341   // TODO: consider using NameInfo for diagnostic.
8342   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8343   DeclarationName Name = NameInfo.getName();
8344   StorageClass SC = getFunctionStorageClass(*this, D);
8345
8346   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8347     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8348          diag::err_invalid_thread)
8349       << DeclSpec::getSpecifierName(TSCS);
8350
8351   if (D.isFirstDeclarationOfMember())
8352     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8353                            D.getIdentifierLoc());
8354
8355   bool isFriend = false;
8356   FunctionTemplateDecl *FunctionTemplate = nullptr;
8357   bool isMemberSpecialization = false;
8358   bool isFunctionTemplateSpecialization = false;
8359
8360   bool isDependentClassScopeExplicitSpecialization = false;
8361   bool HasExplicitTemplateArgs = false;
8362   TemplateArgumentListInfo TemplateArgs;
8363
8364   bool isVirtualOkay = false;
8365
8366   DeclContext *OriginalDC = DC;
8367   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8368
8369   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8370                                               isVirtualOkay);
8371   if (!NewFD) return nullptr;
8372
8373   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8374     NewFD->setTopLevelDeclInObjCContainer();
8375
8376   // Set the lexical context. If this is a function-scope declaration, or has a
8377   // C++ scope specifier, or is the object of a friend declaration, the lexical
8378   // context will be different from the semantic context.
8379   NewFD->setLexicalDeclContext(CurContext);
8380
8381   if (IsLocalExternDecl)
8382     NewFD->setLocalExternDecl();
8383
8384   if (getLangOpts().CPlusPlus) {
8385     bool isInline = D.getDeclSpec().isInlineSpecified();
8386     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8387     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8388     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8389     isFriend = D.getDeclSpec().isFriendSpecified();
8390     if (isFriend && !isInline && D.isFunctionDefinition()) {
8391       // C++ [class.friend]p5
8392       //   A function can be defined in a friend declaration of a
8393       //   class . . . . Such a function is implicitly inline.
8394       NewFD->setImplicitlyInline();
8395     }
8396
8397     // If this is a method defined in an __interface, and is not a constructor
8398     // or an overloaded operator, then set the pure flag (isVirtual will already
8399     // return true).
8400     if (const CXXRecordDecl *Parent =
8401           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8402       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8403         NewFD->setPure(true);
8404
8405       // C++ [class.union]p2
8406       //   A union can have member functions, but not virtual functions.
8407       if (isVirtual && Parent->isUnion())
8408         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8409     }
8410
8411     SetNestedNameSpecifier(NewFD, D);
8412     isMemberSpecialization = false;
8413     isFunctionTemplateSpecialization = false;
8414     if (D.isInvalidType())
8415       NewFD->setInvalidDecl();
8416
8417     // Match up the template parameter lists with the scope specifier, then
8418     // determine whether we have a template or a template specialization.
8419     bool Invalid = false;
8420     if (TemplateParameterList *TemplateParams =
8421             MatchTemplateParametersToScopeSpecifier(
8422                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8423                 D.getCXXScopeSpec(),
8424                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8425                     ? D.getName().TemplateId
8426                     : nullptr,
8427                 TemplateParamLists, isFriend, isMemberSpecialization,
8428                 Invalid)) {
8429       if (TemplateParams->size() > 0) {
8430         // This is a function template
8431
8432         // Check that we can declare a template here.
8433         if (CheckTemplateDeclScope(S, TemplateParams))
8434           NewFD->setInvalidDecl();
8435
8436         // A destructor cannot be a template.
8437         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8438           Diag(NewFD->getLocation(), diag::err_destructor_template);
8439           NewFD->setInvalidDecl();
8440         }
8441
8442         // If we're adding a template to a dependent context, we may need to
8443         // rebuilding some of the types used within the template parameter list,
8444         // now that we know what the current instantiation is.
8445         if (DC->isDependentContext()) {
8446           ContextRAII SavedContext(*this, DC);
8447           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8448             Invalid = true;
8449         }
8450
8451         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8452                                                         NewFD->getLocation(),
8453                                                         Name, TemplateParams,
8454                                                         NewFD);
8455         FunctionTemplate->setLexicalDeclContext(CurContext);
8456         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8457
8458         // For source fidelity, store the other template param lists.
8459         if (TemplateParamLists.size() > 1) {
8460           NewFD->setTemplateParameterListsInfo(Context,
8461                                                TemplateParamLists.drop_back(1));
8462         }
8463       } else {
8464         // This is a function template specialization.
8465         isFunctionTemplateSpecialization = true;
8466         // For source fidelity, store all the template param lists.
8467         if (TemplateParamLists.size() > 0)
8468           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8469
8470         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8471         if (isFriend) {
8472           // We want to remove the "template<>", found here.
8473           SourceRange RemoveRange = TemplateParams->getSourceRange();
8474
8475           // If we remove the template<> and the name is not a
8476           // template-id, we're actually silently creating a problem:
8477           // the friend declaration will refer to an untemplated decl,
8478           // and clearly the user wants a template specialization.  So
8479           // we need to insert '<>' after the name.
8480           SourceLocation InsertLoc;
8481           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8482             InsertLoc = D.getName().getSourceRange().getEnd();
8483             InsertLoc = getLocForEndOfToken(InsertLoc);
8484           }
8485
8486           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8487             << Name << RemoveRange
8488             << FixItHint::CreateRemoval(RemoveRange)
8489             << FixItHint::CreateInsertion(InsertLoc, "<>");
8490         }
8491       }
8492     }
8493     else {
8494       // All template param lists were matched against the scope specifier:
8495       // this is NOT (an explicit specialization of) a template.
8496       if (TemplateParamLists.size() > 0)
8497         // For source fidelity, store all the template param lists.
8498         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8499     }
8500
8501     if (Invalid) {
8502       NewFD->setInvalidDecl();
8503       if (FunctionTemplate)
8504         FunctionTemplate->setInvalidDecl();
8505     }
8506
8507     // C++ [dcl.fct.spec]p5:
8508     //   The virtual specifier shall only be used in declarations of
8509     //   nonstatic class member functions that appear within a
8510     //   member-specification of a class declaration; see 10.3.
8511     //
8512     if (isVirtual && !NewFD->isInvalidDecl()) {
8513       if (!isVirtualOkay) {
8514         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8515              diag::err_virtual_non_function);
8516       } else if (!CurContext->isRecord()) {
8517         // 'virtual' was specified outside of the class.
8518         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8519              diag::err_virtual_out_of_class)
8520           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8521       } else if (NewFD->getDescribedFunctionTemplate()) {
8522         // C++ [temp.mem]p3:
8523         //  A member function template shall not be virtual.
8524         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8525              diag::err_virtual_member_function_template)
8526           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8527       } else {
8528         // Okay: Add virtual to the method.
8529         NewFD->setVirtualAsWritten(true);
8530       }
8531
8532       if (getLangOpts().CPlusPlus14 &&
8533           NewFD->getReturnType()->isUndeducedType())
8534         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8535     }
8536
8537     if (getLangOpts().CPlusPlus14 &&
8538         (NewFD->isDependentContext() ||
8539          (isFriend && CurContext->isDependentContext())) &&
8540         NewFD->getReturnType()->isUndeducedType()) {
8541       // If the function template is referenced directly (for instance, as a
8542       // member of the current instantiation), pretend it has a dependent type.
8543       // This is not really justified by the standard, but is the only sane
8544       // thing to do.
8545       // FIXME: For a friend function, we have not marked the function as being
8546       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8547       const FunctionProtoType *FPT =
8548           NewFD->getType()->castAs<FunctionProtoType>();
8549       QualType Result =
8550           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8551       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8552                                              FPT->getExtProtoInfo()));
8553     }
8554
8555     // C++ [dcl.fct.spec]p3:
8556     //  The inline specifier shall not appear on a block scope function
8557     //  declaration.
8558     if (isInline && !NewFD->isInvalidDecl()) {
8559       if (CurContext->isFunctionOrMethod()) {
8560         // 'inline' is not allowed on block scope function declaration.
8561         Diag(D.getDeclSpec().getInlineSpecLoc(),
8562              diag::err_inline_declaration_block_scope) << Name
8563           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8564       }
8565     }
8566
8567     // C++ [dcl.fct.spec]p6:
8568     //  The explicit specifier shall be used only in the declaration of a
8569     //  constructor or conversion function within its class definition;
8570     //  see 12.3.1 and 12.3.2.
8571     if (isExplicit && !NewFD->isInvalidDecl() &&
8572         !isa<CXXDeductionGuideDecl>(NewFD)) {
8573       if (!CurContext->isRecord()) {
8574         // 'explicit' was specified outside of the class.
8575         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8576              diag::err_explicit_out_of_class)
8577           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8578       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8579                  !isa<CXXConversionDecl>(NewFD)) {
8580         // 'explicit' was specified on a function that wasn't a constructor
8581         // or conversion function.
8582         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8583              diag::err_explicit_non_ctor_or_conv_function)
8584           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8585       }
8586     }
8587
8588     if (isConstexpr) {
8589       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8590       // are implicitly inline.
8591       NewFD->setImplicitlyInline();
8592
8593       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8594       // be either constructors or to return a literal type. Therefore,
8595       // destructors cannot be declared constexpr.
8596       if (isa<CXXDestructorDecl>(NewFD))
8597         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8598     }
8599
8600     // If __module_private__ was specified, mark the function accordingly.
8601     if (D.getDeclSpec().isModulePrivateSpecified()) {
8602       if (isFunctionTemplateSpecialization) {
8603         SourceLocation ModulePrivateLoc
8604           = D.getDeclSpec().getModulePrivateSpecLoc();
8605         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8606           << 0
8607           << FixItHint::CreateRemoval(ModulePrivateLoc);
8608       } else {
8609         NewFD->setModulePrivate();
8610         if (FunctionTemplate)
8611           FunctionTemplate->setModulePrivate();
8612       }
8613     }
8614
8615     if (isFriend) {
8616       if (FunctionTemplate) {
8617         FunctionTemplate->setObjectOfFriendDecl();
8618         FunctionTemplate->setAccess(AS_public);
8619       }
8620       NewFD->setObjectOfFriendDecl();
8621       NewFD->setAccess(AS_public);
8622     }
8623
8624     // If a function is defined as defaulted or deleted, mark it as such now.
8625     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8626     // definition kind to FDK_Definition.
8627     switch (D.getFunctionDefinitionKind()) {
8628       case FDK_Declaration:
8629       case FDK_Definition:
8630         break;
8631
8632       case FDK_Defaulted:
8633         NewFD->setDefaulted();
8634         break;
8635
8636       case FDK_Deleted:
8637         NewFD->setDeletedAsWritten();
8638         break;
8639     }
8640
8641     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8642         D.isFunctionDefinition()) {
8643       // C++ [class.mfct]p2:
8644       //   A member function may be defined (8.4) in its class definition, in
8645       //   which case it is an inline member function (7.1.2)
8646       NewFD->setImplicitlyInline();
8647     }
8648
8649     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8650         !CurContext->isRecord()) {
8651       // C++ [class.static]p1:
8652       //   A data or function member of a class may be declared static
8653       //   in a class definition, in which case it is a static member of
8654       //   the class.
8655
8656       // Complain about the 'static' specifier if it's on an out-of-line
8657       // member function definition.
8658       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8659            diag::err_static_out_of_line)
8660         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8661     }
8662
8663     // C++11 [except.spec]p15:
8664     //   A deallocation function with no exception-specification is treated
8665     //   as if it were specified with noexcept(true).
8666     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8667     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8668          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8669         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8670       NewFD->setType(Context.getFunctionType(
8671           FPT->getReturnType(), FPT->getParamTypes(),
8672           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8673   }
8674
8675   // Filter out previous declarations that don't match the scope.
8676   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8677                        D.getCXXScopeSpec().isNotEmpty() ||
8678                        isMemberSpecialization ||
8679                        isFunctionTemplateSpecialization);
8680
8681   // Handle GNU asm-label extension (encoded as an attribute).
8682   if (Expr *E = (Expr*) D.getAsmLabel()) {
8683     // The parser guarantees this is a string.
8684     StringLiteral *SE = cast<StringLiteral>(E);
8685     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8686                                                 SE->getString(), 0));
8687   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8688     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8689       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8690     if (I != ExtnameUndeclaredIdentifiers.end()) {
8691       if (isDeclExternC(NewFD)) {
8692         NewFD->addAttr(I->second);
8693         ExtnameUndeclaredIdentifiers.erase(I);
8694       } else
8695         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8696             << /*Variable*/0 << NewFD;
8697     }
8698   }
8699
8700   // Copy the parameter declarations from the declarator D to the function
8701   // declaration NewFD, if they are available.  First scavenge them into Params.
8702   SmallVector<ParmVarDecl*, 16> Params;
8703   unsigned FTIIdx;
8704   if (D.isFunctionDeclarator(FTIIdx)) {
8705     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8706
8707     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8708     // function that takes no arguments, not a function that takes a
8709     // single void argument.
8710     // We let through "const void" here because Sema::GetTypeForDeclarator
8711     // already checks for that case.
8712     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8713       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8714         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8715         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8716         Param->setDeclContext(NewFD);
8717         Params.push_back(Param);
8718
8719         if (Param->isInvalidDecl())
8720           NewFD->setInvalidDecl();
8721       }
8722     }
8723
8724     if (!getLangOpts().CPlusPlus) {
8725       // In C, find all the tag declarations from the prototype and move them
8726       // into the function DeclContext. Remove them from the surrounding tag
8727       // injection context of the function, which is typically but not always
8728       // the TU.
8729       DeclContext *PrototypeTagContext =
8730           getTagInjectionContext(NewFD->getLexicalDeclContext());
8731       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8732         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8733
8734         // We don't want to reparent enumerators. Look at their parent enum
8735         // instead.
8736         if (!TD) {
8737           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8738             TD = cast<EnumDecl>(ECD->getDeclContext());
8739         }
8740         if (!TD)
8741           continue;
8742         DeclContext *TagDC = TD->getLexicalDeclContext();
8743         if (!TagDC->containsDecl(TD))
8744           continue;
8745         TagDC->removeDecl(TD);
8746         TD->setDeclContext(NewFD);
8747         NewFD->addDecl(TD);
8748
8749         // Preserve the lexical DeclContext if it is not the surrounding tag
8750         // injection context of the FD. In this example, the semantic context of
8751         // E will be f and the lexical context will be S, while both the
8752         // semantic and lexical contexts of S will be f:
8753         //   void f(struct S { enum E { a } f; } s);
8754         if (TagDC != PrototypeTagContext)
8755           TD->setLexicalDeclContext(TagDC);
8756       }
8757     }
8758   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8759     // When we're declaring a function with a typedef, typeof, etc as in the
8760     // following example, we'll need to synthesize (unnamed)
8761     // parameters for use in the declaration.
8762     //
8763     // @code
8764     // typedef void fn(int);
8765     // fn f;
8766     // @endcode
8767
8768     // Synthesize a parameter for each argument type.
8769     for (const auto &AI : FT->param_types()) {
8770       ParmVarDecl *Param =
8771           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8772       Param->setScopeInfo(0, Params.size());
8773       Params.push_back(Param);
8774     }
8775   } else {
8776     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8777            "Should not need args for typedef of non-prototype fn");
8778   }
8779
8780   // Finally, we know we have the right number of parameters, install them.
8781   NewFD->setParams(Params);
8782
8783   if (D.getDeclSpec().isNoreturnSpecified())
8784     NewFD->addAttr(
8785         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8786                                        Context, 0));
8787
8788   // Functions returning a variably modified type violate C99 6.7.5.2p2
8789   // because all functions have linkage.
8790   if (!NewFD->isInvalidDecl() &&
8791       NewFD->getReturnType()->isVariablyModifiedType()) {
8792     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8793     NewFD->setInvalidDecl();
8794   }
8795
8796   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8797   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8798       !NewFD->hasAttr<SectionAttr>()) {
8799     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8800                                                  PragmaClangTextSection.SectionName,
8801                                                  PragmaClangTextSection.PragmaLocation));
8802   }
8803
8804   // Apply an implicit SectionAttr if #pragma code_seg is active.
8805   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8806       !NewFD->hasAttr<SectionAttr>()) {
8807     NewFD->addAttr(
8808         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8809                                     CodeSegStack.CurrentValue->getString(),
8810                                     CodeSegStack.CurrentPragmaLocation));
8811     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8812                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8813                          ASTContext::PSF_Read,
8814                      NewFD))
8815       NewFD->dropAttr<SectionAttr>();
8816   }
8817
8818   // Apply an implicit CodeSegAttr from class declspec or
8819   // apply an implicit SectionAttr from #pragma code_seg if active.
8820   if (!NewFD->hasAttr<CodeSegAttr>()) {
8821     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8822                                                                  D.isFunctionDefinition())) {
8823       NewFD->addAttr(SAttr);
8824     }
8825   }
8826
8827   // Handle attributes.
8828   ProcessDeclAttributes(S, NewFD, D);
8829
8830   if (getLangOpts().OpenCL) {
8831     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8832     // type declaration will generate a compilation error.
8833     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8834     if (AddressSpace != LangAS::Default) {
8835       Diag(NewFD->getLocation(),
8836            diag::err_opencl_return_value_with_address_space);
8837       NewFD->setInvalidDecl();
8838     }
8839   }
8840
8841   if (!getLangOpts().CPlusPlus) {
8842     // Perform semantic checking on the function declaration.
8843     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8844       CheckMain(NewFD, D.getDeclSpec());
8845
8846     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8847       CheckMSVCRTEntryPoint(NewFD);
8848
8849     if (!NewFD->isInvalidDecl())
8850       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8851                                                   isMemberSpecialization));
8852     else if (!Previous.empty())
8853       // Recover gracefully from an invalid redeclaration.
8854       D.setRedeclaration(true);
8855     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8856             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8857            "previous declaration set still overloaded");
8858
8859     // Diagnose no-prototype function declarations with calling conventions that
8860     // don't support variadic calls. Only do this in C and do it after merging
8861     // possibly prototyped redeclarations.
8862     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8863     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8864       CallingConv CC = FT->getExtInfo().getCC();
8865       if (!supportsVariadicCall(CC)) {
8866         // Windows system headers sometimes accidentally use stdcall without
8867         // (void) parameters, so we relax this to a warning.
8868         int DiagID =
8869             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8870         Diag(NewFD->getLocation(), DiagID)
8871             << FunctionType::getNameForCallConv(CC);
8872       }
8873     }
8874   } else {
8875     // C++11 [replacement.functions]p3:
8876     //  The program's definitions shall not be specified as inline.
8877     //
8878     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8879     //
8880     // Suppress the diagnostic if the function is __attribute__((used)), since
8881     // that forces an external definition to be emitted.
8882     if (D.getDeclSpec().isInlineSpecified() &&
8883         NewFD->isReplaceableGlobalAllocationFunction() &&
8884         !NewFD->hasAttr<UsedAttr>())
8885       Diag(D.getDeclSpec().getInlineSpecLoc(),
8886            diag::ext_operator_new_delete_declared_inline)
8887         << NewFD->getDeclName();
8888
8889     // If the declarator is a template-id, translate the parser's template
8890     // argument list into our AST format.
8891     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8892       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8893       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8894       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8895       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8896                                          TemplateId->NumArgs);
8897       translateTemplateArguments(TemplateArgsPtr,
8898                                  TemplateArgs);
8899
8900       HasExplicitTemplateArgs = true;
8901
8902       if (NewFD->isInvalidDecl()) {
8903         HasExplicitTemplateArgs = false;
8904       } else if (FunctionTemplate) {
8905         // Function template with explicit template arguments.
8906         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8907           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8908
8909         HasExplicitTemplateArgs = false;
8910       } else {
8911         assert((isFunctionTemplateSpecialization ||
8912                 D.getDeclSpec().isFriendSpecified()) &&
8913                "should have a 'template<>' for this decl");
8914         // "friend void foo<>(int);" is an implicit specialization decl.
8915         isFunctionTemplateSpecialization = true;
8916       }
8917     } else if (isFriend && isFunctionTemplateSpecialization) {
8918       // This combination is only possible in a recovery case;  the user
8919       // wrote something like:
8920       //   template <> friend void foo(int);
8921       // which we're recovering from as if the user had written:
8922       //   friend void foo<>(int);
8923       // Go ahead and fake up a template id.
8924       HasExplicitTemplateArgs = true;
8925       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8926       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8927     }
8928
8929     // We do not add HD attributes to specializations here because
8930     // they may have different constexpr-ness compared to their
8931     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8932     // may end up with different effective targets. Instead, a
8933     // specialization inherits its target attributes from its template
8934     // in the CheckFunctionTemplateSpecialization() call below.
8935     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8936       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8937
8938     // If it's a friend (and only if it's a friend), it's possible
8939     // that either the specialized function type or the specialized
8940     // template is dependent, and therefore matching will fail.  In
8941     // this case, don't check the specialization yet.
8942     bool InstantiationDependent = false;
8943     if (isFunctionTemplateSpecialization && isFriend &&
8944         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8945          TemplateSpecializationType::anyDependentTemplateArguments(
8946             TemplateArgs,
8947             InstantiationDependent))) {
8948       assert(HasExplicitTemplateArgs &&
8949              "friend function specialization without template args");
8950       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8951                                                        Previous))
8952         NewFD->setInvalidDecl();
8953     } else if (isFunctionTemplateSpecialization) {
8954       if (CurContext->isDependentContext() && CurContext->isRecord()
8955           && !isFriend) {
8956         isDependentClassScopeExplicitSpecialization = true;
8957       } else if (!NewFD->isInvalidDecl() &&
8958                  CheckFunctionTemplateSpecialization(
8959                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8960                      Previous))
8961         NewFD->setInvalidDecl();
8962
8963       // C++ [dcl.stc]p1:
8964       //   A storage-class-specifier shall not be specified in an explicit
8965       //   specialization (14.7.3)
8966       FunctionTemplateSpecializationInfo *Info =
8967           NewFD->getTemplateSpecializationInfo();
8968       if (Info && SC != SC_None) {
8969         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8970           Diag(NewFD->getLocation(),
8971                diag::err_explicit_specialization_inconsistent_storage_class)
8972             << SC
8973             << FixItHint::CreateRemoval(
8974                                       D.getDeclSpec().getStorageClassSpecLoc());
8975
8976         else
8977           Diag(NewFD->getLocation(),
8978                diag::ext_explicit_specialization_storage_class)
8979             << FixItHint::CreateRemoval(
8980                                       D.getDeclSpec().getStorageClassSpecLoc());
8981       }
8982     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8983       if (CheckMemberSpecialization(NewFD, Previous))
8984           NewFD->setInvalidDecl();
8985     }
8986
8987     // Perform semantic checking on the function declaration.
8988     if (!isDependentClassScopeExplicitSpecialization) {
8989       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8990         CheckMain(NewFD, D.getDeclSpec());
8991
8992       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8993         CheckMSVCRTEntryPoint(NewFD);
8994
8995       if (!NewFD->isInvalidDecl())
8996         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8997                                                     isMemberSpecialization));
8998       else if (!Previous.empty())
8999         // Recover gracefully from an invalid redeclaration.
9000         D.setRedeclaration(true);
9001     }
9002
9003     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9004             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9005            "previous declaration set still overloaded");
9006
9007     NamedDecl *PrincipalDecl = (FunctionTemplate
9008                                 ? cast<NamedDecl>(FunctionTemplate)
9009                                 : NewFD);
9010
9011     if (isFriend && NewFD->getPreviousDecl()) {
9012       AccessSpecifier Access = AS_public;
9013       if (!NewFD->isInvalidDecl())
9014         Access = NewFD->getPreviousDecl()->getAccess();
9015
9016       NewFD->setAccess(Access);
9017       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9018     }
9019
9020     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9021         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9022       PrincipalDecl->setNonMemberOperator();
9023
9024     // If we have a function template, check the template parameter
9025     // list. This will check and merge default template arguments.
9026     if (FunctionTemplate) {
9027       FunctionTemplateDecl *PrevTemplate =
9028                                      FunctionTemplate->getPreviousDecl();
9029       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9030                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9031                                     : nullptr,
9032                             D.getDeclSpec().isFriendSpecified()
9033                               ? (D.isFunctionDefinition()
9034                                    ? TPC_FriendFunctionTemplateDefinition
9035                                    : TPC_FriendFunctionTemplate)
9036                               : (D.getCXXScopeSpec().isSet() &&
9037                                  DC && DC->isRecord() &&
9038                                  DC->isDependentContext())
9039                                   ? TPC_ClassTemplateMember
9040                                   : TPC_FunctionTemplate);
9041     }
9042
9043     if (NewFD->isInvalidDecl()) {
9044       // Ignore all the rest of this.
9045     } else if (!D.isRedeclaration()) {
9046       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9047                                        AddToScope };
9048       // Fake up an access specifier if it's supposed to be a class member.
9049       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9050         NewFD->setAccess(AS_public);
9051
9052       // Qualified decls generally require a previous declaration.
9053       if (D.getCXXScopeSpec().isSet()) {
9054         // ...with the major exception of templated-scope or
9055         // dependent-scope friend declarations.
9056
9057         // TODO: we currently also suppress this check in dependent
9058         // contexts because (1) the parameter depth will be off when
9059         // matching friend templates and (2) we might actually be
9060         // selecting a friend based on a dependent factor.  But there
9061         // are situations where these conditions don't apply and we
9062         // can actually do this check immediately.
9063         if (isFriend &&
9064             (TemplateParamLists.size() ||
9065              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9066              CurContext->isDependentContext())) {
9067           // ignore these
9068         } else {
9069           // The user tried to provide an out-of-line definition for a
9070           // function that is a member of a class or namespace, but there
9071           // was no such member function declared (C++ [class.mfct]p2,
9072           // C++ [namespace.memdef]p2). For example:
9073           //
9074           // class X {
9075           //   void f() const;
9076           // };
9077           //
9078           // void X::f() { } // ill-formed
9079           //
9080           // Complain about this problem, and attempt to suggest close
9081           // matches (e.g., those that differ only in cv-qualifiers and
9082           // whether the parameter types are references).
9083
9084           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9085                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9086             AddToScope = ExtraArgs.AddToScope;
9087             return Result;
9088           }
9089         }
9090
9091         // Unqualified local friend declarations are required to resolve
9092         // to something.
9093       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9094         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9095                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9096           AddToScope = ExtraArgs.AddToScope;
9097           return Result;
9098         }
9099       }
9100     } else if (!D.isFunctionDefinition() &&
9101                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9102                !isFriend && !isFunctionTemplateSpecialization &&
9103                !isMemberSpecialization) {
9104       // An out-of-line member function declaration must also be a
9105       // definition (C++ [class.mfct]p2).
9106       // Note that this is not the case for explicit specializations of
9107       // function templates or member functions of class templates, per
9108       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9109       // extension for compatibility with old SWIG code which likes to
9110       // generate them.
9111       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9112         << D.getCXXScopeSpec().getRange();
9113     }
9114   }
9115
9116   ProcessPragmaWeak(S, NewFD);
9117   checkAttributesAfterMerging(*this, *NewFD);
9118
9119   AddKnownFunctionAttributes(NewFD);
9120
9121   if (NewFD->hasAttr<OverloadableAttr>() &&
9122       !NewFD->getType()->getAs<FunctionProtoType>()) {
9123     Diag(NewFD->getLocation(),
9124          diag::err_attribute_overloadable_no_prototype)
9125       << NewFD;
9126
9127     // Turn this into a variadic function with no parameters.
9128     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9129     FunctionProtoType::ExtProtoInfo EPI(
9130         Context.getDefaultCallingConvention(true, false));
9131     EPI.Variadic = true;
9132     EPI.ExtInfo = FT->getExtInfo();
9133
9134     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9135     NewFD->setType(R);
9136   }
9137
9138   // If there's a #pragma GCC visibility in scope, and this isn't a class
9139   // member, set the visibility of this function.
9140   if (!DC->isRecord() && NewFD->isExternallyVisible())
9141     AddPushedVisibilityAttribute(NewFD);
9142
9143   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9144   // marking the function.
9145   AddCFAuditedAttribute(NewFD);
9146
9147   // If this is a function definition, check if we have to apply optnone due to
9148   // a pragma.
9149   if(D.isFunctionDefinition())
9150     AddRangeBasedOptnone(NewFD);
9151
9152   // If this is the first declaration of an extern C variable, update
9153   // the map of such variables.
9154   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9155       isIncompleteDeclExternC(*this, NewFD))
9156     RegisterLocallyScopedExternCDecl(NewFD, S);
9157
9158   // Set this FunctionDecl's range up to the right paren.
9159   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9160
9161   if (D.isRedeclaration() && !Previous.empty()) {
9162     NamedDecl *Prev = Previous.getRepresentativeDecl();
9163     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9164                                    isMemberSpecialization ||
9165                                        isFunctionTemplateSpecialization,
9166                                    D.isFunctionDefinition());
9167   }
9168
9169   if (getLangOpts().CUDA) {
9170     IdentifierInfo *II = NewFD->getIdentifier();
9171     if (II &&
9172         II->isStr(getLangOpts().HIP ? "hipConfigureCall"
9173                                     : "cudaConfigureCall") &&
9174         !NewFD->isInvalidDecl() &&
9175         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9176       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9177         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9178       Context.setcudaConfigureCallDecl(NewFD);
9179     }
9180
9181     // Variadic functions, other than a *declaration* of printf, are not allowed
9182     // in device-side CUDA code, unless someone passed
9183     // -fcuda-allow-variadic-functions.
9184     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9185         (NewFD->hasAttr<CUDADeviceAttr>() ||
9186          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9187         !(II && II->isStr("printf") && NewFD->isExternC() &&
9188           !D.isFunctionDefinition())) {
9189       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9190     }
9191   }
9192
9193   MarkUnusedFileScopedDecl(NewFD);
9194
9195   if (getLangOpts().CPlusPlus) {
9196     if (FunctionTemplate) {
9197       if (NewFD->isInvalidDecl())
9198         FunctionTemplate->setInvalidDecl();
9199       return FunctionTemplate;
9200     }
9201
9202     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9203       CompleteMemberSpecialization(NewFD, Previous);
9204   }
9205
9206   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9207     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9208     if ((getLangOpts().OpenCLVersion >= 120)
9209         && (SC == SC_Static)) {
9210       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9211       D.setInvalidType();
9212     }
9213
9214     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9215     if (!NewFD->getReturnType()->isVoidType()) {
9216       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9217       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9218           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9219                                 : FixItHint());
9220       D.setInvalidType();
9221     }
9222
9223     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9224     for (auto Param : NewFD->parameters())
9225       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9226   }
9227   for (const ParmVarDecl *Param : NewFD->parameters()) {
9228     QualType PT = Param->getType();
9229
9230     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9231     // types.
9232     if (getLangOpts().OpenCLVersion >= 200) {
9233       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9234         QualType ElemTy = PipeTy->getElementType();
9235           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9236             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9237             D.setInvalidType();
9238           }
9239       }
9240     }
9241   }
9242
9243   // Here we have an function template explicit specialization at class scope.
9244   // The actual specialization will be postponed to template instatiation
9245   // time via the ClassScopeFunctionSpecializationDecl node.
9246   if (isDependentClassScopeExplicitSpecialization) {
9247     ClassScopeFunctionSpecializationDecl *NewSpec =
9248                          ClassScopeFunctionSpecializationDecl::Create(
9249                                 Context, CurContext, NewFD->getLocation(),
9250                                 cast<CXXMethodDecl>(NewFD),
9251                                 HasExplicitTemplateArgs, TemplateArgs);
9252     CurContext->addDecl(NewSpec);
9253     AddToScope = false;
9254   }
9255
9256   // Diagnose availability attributes. Availability cannot be used on functions
9257   // that are run during load/unload.
9258   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9259     if (NewFD->hasAttr<ConstructorAttr>()) {
9260       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9261           << 1;
9262       NewFD->dropAttr<AvailabilityAttr>();
9263     }
9264     if (NewFD->hasAttr<DestructorAttr>()) {
9265       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9266           << 2;
9267       NewFD->dropAttr<AvailabilityAttr>();
9268     }
9269   }
9270
9271   return NewFD;
9272 }
9273
9274 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9275 /// when __declspec(code_seg) "is applied to a class, all member functions of
9276 /// the class and nested classes -- this includes compiler-generated special
9277 /// member functions -- are put in the specified segment."
9278 /// The actual behavior is a little more complicated. The Microsoft compiler
9279 /// won't check outer classes if there is an active value from #pragma code_seg.
9280 /// The CodeSeg is always applied from the direct parent but only from outer
9281 /// classes when the #pragma code_seg stack is empty. See:
9282 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9283 /// available since MS has removed the page.
9284 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9285   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9286   if (!Method)
9287     return nullptr;
9288   const CXXRecordDecl *Parent = Method->getParent();
9289   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9290     Attr *NewAttr = SAttr->clone(S.getASTContext());
9291     NewAttr->setImplicit(true);
9292     return NewAttr;
9293   }
9294
9295   // The Microsoft compiler won't check outer classes for the CodeSeg
9296   // when the #pragma code_seg stack is active.
9297   if (S.CodeSegStack.CurrentValue)
9298    return nullptr;
9299
9300   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9301     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9302       Attr *NewAttr = SAttr->clone(S.getASTContext());
9303       NewAttr->setImplicit(true);
9304       return NewAttr;
9305     }
9306   }
9307   return nullptr;
9308 }
9309
9310 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9311 /// containing class. Otherwise it will return implicit SectionAttr if the
9312 /// function is a definition and there is an active value on CodeSegStack
9313 /// (from the current #pragma code-seg value).
9314 ///
9315 /// \param FD Function being declared.
9316 /// \param IsDefinition Whether it is a definition or just a declarartion.
9317 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9318 ///          nullptr if no attribute should be added.
9319 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9320                                                        bool IsDefinition) {
9321   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9322     return A;
9323   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9324       CodeSegStack.CurrentValue) {
9325     return SectionAttr::CreateImplicit(getASTContext(),
9326                                        SectionAttr::Declspec_allocate,
9327                                        CodeSegStack.CurrentValue->getString(),
9328                                        CodeSegStack.CurrentPragmaLocation);
9329   }
9330   return nullptr;
9331 }
9332
9333 /// Determines if we can perform a correct type check for \p D as a
9334 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9335 /// best-effort check.
9336 ///
9337 /// \param NewD The new declaration.
9338 /// \param OldD The old declaration.
9339 /// \param NewT The portion of the type of the new declaration to check.
9340 /// \param OldT The portion of the type of the old declaration to check.
9341 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9342                                           QualType NewT, QualType OldT) {
9343   if (!NewD->getLexicalDeclContext()->isDependentContext())
9344     return true;
9345
9346   // For dependently-typed local extern declarations and friends, we can't
9347   // perform a correct type check in general until instantiation:
9348   //
9349   //   int f();
9350   //   template<typename T> void g() { T f(); }
9351   //
9352   // (valid if g() is only instantiated with T = int).
9353   if (NewT->isDependentType() &&
9354       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9355     return false;
9356
9357   // Similarly, if the previous declaration was a dependent local extern
9358   // declaration, we don't really know its type yet.
9359   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9360     return false;
9361
9362   return true;
9363 }
9364
9365 /// Checks if the new declaration declared in dependent context must be
9366 /// put in the same redeclaration chain as the specified declaration.
9367 ///
9368 /// \param D Declaration that is checked.
9369 /// \param PrevDecl Previous declaration found with proper lookup method for the
9370 ///                 same declaration name.
9371 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9372 ///          belongs to.
9373 ///
9374 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9375   if (!D->getLexicalDeclContext()->isDependentContext())
9376     return true;
9377
9378   // Don't chain dependent friend function definitions until instantiation, to
9379   // permit cases like
9380   //
9381   //   void func();
9382   //   template<typename T> class C1 { friend void func() {} };
9383   //   template<typename T> class C2 { friend void func() {} };
9384   //
9385   // ... which is valid if only one of C1 and C2 is ever instantiated.
9386   //
9387   // FIXME: This need only apply to function definitions. For now, we proxy
9388   // this by checking for a file-scope function. We do not want this to apply
9389   // to friend declarations nominating member functions, because that gets in
9390   // the way of access checks.
9391   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9392     return false;
9393
9394   auto *VD = dyn_cast<ValueDecl>(D);
9395   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9396   return !VD || !PrevVD ||
9397          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9398                                         PrevVD->getType());
9399 }
9400
9401 namespace MultiVersioning {
9402 enum Type { None, Target, CPUSpecific, CPUDispatch};
9403 } // MultiVersionType
9404
9405 static MultiVersioning::Type
9406 getMultiVersionType(const FunctionDecl *FD) {
9407   if (FD->hasAttr<TargetAttr>())
9408     return MultiVersioning::Target;
9409   if (FD->hasAttr<CPUDispatchAttr>())
9410     return MultiVersioning::CPUDispatch;
9411   if (FD->hasAttr<CPUSpecificAttr>())
9412     return MultiVersioning::CPUSpecific;
9413   return MultiVersioning::None;
9414 }
9415 /// Check the target attribute of the function for MultiVersion
9416 /// validity.
9417 ///
9418 /// Returns true if there was an error, false otherwise.
9419 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9420   const auto *TA = FD->getAttr<TargetAttr>();
9421   assert(TA && "MultiVersion Candidate requires a target attribute");
9422   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9423   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9424   enum ErrType { Feature = 0, Architecture = 1 };
9425
9426   if (!ParseInfo.Architecture.empty() &&
9427       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9428     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9429         << Architecture << ParseInfo.Architecture;
9430     return true;
9431   }
9432
9433   for (const auto &Feat : ParseInfo.Features) {
9434     auto BareFeat = StringRef{Feat}.substr(1);
9435     if (Feat[0] == '-') {
9436       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9437           << Feature << ("no-" + BareFeat).str();
9438       return true;
9439     }
9440
9441     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9442         !TargetInfo.isValidFeatureName(BareFeat)) {
9443       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9444           << Feature << BareFeat;
9445       return true;
9446     }
9447   }
9448   return false;
9449 }
9450
9451 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9452                                              const FunctionDecl *NewFD,
9453                                              bool CausesMV,
9454                                              MultiVersioning::Type MVType) {
9455   enum DoesntSupport {
9456     FuncTemplates = 0,
9457     VirtFuncs = 1,
9458     DeducedReturn = 2,
9459     Constructors = 3,
9460     Destructors = 4,
9461     DeletedFuncs = 5,
9462     DefaultedFuncs = 6,
9463     ConstexprFuncs = 7,
9464   };
9465   enum Different {
9466     CallingConv = 0,
9467     ReturnType = 1,
9468     ConstexprSpec = 2,
9469     InlineSpec = 3,
9470     StorageClass = 4,
9471     Linkage = 5
9472   };
9473
9474   bool IsCPUSpecificCPUDispatchMVType =
9475       MVType == MultiVersioning::CPUDispatch ||
9476       MVType == MultiVersioning::CPUSpecific;
9477
9478   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9479     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9480     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9481     return true;
9482   }
9483
9484   if (!NewFD->getType()->getAs<FunctionProtoType>())
9485     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9486
9487   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9488     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9489     if (OldFD)
9490       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9491     return true;
9492   }
9493
9494   // For now, disallow all other attributes.  These should be opt-in, but
9495   // an analysis of all of them is a future FIXME.
9496   if (CausesMV && OldFD &&
9497       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9498     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9499         << IsCPUSpecificCPUDispatchMVType;
9500     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9501     return true;
9502   }
9503
9504   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9505     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9506            << IsCPUSpecificCPUDispatchMVType;
9507
9508   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9509     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9510            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9511
9512   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9513     if (NewCXXFD->isVirtual())
9514       return S.Diag(NewCXXFD->getLocation(),
9515                     diag::err_multiversion_doesnt_support)
9516              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9517
9518     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9519       return S.Diag(NewCXXCtor->getLocation(),
9520                     diag::err_multiversion_doesnt_support)
9521              << IsCPUSpecificCPUDispatchMVType << Constructors;
9522
9523     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9524       return S.Diag(NewCXXDtor->getLocation(),
9525                     diag::err_multiversion_doesnt_support)
9526              << IsCPUSpecificCPUDispatchMVType << Destructors;
9527   }
9528
9529   if (NewFD->isDeleted())
9530     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9531            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9532
9533   if (NewFD->isDefaulted())
9534     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9535            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9536
9537   if (NewFD->isConstexpr() && (MVType == MultiVersioning::CPUDispatch ||
9538                                MVType == MultiVersioning::CPUSpecific))
9539     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9540            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9541
9542   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9543   const auto *NewType = cast<FunctionType>(NewQType);
9544   QualType NewReturnType = NewType->getReturnType();
9545
9546   if (NewReturnType->isUndeducedType())
9547     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9548            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9549
9550   // Only allow transition to MultiVersion if it hasn't been used.
9551   if (OldFD && CausesMV && OldFD->isUsed(false))
9552     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9553
9554   // Ensure the return type is identical.
9555   if (OldFD) {
9556     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9557     const auto *OldType = cast<FunctionType>(OldQType);
9558     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9559     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9560
9561     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9562       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9563              << CallingConv;
9564
9565     QualType OldReturnType = OldType->getReturnType();
9566
9567     if (OldReturnType != NewReturnType)
9568       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9569              << ReturnType;
9570
9571     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9572       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9573              << ConstexprSpec;
9574
9575     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9576       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9577              << InlineSpec;
9578
9579     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9580       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9581              << StorageClass;
9582
9583     if (OldFD->isExternC() != NewFD->isExternC())
9584       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9585              << Linkage;
9586
9587     if (S.CheckEquivalentExceptionSpec(
9588             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9589             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9590       return true;
9591   }
9592   return false;
9593 }
9594
9595 /// Check the validity of a multiversion function declaration that is the
9596 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9597 ///
9598 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9599 ///
9600 /// Returns true if there was an error, false otherwise.
9601 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9602                                            MultiVersioning::Type MVType,
9603                                            const TargetAttr *TA,
9604                                            const CPUDispatchAttr *CPUDisp,
9605                                            const CPUSpecificAttr *CPUSpec) {
9606   assert(MVType != MultiVersioning::None &&
9607          "Function lacks multiversion attribute");
9608
9609   // Target only causes MV if it is default, otherwise this is a normal
9610   // function.
9611   if (MVType == MultiVersioning::Target && !TA->isDefaultVersion())
9612     return false;
9613
9614   if (MVType == MultiVersioning::Target && CheckMultiVersionValue(S, FD)) {
9615     FD->setInvalidDecl();
9616     return true;
9617   }
9618
9619   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9620     FD->setInvalidDecl();
9621     return true;
9622   }
9623
9624   FD->setIsMultiVersion();
9625   return false;
9626 }
9627
9628 static bool CheckTargetCausesMultiVersioning(
9629     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9630     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9631     LookupResult &Previous) {
9632   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9633   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9634   // Sort order doesn't matter, it just needs to be consistent.
9635   llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9636
9637   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9638   // to change, this is a simple redeclaration.
9639   if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9640     return false;
9641
9642   // Otherwise, this decl causes MultiVersioning.
9643   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9644     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9645     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9646     NewFD->setInvalidDecl();
9647     return true;
9648   }
9649
9650   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9651                                        MultiVersioning::Target)) {
9652     NewFD->setInvalidDecl();
9653     return true;
9654   }
9655
9656   if (CheckMultiVersionValue(S, NewFD)) {
9657     NewFD->setInvalidDecl();
9658     return true;
9659   }
9660
9661   if (CheckMultiVersionValue(S, OldFD)) {
9662     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9663     NewFD->setInvalidDecl();
9664     return true;
9665   }
9666
9667   TargetAttr::ParsedTargetAttr OldParsed =
9668       OldTA->parse(std::less<std::string>());
9669
9670   if (OldParsed == NewParsed) {
9671     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9672     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9673     NewFD->setInvalidDecl();
9674     return true;
9675   }
9676
9677   for (const auto *FD : OldFD->redecls()) {
9678     const auto *CurTA = FD->getAttr<TargetAttr>();
9679     if (!CurTA || CurTA->isInherited()) {
9680       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9681           << 0;
9682       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9683       NewFD->setInvalidDecl();
9684       return true;
9685     }
9686   }
9687
9688   OldFD->setIsMultiVersion();
9689   NewFD->setIsMultiVersion();
9690   Redeclaration = false;
9691   MergeTypeWithPrevious = false;
9692   OldDecl = nullptr;
9693   Previous.clear();
9694   return false;
9695 }
9696
9697 /// Check the validity of a new function declaration being added to an existing
9698 /// multiversioned declaration collection.
9699 static bool CheckMultiVersionAdditionalDecl(
9700     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9701     MultiVersioning::Type NewMVType, const TargetAttr *NewTA,
9702     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9703     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9704     LookupResult &Previous) {
9705
9706   MultiVersioning::Type OldMVType = getMultiVersionType(OldFD);
9707   // Disallow mixing of multiversioning types.
9708   if ((OldMVType == MultiVersioning::Target &&
9709        NewMVType != MultiVersioning::Target) ||
9710       (NewMVType == MultiVersioning::Target &&
9711        OldMVType != MultiVersioning::Target)) {
9712     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9713     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9714     NewFD->setInvalidDecl();
9715     return true;
9716   }
9717
9718   TargetAttr::ParsedTargetAttr NewParsed;
9719   if (NewTA) {
9720     NewParsed = NewTA->parse();
9721     llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9722   }
9723
9724   bool UseMemberUsingDeclRules =
9725       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9726
9727   // Next, check ALL non-overloads to see if this is a redeclaration of a
9728   // previous member of the MultiVersion set.
9729   for (NamedDecl *ND : Previous) {
9730     FunctionDecl *CurFD = ND->getAsFunction();
9731     if (!CurFD)
9732       continue;
9733     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9734       continue;
9735
9736     if (NewMVType == MultiVersioning::Target) {
9737       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9738       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9739         NewFD->setIsMultiVersion();
9740         Redeclaration = true;
9741         OldDecl = ND;
9742         return false;
9743       }
9744
9745       TargetAttr::ParsedTargetAttr CurParsed =
9746           CurTA->parse(std::less<std::string>());
9747       if (CurParsed == NewParsed) {
9748         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9749         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9750         NewFD->setInvalidDecl();
9751         return true;
9752       }
9753     } else {
9754       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9755       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9756       // Handle CPUDispatch/CPUSpecific versions.
9757       // Only 1 CPUDispatch function is allowed, this will make it go through
9758       // the redeclaration errors.
9759       if (NewMVType == MultiVersioning::CPUDispatch &&
9760           CurFD->hasAttr<CPUDispatchAttr>()) {
9761         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9762             std::equal(
9763                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9764                 NewCPUDisp->cpus_begin(),
9765                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9766                   return Cur->getName() == New->getName();
9767                 })) {
9768           NewFD->setIsMultiVersion();
9769           Redeclaration = true;
9770           OldDecl = ND;
9771           return false;
9772         }
9773
9774         // If the declarations don't match, this is an error condition.
9775         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9776         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9777         NewFD->setInvalidDecl();
9778         return true;
9779       }
9780       if (NewMVType == MultiVersioning::CPUSpecific && CurCPUSpec) {
9781
9782         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9783             std::equal(
9784                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9785                 NewCPUSpec->cpus_begin(),
9786                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9787                   return Cur->getName() == New->getName();
9788                 })) {
9789           NewFD->setIsMultiVersion();
9790           Redeclaration = true;
9791           OldDecl = ND;
9792           return false;
9793         }
9794
9795         // Only 1 version of CPUSpecific is allowed for each CPU.
9796         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9797           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9798             if (CurII == NewII) {
9799               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9800                   << NewII;
9801               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9802               NewFD->setInvalidDecl();
9803               return true;
9804             }
9805           }
9806         }
9807       }
9808       // If the two decls aren't the same MVType, there is no possible error
9809       // condition.
9810     }
9811   }
9812
9813   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9814   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9815   // handled in the attribute adding step.
9816   if (NewMVType == MultiVersioning::Target &&
9817       CheckMultiVersionValue(S, NewFD)) {
9818     NewFD->setInvalidDecl();
9819     return true;
9820   }
9821
9822   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) {
9823     NewFD->setInvalidDecl();
9824     return true;
9825   }
9826
9827   NewFD->setIsMultiVersion();
9828   Redeclaration = false;
9829   MergeTypeWithPrevious = false;
9830   OldDecl = nullptr;
9831   Previous.clear();
9832   return false;
9833 }
9834
9835
9836 /// Check the validity of a mulitversion function declaration.
9837 /// Also sets the multiversion'ness' of the function itself.
9838 ///
9839 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9840 ///
9841 /// Returns true if there was an error, false otherwise.
9842 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9843                                       bool &Redeclaration, NamedDecl *&OldDecl,
9844                                       bool &MergeTypeWithPrevious,
9845                                       LookupResult &Previous) {
9846   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9847   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9848   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9849
9850   // Mixing Multiversioning types is prohibited.
9851   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9852       (NewCPUDisp && NewCPUSpec)) {
9853     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9854     NewFD->setInvalidDecl();
9855     return true;
9856   }
9857
9858   MultiVersioning::Type MVType = getMultiVersionType(NewFD);
9859
9860   // Main isn't allowed to become a multiversion function, however it IS
9861   // permitted to have 'main' be marked with the 'target' optimization hint.
9862   if (NewFD->isMain()) {
9863     if ((MVType == MultiVersioning::Target && NewTA->isDefaultVersion()) ||
9864         MVType == MultiVersioning::CPUDispatch ||
9865         MVType == MultiVersioning::CPUSpecific) {
9866       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9867       NewFD->setInvalidDecl();
9868       return true;
9869     }
9870     return false;
9871   }
9872
9873   if (!OldDecl || !OldDecl->getAsFunction() ||
9874       OldDecl->getDeclContext()->getRedeclContext() !=
9875           NewFD->getDeclContext()->getRedeclContext()) {
9876     // If there's no previous declaration, AND this isn't attempting to cause
9877     // multiversioning, this isn't an error condition.
9878     if (MVType == MultiVersioning::None)
9879       return false;
9880     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9881                                           NewCPUSpec);
9882   }
9883
9884   FunctionDecl *OldFD = OldDecl->getAsFunction();
9885
9886   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::None)
9887     return false;
9888
9889   if (OldFD->isMultiVersion() && MVType == MultiVersioning::None) {
9890     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9891         << (getMultiVersionType(OldFD) != MultiVersioning::Target);
9892     NewFD->setInvalidDecl();
9893     return true;
9894   }
9895
9896   // Handle the target potentially causes multiversioning case.
9897   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::Target)
9898     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9899                                             Redeclaration, OldDecl,
9900                                             MergeTypeWithPrevious, Previous);
9901   // Previous declarations lack CPUDispatch/CPUSpecific.
9902   if (!OldFD->isMultiVersion()) {
9903     S.Diag(OldFD->getLocation(), diag::err_multiversion_required_in_redecl)
9904         << 1;
9905     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9906     NewFD->setInvalidDecl();
9907     return true;
9908   }
9909
9910   // At this point, we have a multiversion function decl (in OldFD) AND an
9911   // appropriate attribute in the current function decl.  Resolve that these are
9912   // still compatible with previous declarations.
9913   return CheckMultiVersionAdditionalDecl(
9914       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9915       OldDecl, MergeTypeWithPrevious, Previous);
9916 }
9917
9918 /// Perform semantic checking of a new function declaration.
9919 ///
9920 /// Performs semantic analysis of the new function declaration
9921 /// NewFD. This routine performs all semantic checking that does not
9922 /// require the actual declarator involved in the declaration, and is
9923 /// used both for the declaration of functions as they are parsed
9924 /// (called via ActOnDeclarator) and for the declaration of functions
9925 /// that have been instantiated via C++ template instantiation (called
9926 /// via InstantiateDecl).
9927 ///
9928 /// \param IsMemberSpecialization whether this new function declaration is
9929 /// a member specialization (that replaces any definition provided by the
9930 /// previous declaration).
9931 ///
9932 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9933 ///
9934 /// \returns true if the function declaration is a redeclaration.
9935 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9936                                     LookupResult &Previous,
9937                                     bool IsMemberSpecialization) {
9938   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9939          "Variably modified return types are not handled here");
9940
9941   // Determine whether the type of this function should be merged with
9942   // a previous visible declaration. This never happens for functions in C++,
9943   // and always happens in C if the previous declaration was visible.
9944   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9945                                !Previous.isShadowed();
9946
9947   bool Redeclaration = false;
9948   NamedDecl *OldDecl = nullptr;
9949   bool MayNeedOverloadableChecks = false;
9950
9951   // Merge or overload the declaration with an existing declaration of
9952   // the same name, if appropriate.
9953   if (!Previous.empty()) {
9954     // Determine whether NewFD is an overload of PrevDecl or
9955     // a declaration that requires merging. If it's an overload,
9956     // there's no more work to do here; we'll just add the new
9957     // function to the scope.
9958     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9959       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9960       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9961         Redeclaration = true;
9962         OldDecl = Candidate;
9963       }
9964     } else {
9965       MayNeedOverloadableChecks = true;
9966       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9967                             /*NewIsUsingDecl*/ false)) {
9968       case Ovl_Match:
9969         Redeclaration = true;
9970         break;
9971
9972       case Ovl_NonFunction:
9973         Redeclaration = true;
9974         break;
9975
9976       case Ovl_Overload:
9977         Redeclaration = false;
9978         break;
9979       }
9980     }
9981   }
9982
9983   // Check for a previous extern "C" declaration with this name.
9984   if (!Redeclaration &&
9985       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9986     if (!Previous.empty()) {
9987       // This is an extern "C" declaration with the same name as a previous
9988       // declaration, and thus redeclares that entity...
9989       Redeclaration = true;
9990       OldDecl = Previous.getFoundDecl();
9991       MergeTypeWithPrevious = false;
9992
9993       // ... except in the presence of __attribute__((overloadable)).
9994       if (OldDecl->hasAttr<OverloadableAttr>() ||
9995           NewFD->hasAttr<OverloadableAttr>()) {
9996         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9997           MayNeedOverloadableChecks = true;
9998           Redeclaration = false;
9999           OldDecl = nullptr;
10000         }
10001       }
10002     }
10003   }
10004
10005   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10006                                 MergeTypeWithPrevious, Previous))
10007     return Redeclaration;
10008
10009   // C++11 [dcl.constexpr]p8:
10010   //   A constexpr specifier for a non-static member function that is not
10011   //   a constructor declares that member function to be const.
10012   //
10013   // This needs to be delayed until we know whether this is an out-of-line
10014   // definition of a static member function.
10015   //
10016   // This rule is not present in C++1y, so we produce a backwards
10017   // compatibility warning whenever it happens in C++11.
10018   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10019   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10020       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10021       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
10022     CXXMethodDecl *OldMD = nullptr;
10023     if (OldDecl)
10024       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10025     if (!OldMD || !OldMD->isStatic()) {
10026       const FunctionProtoType *FPT =
10027         MD->getType()->castAs<FunctionProtoType>();
10028       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10029       EPI.TypeQuals |= Qualifiers::Const;
10030       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10031                                           FPT->getParamTypes(), EPI));
10032
10033       // Warn that we did this, if we're not performing template instantiation.
10034       // In that case, we'll have warned already when the template was defined.
10035       if (!inTemplateInstantiation()) {
10036         SourceLocation AddConstLoc;
10037         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10038                 .IgnoreParens().getAs<FunctionTypeLoc>())
10039           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10040
10041         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10042           << FixItHint::CreateInsertion(AddConstLoc, " const");
10043       }
10044     }
10045   }
10046
10047   if (Redeclaration) {
10048     // NewFD and OldDecl represent declarations that need to be
10049     // merged.
10050     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10051       NewFD->setInvalidDecl();
10052       return Redeclaration;
10053     }
10054
10055     Previous.clear();
10056     Previous.addDecl(OldDecl);
10057
10058     if (FunctionTemplateDecl *OldTemplateDecl =
10059             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10060       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10061       NewFD->setPreviousDeclaration(OldFD);
10062       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10063       FunctionTemplateDecl *NewTemplateDecl
10064         = NewFD->getDescribedFunctionTemplate();
10065       assert(NewTemplateDecl && "Template/non-template mismatch");
10066       if (NewFD->isCXXClassMember()) {
10067         NewFD->setAccess(OldTemplateDecl->getAccess());
10068         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10069       }
10070
10071       // If this is an explicit specialization of a member that is a function
10072       // template, mark it as a member specialization.
10073       if (IsMemberSpecialization &&
10074           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10075         NewTemplateDecl->setMemberSpecialization();
10076         assert(OldTemplateDecl->isMemberSpecialization());
10077         // Explicit specializations of a member template do not inherit deleted
10078         // status from the parent member template that they are specializing.
10079         if (OldFD->isDeleted()) {
10080           // FIXME: This assert will not hold in the presence of modules.
10081           assert(OldFD->getCanonicalDecl() == OldFD);
10082           // FIXME: We need an update record for this AST mutation.
10083           OldFD->setDeletedAsWritten(false);
10084         }
10085       }
10086
10087     } else {
10088       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10089         auto *OldFD = cast<FunctionDecl>(OldDecl);
10090         // This needs to happen first so that 'inline' propagates.
10091         NewFD->setPreviousDeclaration(OldFD);
10092         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10093         if (NewFD->isCXXClassMember())
10094           NewFD->setAccess(OldFD->getAccess());
10095       }
10096     }
10097   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10098              !NewFD->getAttr<OverloadableAttr>()) {
10099     assert((Previous.empty() ||
10100             llvm::any_of(Previous,
10101                          [](const NamedDecl *ND) {
10102                            return ND->hasAttr<OverloadableAttr>();
10103                          })) &&
10104            "Non-redecls shouldn't happen without overloadable present");
10105
10106     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10107       const auto *FD = dyn_cast<FunctionDecl>(ND);
10108       return FD && !FD->hasAttr<OverloadableAttr>();
10109     });
10110
10111     if (OtherUnmarkedIter != Previous.end()) {
10112       Diag(NewFD->getLocation(),
10113            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10114       Diag((*OtherUnmarkedIter)->getLocation(),
10115            diag::note_attribute_overloadable_prev_overload)
10116           << false;
10117
10118       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10119     }
10120   }
10121
10122   // Semantic checking for this function declaration (in isolation).
10123
10124   if (getLangOpts().CPlusPlus) {
10125     // C++-specific checks.
10126     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10127       CheckConstructor(Constructor);
10128     } else if (CXXDestructorDecl *Destructor =
10129                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10130       CXXRecordDecl *Record = Destructor->getParent();
10131       QualType ClassType = Context.getTypeDeclType(Record);
10132
10133       // FIXME: Shouldn't we be able to perform this check even when the class
10134       // type is dependent? Both gcc and edg can handle that.
10135       if (!ClassType->isDependentType()) {
10136         DeclarationName Name
10137           = Context.DeclarationNames.getCXXDestructorName(
10138                                         Context.getCanonicalType(ClassType));
10139         if (NewFD->getDeclName() != Name) {
10140           Diag(NewFD->getLocation(), diag::err_destructor_name);
10141           NewFD->setInvalidDecl();
10142           return Redeclaration;
10143         }
10144       }
10145     } else if (CXXConversionDecl *Conversion
10146                = dyn_cast<CXXConversionDecl>(NewFD)) {
10147       ActOnConversionDeclarator(Conversion);
10148     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10149       if (auto *TD = Guide->getDescribedFunctionTemplate())
10150         CheckDeductionGuideTemplate(TD);
10151
10152       // A deduction guide is not on the list of entities that can be
10153       // explicitly specialized.
10154       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10155         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
10156             << /*explicit specialization*/ 1;
10157     }
10158
10159     // Find any virtual functions that this function overrides.
10160     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10161       if (!Method->isFunctionTemplateSpecialization() &&
10162           !Method->getDescribedFunctionTemplate() &&
10163           Method->isCanonicalDecl()) {
10164         if (AddOverriddenMethods(Method->getParent(), Method)) {
10165           // If the function was marked as "static", we have a problem.
10166           if (NewFD->getStorageClass() == SC_Static) {
10167             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10168           }
10169         }
10170       }
10171
10172       if (Method->isStatic())
10173         checkThisInStaticMemberFunctionType(Method);
10174     }
10175
10176     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10177     if (NewFD->isOverloadedOperator() &&
10178         CheckOverloadedOperatorDeclaration(NewFD)) {
10179       NewFD->setInvalidDecl();
10180       return Redeclaration;
10181     }
10182
10183     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10184     if (NewFD->getLiteralIdentifier() &&
10185         CheckLiteralOperatorDeclaration(NewFD)) {
10186       NewFD->setInvalidDecl();
10187       return Redeclaration;
10188     }
10189
10190     // In C++, check default arguments now that we have merged decls. Unless
10191     // the lexical context is the class, because in this case this is done
10192     // during delayed parsing anyway.
10193     if (!CurContext->isRecord())
10194       CheckCXXDefaultArguments(NewFD);
10195
10196     // If this function declares a builtin function, check the type of this
10197     // declaration against the expected type for the builtin.
10198     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10199       ASTContext::GetBuiltinTypeError Error;
10200       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10201       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10202       // If the type of the builtin differs only in its exception
10203       // specification, that's OK.
10204       // FIXME: If the types do differ in this way, it would be better to
10205       // retain the 'noexcept' form of the type.
10206       if (!T.isNull() &&
10207           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10208                                                             NewFD->getType()))
10209         // The type of this function differs from the type of the builtin,
10210         // so forget about the builtin entirely.
10211         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10212     }
10213
10214     // If this function is declared as being extern "C", then check to see if
10215     // the function returns a UDT (class, struct, or union type) that is not C
10216     // compatible, and if it does, warn the user.
10217     // But, issue any diagnostic on the first declaration only.
10218     if (Previous.empty() && NewFD->isExternC()) {
10219       QualType R = NewFD->getReturnType();
10220       if (R->isIncompleteType() && !R->isVoidType())
10221         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10222             << NewFD << R;
10223       else if (!R.isPODType(Context) && !R->isVoidType() &&
10224                !R->isObjCObjectPointerType())
10225         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10226     }
10227
10228     // C++1z [dcl.fct]p6:
10229     //   [...] whether the function has a non-throwing exception-specification
10230     //   [is] part of the function type
10231     //
10232     // This results in an ABI break between C++14 and C++17 for functions whose
10233     // declared type includes an exception-specification in a parameter or
10234     // return type. (Exception specifications on the function itself are OK in
10235     // most cases, and exception specifications are not permitted in most other
10236     // contexts where they could make it into a mangling.)
10237     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10238       auto HasNoexcept = [&](QualType T) -> bool {
10239         // Strip off declarator chunks that could be between us and a function
10240         // type. We don't need to look far, exception specifications are very
10241         // restricted prior to C++17.
10242         if (auto *RT = T->getAs<ReferenceType>())
10243           T = RT->getPointeeType();
10244         else if (T->isAnyPointerType())
10245           T = T->getPointeeType();
10246         else if (auto *MPT = T->getAs<MemberPointerType>())
10247           T = MPT->getPointeeType();
10248         if (auto *FPT = T->getAs<FunctionProtoType>())
10249           if (FPT->isNothrow())
10250             return true;
10251         return false;
10252       };
10253
10254       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10255       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10256       for (QualType T : FPT->param_types())
10257         AnyNoexcept |= HasNoexcept(T);
10258       if (AnyNoexcept)
10259         Diag(NewFD->getLocation(),
10260              diag::warn_cxx17_compat_exception_spec_in_signature)
10261             << NewFD;
10262     }
10263
10264     if (!Redeclaration && LangOpts.CUDA)
10265       checkCUDATargetOverload(NewFD, Previous);
10266   }
10267   return Redeclaration;
10268 }
10269
10270 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10271   // C++11 [basic.start.main]p3:
10272   //   A program that [...] declares main to be inline, static or
10273   //   constexpr is ill-formed.
10274   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10275   //   appear in a declaration of main.
10276   // static main is not an error under C99, but we should warn about it.
10277   // We accept _Noreturn main as an extension.
10278   if (FD->getStorageClass() == SC_Static)
10279     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10280          ? diag::err_static_main : diag::warn_static_main)
10281       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10282   if (FD->isInlineSpecified())
10283     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10284       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10285   if (DS.isNoreturnSpecified()) {
10286     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10287     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10288     Diag(NoreturnLoc, diag::ext_noreturn_main);
10289     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10290       << FixItHint::CreateRemoval(NoreturnRange);
10291   }
10292   if (FD->isConstexpr()) {
10293     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10294       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10295     FD->setConstexpr(false);
10296   }
10297
10298   if (getLangOpts().OpenCL) {
10299     Diag(FD->getLocation(), diag::err_opencl_no_main)
10300         << FD->hasAttr<OpenCLKernelAttr>();
10301     FD->setInvalidDecl();
10302     return;
10303   }
10304
10305   QualType T = FD->getType();
10306   assert(T->isFunctionType() && "function decl is not of function type");
10307   const FunctionType* FT = T->castAs<FunctionType>();
10308
10309   // Set default calling convention for main()
10310   if (FT->getCallConv() != CC_C) {
10311     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10312     FD->setType(QualType(FT, 0));
10313     T = Context.getCanonicalType(FD->getType());
10314   }
10315
10316   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10317     // In C with GNU extensions we allow main() to have non-integer return
10318     // type, but we should warn about the extension, and we disable the
10319     // implicit-return-zero rule.
10320
10321     // GCC in C mode accepts qualified 'int'.
10322     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10323       FD->setHasImplicitReturnZero(true);
10324     else {
10325       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10326       SourceRange RTRange = FD->getReturnTypeSourceRange();
10327       if (RTRange.isValid())
10328         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10329             << FixItHint::CreateReplacement(RTRange, "int");
10330     }
10331   } else {
10332     // In C and C++, main magically returns 0 if you fall off the end;
10333     // set the flag which tells us that.
10334     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10335
10336     // All the standards say that main() should return 'int'.
10337     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10338       FD->setHasImplicitReturnZero(true);
10339     else {
10340       // Otherwise, this is just a flat-out error.
10341       SourceRange RTRange = FD->getReturnTypeSourceRange();
10342       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10343           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10344                                 : FixItHint());
10345       FD->setInvalidDecl(true);
10346     }
10347   }
10348
10349   // Treat protoless main() as nullary.
10350   if (isa<FunctionNoProtoType>(FT)) return;
10351
10352   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10353   unsigned nparams = FTP->getNumParams();
10354   assert(FD->getNumParams() == nparams);
10355
10356   bool HasExtraParameters = (nparams > 3);
10357
10358   if (FTP->isVariadic()) {
10359     Diag(FD->getLocation(), diag::ext_variadic_main);
10360     // FIXME: if we had information about the location of the ellipsis, we
10361     // could add a FixIt hint to remove it as a parameter.
10362   }
10363
10364   // Darwin passes an undocumented fourth argument of type char**.  If
10365   // other platforms start sprouting these, the logic below will start
10366   // getting shifty.
10367   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10368     HasExtraParameters = false;
10369
10370   if (HasExtraParameters) {
10371     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10372     FD->setInvalidDecl(true);
10373     nparams = 3;
10374   }
10375
10376   // FIXME: a lot of the following diagnostics would be improved
10377   // if we had some location information about types.
10378
10379   QualType CharPP =
10380     Context.getPointerType(Context.getPointerType(Context.CharTy));
10381   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10382
10383   for (unsigned i = 0; i < nparams; ++i) {
10384     QualType AT = FTP->getParamType(i);
10385
10386     bool mismatch = true;
10387
10388     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10389       mismatch = false;
10390     else if (Expected[i] == CharPP) {
10391       // As an extension, the following forms are okay:
10392       //   char const **
10393       //   char const * const *
10394       //   char * const *
10395
10396       QualifierCollector qs;
10397       const PointerType* PT;
10398       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10399           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10400           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10401                               Context.CharTy)) {
10402         qs.removeConst();
10403         mismatch = !qs.empty();
10404       }
10405     }
10406
10407     if (mismatch) {
10408       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10409       // TODO: suggest replacing given type with expected type
10410       FD->setInvalidDecl(true);
10411     }
10412   }
10413
10414   if (nparams == 1 && !FD->isInvalidDecl()) {
10415     Diag(FD->getLocation(), diag::warn_main_one_arg);
10416   }
10417
10418   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10419     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10420     FD->setInvalidDecl();
10421   }
10422 }
10423
10424 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10425   QualType T = FD->getType();
10426   assert(T->isFunctionType() && "function decl is not of function type");
10427   const FunctionType *FT = T->castAs<FunctionType>();
10428
10429   // Set an implicit return of 'zero' if the function can return some integral,
10430   // enumeration, pointer or nullptr type.
10431   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10432       FT->getReturnType()->isAnyPointerType() ||
10433       FT->getReturnType()->isNullPtrType())
10434     // DllMain is exempt because a return value of zero means it failed.
10435     if (FD->getName() != "DllMain")
10436       FD->setHasImplicitReturnZero(true);
10437
10438   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10439     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10440     FD->setInvalidDecl();
10441   }
10442 }
10443
10444 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10445   // FIXME: Need strict checking.  In C89, we need to check for
10446   // any assignment, increment, decrement, function-calls, or
10447   // commas outside of a sizeof.  In C99, it's the same list,
10448   // except that the aforementioned are allowed in unevaluated
10449   // expressions.  Everything else falls under the
10450   // "may accept other forms of constant expressions" exception.
10451   // (We never end up here for C++, so the constant expression
10452   // rules there don't matter.)
10453   const Expr *Culprit;
10454   if (Init->isConstantInitializer(Context, false, &Culprit))
10455     return false;
10456   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10457     << Culprit->getSourceRange();
10458   return true;
10459 }
10460
10461 namespace {
10462   // Visits an initialization expression to see if OrigDecl is evaluated in
10463   // its own initialization and throws a warning if it does.
10464   class SelfReferenceChecker
10465       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10466     Sema &S;
10467     Decl *OrigDecl;
10468     bool isRecordType;
10469     bool isPODType;
10470     bool isReferenceType;
10471
10472     bool isInitList;
10473     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10474
10475   public:
10476     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10477
10478     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10479                                                     S(S), OrigDecl(OrigDecl) {
10480       isPODType = false;
10481       isRecordType = false;
10482       isReferenceType = false;
10483       isInitList = false;
10484       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10485         isPODType = VD->getType().isPODType(S.Context);
10486         isRecordType = VD->getType()->isRecordType();
10487         isReferenceType = VD->getType()->isReferenceType();
10488       }
10489     }
10490
10491     // For most expressions, just call the visitor.  For initializer lists,
10492     // track the index of the field being initialized since fields are
10493     // initialized in order allowing use of previously initialized fields.
10494     void CheckExpr(Expr *E) {
10495       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10496       if (!InitList) {
10497         Visit(E);
10498         return;
10499       }
10500
10501       // Track and increment the index here.
10502       isInitList = true;
10503       InitFieldIndex.push_back(0);
10504       for (auto Child : InitList->children()) {
10505         CheckExpr(cast<Expr>(Child));
10506         ++InitFieldIndex.back();
10507       }
10508       InitFieldIndex.pop_back();
10509     }
10510
10511     // Returns true if MemberExpr is checked and no further checking is needed.
10512     // Returns false if additional checking is required.
10513     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10514       llvm::SmallVector<FieldDecl*, 4> Fields;
10515       Expr *Base = E;
10516       bool ReferenceField = false;
10517
10518       // Get the field memebers used.
10519       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10520         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10521         if (!FD)
10522           return false;
10523         Fields.push_back(FD);
10524         if (FD->getType()->isReferenceType())
10525           ReferenceField = true;
10526         Base = ME->getBase()->IgnoreParenImpCasts();
10527       }
10528
10529       // Keep checking only if the base Decl is the same.
10530       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10531       if (!DRE || DRE->getDecl() != OrigDecl)
10532         return false;
10533
10534       // A reference field can be bound to an unininitialized field.
10535       if (CheckReference && !ReferenceField)
10536         return true;
10537
10538       // Convert FieldDecls to their index number.
10539       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10540       for (const FieldDecl *I : llvm::reverse(Fields))
10541         UsedFieldIndex.push_back(I->getFieldIndex());
10542
10543       // See if a warning is needed by checking the first difference in index
10544       // numbers.  If field being used has index less than the field being
10545       // initialized, then the use is safe.
10546       for (auto UsedIter = UsedFieldIndex.begin(),
10547                 UsedEnd = UsedFieldIndex.end(),
10548                 OrigIter = InitFieldIndex.begin(),
10549                 OrigEnd = InitFieldIndex.end();
10550            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10551         if (*UsedIter < *OrigIter)
10552           return true;
10553         if (*UsedIter > *OrigIter)
10554           break;
10555       }
10556
10557       // TODO: Add a different warning which will print the field names.
10558       HandleDeclRefExpr(DRE);
10559       return true;
10560     }
10561
10562     // For most expressions, the cast is directly above the DeclRefExpr.
10563     // For conditional operators, the cast can be outside the conditional
10564     // operator if both expressions are DeclRefExpr's.
10565     void HandleValue(Expr *E) {
10566       E = E->IgnoreParens();
10567       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10568         HandleDeclRefExpr(DRE);
10569         return;
10570       }
10571
10572       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10573         Visit(CO->getCond());
10574         HandleValue(CO->getTrueExpr());
10575         HandleValue(CO->getFalseExpr());
10576         return;
10577       }
10578
10579       if (BinaryConditionalOperator *BCO =
10580               dyn_cast<BinaryConditionalOperator>(E)) {
10581         Visit(BCO->getCond());
10582         HandleValue(BCO->getFalseExpr());
10583         return;
10584       }
10585
10586       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10587         HandleValue(OVE->getSourceExpr());
10588         return;
10589       }
10590
10591       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10592         if (BO->getOpcode() == BO_Comma) {
10593           Visit(BO->getLHS());
10594           HandleValue(BO->getRHS());
10595           return;
10596         }
10597       }
10598
10599       if (isa<MemberExpr>(E)) {
10600         if (isInitList) {
10601           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10602                                       false /*CheckReference*/))
10603             return;
10604         }
10605
10606         Expr *Base = E->IgnoreParenImpCasts();
10607         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10608           // Check for static member variables and don't warn on them.
10609           if (!isa<FieldDecl>(ME->getMemberDecl()))
10610             return;
10611           Base = ME->getBase()->IgnoreParenImpCasts();
10612         }
10613         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10614           HandleDeclRefExpr(DRE);
10615         return;
10616       }
10617
10618       Visit(E);
10619     }
10620
10621     // Reference types not handled in HandleValue are handled here since all
10622     // uses of references are bad, not just r-value uses.
10623     void VisitDeclRefExpr(DeclRefExpr *E) {
10624       if (isReferenceType)
10625         HandleDeclRefExpr(E);
10626     }
10627
10628     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10629       if (E->getCastKind() == CK_LValueToRValue) {
10630         HandleValue(E->getSubExpr());
10631         return;
10632       }
10633
10634       Inherited::VisitImplicitCastExpr(E);
10635     }
10636
10637     void VisitMemberExpr(MemberExpr *E) {
10638       if (isInitList) {
10639         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10640           return;
10641       }
10642
10643       // Don't warn on arrays since they can be treated as pointers.
10644       if (E->getType()->canDecayToPointerType()) return;
10645
10646       // Warn when a non-static method call is followed by non-static member
10647       // field accesses, which is followed by a DeclRefExpr.
10648       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10649       bool Warn = (MD && !MD->isStatic());
10650       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10651       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10652         if (!isa<FieldDecl>(ME->getMemberDecl()))
10653           Warn = false;
10654         Base = ME->getBase()->IgnoreParenImpCasts();
10655       }
10656
10657       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10658         if (Warn)
10659           HandleDeclRefExpr(DRE);
10660         return;
10661       }
10662
10663       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10664       // Visit that expression.
10665       Visit(Base);
10666     }
10667
10668     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10669       Expr *Callee = E->getCallee();
10670
10671       if (isa<UnresolvedLookupExpr>(Callee))
10672         return Inherited::VisitCXXOperatorCallExpr(E);
10673
10674       Visit(Callee);
10675       for (auto Arg: E->arguments())
10676         HandleValue(Arg->IgnoreParenImpCasts());
10677     }
10678
10679     void VisitUnaryOperator(UnaryOperator *E) {
10680       // For POD record types, addresses of its own members are well-defined.
10681       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10682           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10683         if (!isPODType)
10684           HandleValue(E->getSubExpr());
10685         return;
10686       }
10687
10688       if (E->isIncrementDecrementOp()) {
10689         HandleValue(E->getSubExpr());
10690         return;
10691       }
10692
10693       Inherited::VisitUnaryOperator(E);
10694     }
10695
10696     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10697
10698     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10699       if (E->getConstructor()->isCopyConstructor()) {
10700         Expr *ArgExpr = E->getArg(0);
10701         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10702           if (ILE->getNumInits() == 1)
10703             ArgExpr = ILE->getInit(0);
10704         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10705           if (ICE->getCastKind() == CK_NoOp)
10706             ArgExpr = ICE->getSubExpr();
10707         HandleValue(ArgExpr);
10708         return;
10709       }
10710       Inherited::VisitCXXConstructExpr(E);
10711     }
10712
10713     void VisitCallExpr(CallExpr *E) {
10714       // Treat std::move as a use.
10715       if (E->isCallToStdMove()) {
10716         HandleValue(E->getArg(0));
10717         return;
10718       }
10719
10720       Inherited::VisitCallExpr(E);
10721     }
10722
10723     void VisitBinaryOperator(BinaryOperator *E) {
10724       if (E->isCompoundAssignmentOp()) {
10725         HandleValue(E->getLHS());
10726         Visit(E->getRHS());
10727         return;
10728       }
10729
10730       Inherited::VisitBinaryOperator(E);
10731     }
10732
10733     // A custom visitor for BinaryConditionalOperator is needed because the
10734     // regular visitor would check the condition and true expression separately
10735     // but both point to the same place giving duplicate diagnostics.
10736     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10737       Visit(E->getCond());
10738       Visit(E->getFalseExpr());
10739     }
10740
10741     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10742       Decl* ReferenceDecl = DRE->getDecl();
10743       if (OrigDecl != ReferenceDecl) return;
10744       unsigned diag;
10745       if (isReferenceType) {
10746         diag = diag::warn_uninit_self_reference_in_reference_init;
10747       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10748         diag = diag::warn_static_self_reference_in_init;
10749       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10750                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10751                  DRE->getDecl()->getType()->isRecordType()) {
10752         diag = diag::warn_uninit_self_reference_in_init;
10753       } else {
10754         // Local variables will be handled by the CFG analysis.
10755         return;
10756       }
10757
10758       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10759                             S.PDiag(diag)
10760                               << DRE->getDecl()
10761                               << OrigDecl->getLocation()
10762                               << DRE->getSourceRange());
10763     }
10764   };
10765
10766   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10767   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10768                                  bool DirectInit) {
10769     // Parameters arguments are occassionially constructed with itself,
10770     // for instance, in recursive functions.  Skip them.
10771     if (isa<ParmVarDecl>(OrigDecl))
10772       return;
10773
10774     E = E->IgnoreParens();
10775
10776     // Skip checking T a = a where T is not a record or reference type.
10777     // Doing so is a way to silence uninitialized warnings.
10778     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10779       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10780         if (ICE->getCastKind() == CK_LValueToRValue)
10781           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10782             if (DRE->getDecl() == OrigDecl)
10783               return;
10784
10785     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10786   }
10787 } // end anonymous namespace
10788
10789 namespace {
10790   // Simple wrapper to add the name of a variable or (if no variable is
10791   // available) a DeclarationName into a diagnostic.
10792   struct VarDeclOrName {
10793     VarDecl *VDecl;
10794     DeclarationName Name;
10795
10796     friend const Sema::SemaDiagnosticBuilder &
10797     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10798       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10799     }
10800   };
10801 } // end anonymous namespace
10802
10803 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10804                                             DeclarationName Name, QualType Type,
10805                                             TypeSourceInfo *TSI,
10806                                             SourceRange Range, bool DirectInit,
10807                                             Expr *Init) {
10808   bool IsInitCapture = !VDecl;
10809   assert((!VDecl || !VDecl->isInitCapture()) &&
10810          "init captures are expected to be deduced prior to initialization");
10811
10812   VarDeclOrName VN{VDecl, Name};
10813
10814   DeducedType *Deduced = Type->getContainedDeducedType();
10815   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10816
10817   // C++11 [dcl.spec.auto]p3
10818   if (!Init) {
10819     assert(VDecl && "no init for init capture deduction?");
10820
10821     // Except for class argument deduction, and then for an initializing
10822     // declaration only, i.e. no static at class scope or extern.
10823     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10824         VDecl->hasExternalStorage() ||
10825         VDecl->isStaticDataMember()) {
10826       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10827         << VDecl->getDeclName() << Type;
10828       return QualType();
10829     }
10830   }
10831
10832   ArrayRef<Expr*> DeduceInits;
10833   if (Init)
10834     DeduceInits = Init;
10835
10836   if (DirectInit) {
10837     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10838       DeduceInits = PL->exprs();
10839   }
10840
10841   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10842     assert(VDecl && "non-auto type for init capture deduction?");
10843     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10844     InitializationKind Kind = InitializationKind::CreateForInit(
10845         VDecl->getLocation(), DirectInit, Init);
10846     // FIXME: Initialization should not be taking a mutable list of inits.
10847     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10848     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10849                                                        InitsCopy);
10850   }
10851
10852   if (DirectInit) {
10853     if (auto *IL = dyn_cast<InitListExpr>(Init))
10854       DeduceInits = IL->inits();
10855   }
10856
10857   // Deduction only works if we have exactly one source expression.
10858   if (DeduceInits.empty()) {
10859     // It isn't possible to write this directly, but it is possible to
10860     // end up in this situation with "auto x(some_pack...);"
10861     Diag(Init->getLocStart(), IsInitCapture
10862                                   ? diag::err_init_capture_no_expression
10863                                   : diag::err_auto_var_init_no_expression)
10864         << VN << Type << Range;
10865     return QualType();
10866   }
10867
10868   if (DeduceInits.size() > 1) {
10869     Diag(DeduceInits[1]->getLocStart(),
10870          IsInitCapture ? diag::err_init_capture_multiple_expressions
10871                        : diag::err_auto_var_init_multiple_expressions)
10872         << VN << Type << Range;
10873     return QualType();
10874   }
10875
10876   Expr *DeduceInit = DeduceInits[0];
10877   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10878     Diag(Init->getLocStart(), IsInitCapture
10879                                   ? diag::err_init_capture_paren_braces
10880                                   : diag::err_auto_var_init_paren_braces)
10881         << isa<InitListExpr>(Init) << VN << Type << Range;
10882     return QualType();
10883   }
10884
10885   // Expressions default to 'id' when we're in a debugger.
10886   bool DefaultedAnyToId = false;
10887   if (getLangOpts().DebuggerCastResultToId &&
10888       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10889     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10890     if (Result.isInvalid()) {
10891       return QualType();
10892     }
10893     Init = Result.get();
10894     DefaultedAnyToId = true;
10895   }
10896
10897   // C++ [dcl.decomp]p1:
10898   //   If the assignment-expression [...] has array type A and no ref-qualifier
10899   //   is present, e has type cv A
10900   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10901       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10902       DeduceInit->getType()->isConstantArrayType())
10903     return Context.getQualifiedType(DeduceInit->getType(),
10904                                     Type.getQualifiers());
10905
10906   QualType DeducedType;
10907   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10908     if (!IsInitCapture)
10909       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10910     else if (isa<InitListExpr>(Init))
10911       Diag(Range.getBegin(),
10912            diag::err_init_capture_deduction_failure_from_init_list)
10913           << VN
10914           << (DeduceInit->getType().isNull() ? TSI->getType()
10915                                              : DeduceInit->getType())
10916           << DeduceInit->getSourceRange();
10917     else
10918       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10919           << VN << TSI->getType()
10920           << (DeduceInit->getType().isNull() ? TSI->getType()
10921                                              : DeduceInit->getType())
10922           << DeduceInit->getSourceRange();
10923   }
10924
10925   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10926   // 'id' instead of a specific object type prevents most of our usual
10927   // checks.
10928   // We only want to warn outside of template instantiations, though:
10929   // inside a template, the 'id' could have come from a parameter.
10930   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10931       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10932     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10933     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10934   }
10935
10936   return DeducedType;
10937 }
10938
10939 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10940                                          Expr *Init) {
10941   QualType DeducedType = deduceVarTypeFromInitializer(
10942       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10943       VDecl->getSourceRange(), DirectInit, Init);
10944   if (DeducedType.isNull()) {
10945     VDecl->setInvalidDecl();
10946     return true;
10947   }
10948
10949   VDecl->setType(DeducedType);
10950   assert(VDecl->isLinkageValid());
10951
10952   // In ARC, infer lifetime.
10953   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10954     VDecl->setInvalidDecl();
10955
10956   // If this is a redeclaration, check that the type we just deduced matches
10957   // the previously declared type.
10958   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10959     // We never need to merge the type, because we cannot form an incomplete
10960     // array of auto, nor deduce such a type.
10961     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10962   }
10963
10964   // Check the deduced type is valid for a variable declaration.
10965   CheckVariableDeclarationType(VDecl);
10966   return VDecl->isInvalidDecl();
10967 }
10968
10969 /// AddInitializerToDecl - Adds the initializer Init to the
10970 /// declaration dcl. If DirectInit is true, this is C++ direct
10971 /// initialization rather than copy initialization.
10972 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10973   // If there is no declaration, there was an error parsing it.  Just ignore
10974   // the initializer.
10975   if (!RealDecl || RealDecl->isInvalidDecl()) {
10976     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10977     return;
10978   }
10979
10980   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10981     // Pure-specifiers are handled in ActOnPureSpecifier.
10982     Diag(Method->getLocation(), diag::err_member_function_initialization)
10983       << Method->getDeclName() << Init->getSourceRange();
10984     Method->setInvalidDecl();
10985     return;
10986   }
10987
10988   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10989   if (!VDecl) {
10990     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10991     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10992     RealDecl->setInvalidDecl();
10993     return;
10994   }
10995
10996   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10997   if (VDecl->getType()->isUndeducedType()) {
10998     // Attempt typo correction early so that the type of the init expression can
10999     // be deduced based on the chosen correction if the original init contains a
11000     // TypoExpr.
11001     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11002     if (!Res.isUsable()) {
11003       RealDecl->setInvalidDecl();
11004       return;
11005     }
11006     Init = Res.get();
11007
11008     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11009       return;
11010   }
11011
11012   // dllimport cannot be used on variable definitions.
11013   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11014     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11015     VDecl->setInvalidDecl();
11016     return;
11017   }
11018
11019   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11020     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11021     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11022     VDecl->setInvalidDecl();
11023     return;
11024   }
11025
11026   if (!VDecl->getType()->isDependentType()) {
11027     // A definition must end up with a complete type, which means it must be
11028     // complete with the restriction that an array type might be completed by
11029     // the initializer; note that later code assumes this restriction.
11030     QualType BaseDeclType = VDecl->getType();
11031     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11032       BaseDeclType = Array->getElementType();
11033     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11034                             diag::err_typecheck_decl_incomplete_type)) {
11035       RealDecl->setInvalidDecl();
11036       return;
11037     }
11038
11039     // The variable can not have an abstract class type.
11040     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11041                                diag::err_abstract_type_in_decl,
11042                                AbstractVariableType))
11043       VDecl->setInvalidDecl();
11044   }
11045
11046   // If adding the initializer will turn this declaration into a definition,
11047   // and we already have a definition for this variable, diagnose or otherwise
11048   // handle the situation.
11049   VarDecl *Def;
11050   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11051       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11052       !VDecl->isThisDeclarationADemotedDefinition() &&
11053       checkVarDeclRedefinition(Def, VDecl))
11054     return;
11055
11056   if (getLangOpts().CPlusPlus) {
11057     // C++ [class.static.data]p4
11058     //   If a static data member is of const integral or const
11059     //   enumeration type, its declaration in the class definition can
11060     //   specify a constant-initializer which shall be an integral
11061     //   constant expression (5.19). In that case, the member can appear
11062     //   in integral constant expressions. The member shall still be
11063     //   defined in a namespace scope if it is used in the program and the
11064     //   namespace scope definition shall not contain an initializer.
11065     //
11066     // We already performed a redefinition check above, but for static
11067     // data members we also need to check whether there was an in-class
11068     // declaration with an initializer.
11069     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11070       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11071           << VDecl->getDeclName();
11072       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11073            diag::note_previous_initializer)
11074           << 0;
11075       return;
11076     }
11077
11078     if (VDecl->hasLocalStorage())
11079       setFunctionHasBranchProtectedScope();
11080
11081     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11082       VDecl->setInvalidDecl();
11083       return;
11084     }
11085   }
11086
11087   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11088   // a kernel function cannot be initialized."
11089   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11090     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11091     VDecl->setInvalidDecl();
11092     return;
11093   }
11094
11095   // Get the decls type and save a reference for later, since
11096   // CheckInitializerTypes may change it.
11097   QualType DclT = VDecl->getType(), SavT = DclT;
11098
11099   // Expressions default to 'id' when we're in a debugger
11100   // and we are assigning it to a variable of Objective-C pointer type.
11101   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11102       Init->getType() == Context.UnknownAnyTy) {
11103     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11104     if (Result.isInvalid()) {
11105       VDecl->setInvalidDecl();
11106       return;
11107     }
11108     Init = Result.get();
11109   }
11110
11111   // Perform the initialization.
11112   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11113   if (!VDecl->isInvalidDecl()) {
11114     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11115     InitializationKind Kind = InitializationKind::CreateForInit(
11116         VDecl->getLocation(), DirectInit, Init);
11117
11118     MultiExprArg Args = Init;
11119     if (CXXDirectInit)
11120       Args = MultiExprArg(CXXDirectInit->getExprs(),
11121                           CXXDirectInit->getNumExprs());
11122
11123     // Try to correct any TypoExprs in the initialization arguments.
11124     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11125       ExprResult Res = CorrectDelayedTyposInExpr(
11126           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11127             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11128             return Init.Failed() ? ExprError() : E;
11129           });
11130       if (Res.isInvalid()) {
11131         VDecl->setInvalidDecl();
11132       } else if (Res.get() != Args[Idx]) {
11133         Args[Idx] = Res.get();
11134       }
11135     }
11136     if (VDecl->isInvalidDecl())
11137       return;
11138
11139     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11140                                    /*TopLevelOfInitList=*/false,
11141                                    /*TreatUnavailableAsInvalid=*/false);
11142     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11143     if (Result.isInvalid()) {
11144       VDecl->setInvalidDecl();
11145       return;
11146     }
11147
11148     Init = Result.getAs<Expr>();
11149   }
11150
11151   // Check for self-references within variable initializers.
11152   // Variables declared within a function/method body (except for references)
11153   // are handled by a dataflow analysis.
11154   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11155       VDecl->getType()->isReferenceType()) {
11156     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11157   }
11158
11159   // If the type changed, it means we had an incomplete type that was
11160   // completed by the initializer. For example:
11161   //   int ary[] = { 1, 3, 5 };
11162   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11163   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11164     VDecl->setType(DclT);
11165
11166   if (!VDecl->isInvalidDecl()) {
11167     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11168
11169     if (VDecl->hasAttr<BlocksAttr>())
11170       checkRetainCycles(VDecl, Init);
11171
11172     // It is safe to assign a weak reference into a strong variable.
11173     // Although this code can still have problems:
11174     //   id x = self.weakProp;
11175     //   id y = self.weakProp;
11176     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11177     // paths through the function. This should be revisited if
11178     // -Wrepeated-use-of-weak is made flow-sensitive.
11179     if (FunctionScopeInfo *FSI = getCurFunction())
11180       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11181            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11182           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11183                            Init->getLocStart()))
11184         FSI->markSafeWeakUse(Init);
11185   }
11186
11187   // The initialization is usually a full-expression.
11188   //
11189   // FIXME: If this is a braced initialization of an aggregate, it is not
11190   // an expression, and each individual field initializer is a separate
11191   // full-expression. For instance, in:
11192   //
11193   //   struct Temp { ~Temp(); };
11194   //   struct S { S(Temp); };
11195   //   struct T { S a, b; } t = { Temp(), Temp() }
11196   //
11197   // we should destroy the first Temp before constructing the second.
11198   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
11199                                           false,
11200                                           VDecl->isConstexpr());
11201   if (Result.isInvalid()) {
11202     VDecl->setInvalidDecl();
11203     return;
11204   }
11205   Init = Result.get();
11206
11207   // Attach the initializer to the decl.
11208   VDecl->setInit(Init);
11209
11210   if (VDecl->isLocalVarDecl()) {
11211     // Don't check the initializer if the declaration is malformed.
11212     if (VDecl->isInvalidDecl()) {
11213       // do nothing
11214
11215     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11216     // This is true even in OpenCL C++.
11217     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11218       CheckForConstantInitializer(Init, DclT);
11219
11220     // Otherwise, C++ does not restrict the initializer.
11221     } else if (getLangOpts().CPlusPlus) {
11222       // do nothing
11223
11224     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11225     // static storage duration shall be constant expressions or string literals.
11226     } else if (VDecl->getStorageClass() == SC_Static) {
11227       CheckForConstantInitializer(Init, DclT);
11228
11229     // C89 is stricter than C99 for aggregate initializers.
11230     // C89 6.5.7p3: All the expressions [...] in an initializer list
11231     // for an object that has aggregate or union type shall be
11232     // constant expressions.
11233     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11234                isa<InitListExpr>(Init)) {
11235       const Expr *Culprit;
11236       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11237         Diag(Culprit->getExprLoc(),
11238              diag::ext_aggregate_init_not_constant)
11239           << Culprit->getSourceRange();
11240       }
11241     }
11242   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11243              VDecl->getLexicalDeclContext()->isRecord()) {
11244     // This is an in-class initialization for a static data member, e.g.,
11245     //
11246     // struct S {
11247     //   static const int value = 17;
11248     // };
11249
11250     // C++ [class.mem]p4:
11251     //   A member-declarator can contain a constant-initializer only
11252     //   if it declares a static member (9.4) of const integral or
11253     //   const enumeration type, see 9.4.2.
11254     //
11255     // C++11 [class.static.data]p3:
11256     //   If a non-volatile non-inline const static data member is of integral
11257     //   or enumeration type, its declaration in the class definition can
11258     //   specify a brace-or-equal-initializer in which every initializer-clause
11259     //   that is an assignment-expression is a constant expression. A static
11260     //   data member of literal type can be declared in the class definition
11261     //   with the constexpr specifier; if so, its declaration shall specify a
11262     //   brace-or-equal-initializer in which every initializer-clause that is
11263     //   an assignment-expression is a constant expression.
11264
11265     // Do nothing on dependent types.
11266     if (DclT->isDependentType()) {
11267
11268     // Allow any 'static constexpr' members, whether or not they are of literal
11269     // type. We separately check that every constexpr variable is of literal
11270     // type.
11271     } else if (VDecl->isConstexpr()) {
11272
11273     // Require constness.
11274     } else if (!DclT.isConstQualified()) {
11275       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11276         << Init->getSourceRange();
11277       VDecl->setInvalidDecl();
11278
11279     // We allow integer constant expressions in all cases.
11280     } else if (DclT->isIntegralOrEnumerationType()) {
11281       // Check whether the expression is a constant expression.
11282       SourceLocation Loc;
11283       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11284         // In C++11, a non-constexpr const static data member with an
11285         // in-class initializer cannot be volatile.
11286         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11287       else if (Init->isValueDependent())
11288         ; // Nothing to check.
11289       else if (Init->isIntegerConstantExpr(Context, &Loc))
11290         ; // Ok, it's an ICE!
11291       else if (Init->getType()->isScopedEnumeralType() &&
11292                Init->isCXX11ConstantExpr(Context))
11293         ; // Ok, it is a scoped-enum constant expression.
11294       else if (Init->isEvaluatable(Context)) {
11295         // If we can constant fold the initializer through heroics, accept it,
11296         // but report this as a use of an extension for -pedantic.
11297         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11298           << Init->getSourceRange();
11299       } else {
11300         // Otherwise, this is some crazy unknown case.  Report the issue at the
11301         // location provided by the isIntegerConstantExpr failed check.
11302         Diag(Loc, diag::err_in_class_initializer_non_constant)
11303           << Init->getSourceRange();
11304         VDecl->setInvalidDecl();
11305       }
11306
11307     // We allow foldable floating-point constants as an extension.
11308     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11309       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11310       // it anyway and provide a fixit to add the 'constexpr'.
11311       if (getLangOpts().CPlusPlus11) {
11312         Diag(VDecl->getLocation(),
11313              diag::ext_in_class_initializer_float_type_cxx11)
11314             << DclT << Init->getSourceRange();
11315         Diag(VDecl->getLocStart(),
11316              diag::note_in_class_initializer_float_type_cxx11)
11317             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
11318       } else {
11319         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11320           << DclT << Init->getSourceRange();
11321
11322         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11323           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11324             << Init->getSourceRange();
11325           VDecl->setInvalidDecl();
11326         }
11327       }
11328
11329     // Suggest adding 'constexpr' in C++11 for literal types.
11330     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11331       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11332         << DclT << Init->getSourceRange()
11333         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
11334       VDecl->setConstexpr(true);
11335
11336     } else {
11337       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11338         << DclT << Init->getSourceRange();
11339       VDecl->setInvalidDecl();
11340     }
11341   } else if (VDecl->isFileVarDecl()) {
11342     // In C, extern is typically used to avoid tentative definitions when
11343     // declaring variables in headers, but adding an intializer makes it a
11344     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11345     // In C++, extern is often used to give implictly static const variables
11346     // external linkage, so don't warn in that case. If selectany is present,
11347     // this might be header code intended for C and C++ inclusion, so apply the
11348     // C++ rules.
11349     if (VDecl->getStorageClass() == SC_Extern &&
11350         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11351          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11352         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11353         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11354       Diag(VDecl->getLocation(), diag::warn_extern_init);
11355
11356     // C99 6.7.8p4. All file scoped initializers need to be constant.
11357     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11358       CheckForConstantInitializer(Init, DclT);
11359   }
11360
11361   // We will represent direct-initialization similarly to copy-initialization:
11362   //    int x(1);  -as-> int x = 1;
11363   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11364   //
11365   // Clients that want to distinguish between the two forms, can check for
11366   // direct initializer using VarDecl::getInitStyle().
11367   // A major benefit is that clients that don't particularly care about which
11368   // exactly form was it (like the CodeGen) can handle both cases without
11369   // special case code.
11370
11371   // C++ 8.5p11:
11372   // The form of initialization (using parentheses or '=') is generally
11373   // insignificant, but does matter when the entity being initialized has a
11374   // class type.
11375   if (CXXDirectInit) {
11376     assert(DirectInit && "Call-style initializer must be direct init.");
11377     VDecl->setInitStyle(VarDecl::CallInit);
11378   } else if (DirectInit) {
11379     // This must be list-initialization. No other way is direct-initialization.
11380     VDecl->setInitStyle(VarDecl::ListInit);
11381   }
11382
11383   CheckCompleteVariableDeclaration(VDecl);
11384 }
11385
11386 /// ActOnInitializerError - Given that there was an error parsing an
11387 /// initializer for the given declaration, try to return to some form
11388 /// of sanity.
11389 void Sema::ActOnInitializerError(Decl *D) {
11390   // Our main concern here is re-establishing invariants like "a
11391   // variable's type is either dependent or complete".
11392   if (!D || D->isInvalidDecl()) return;
11393
11394   VarDecl *VD = dyn_cast<VarDecl>(D);
11395   if (!VD) return;
11396
11397   // Bindings are not usable if we can't make sense of the initializer.
11398   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11399     for (auto *BD : DD->bindings())
11400       BD->setInvalidDecl();
11401
11402   // Auto types are meaningless if we can't make sense of the initializer.
11403   if (ParsingInitForAutoVars.count(D)) {
11404     D->setInvalidDecl();
11405     return;
11406   }
11407
11408   QualType Ty = VD->getType();
11409   if (Ty->isDependentType()) return;
11410
11411   // Require a complete type.
11412   if (RequireCompleteType(VD->getLocation(),
11413                           Context.getBaseElementType(Ty),
11414                           diag::err_typecheck_decl_incomplete_type)) {
11415     VD->setInvalidDecl();
11416     return;
11417   }
11418
11419   // Require a non-abstract type.
11420   if (RequireNonAbstractType(VD->getLocation(), Ty,
11421                              diag::err_abstract_type_in_decl,
11422                              AbstractVariableType)) {
11423     VD->setInvalidDecl();
11424     return;
11425   }
11426
11427   // Don't bother complaining about constructors or destructors,
11428   // though.
11429 }
11430
11431 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11432   // If there is no declaration, there was an error parsing it. Just ignore it.
11433   if (!RealDecl)
11434     return;
11435
11436   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11437     QualType Type = Var->getType();
11438
11439     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11440     if (isa<DecompositionDecl>(RealDecl)) {
11441       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11442       Var->setInvalidDecl();
11443       return;
11444     }
11445
11446     if (Type->isUndeducedType() &&
11447         DeduceVariableDeclarationType(Var, false, nullptr))
11448       return;
11449
11450     // C++11 [class.static.data]p3: A static data member can be declared with
11451     // the constexpr specifier; if so, its declaration shall specify
11452     // a brace-or-equal-initializer.
11453     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11454     // the definition of a variable [...] or the declaration of a static data
11455     // member.
11456     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11457         !Var->isThisDeclarationADemotedDefinition()) {
11458       if (Var->isStaticDataMember()) {
11459         // C++1z removes the relevant rule; the in-class declaration is always
11460         // a definition there.
11461         if (!getLangOpts().CPlusPlus17) {
11462           Diag(Var->getLocation(),
11463                diag::err_constexpr_static_mem_var_requires_init)
11464             << Var->getDeclName();
11465           Var->setInvalidDecl();
11466           return;
11467         }
11468       } else {
11469         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11470         Var->setInvalidDecl();
11471         return;
11472       }
11473     }
11474
11475     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11476     // be initialized.
11477     if (!Var->isInvalidDecl() &&
11478         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11479         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11480       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11481       Var->setInvalidDecl();
11482       return;
11483     }
11484
11485     switch (Var->isThisDeclarationADefinition()) {
11486     case VarDecl::Definition:
11487       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11488         break;
11489
11490       // We have an out-of-line definition of a static data member
11491       // that has an in-class initializer, so we type-check this like
11492       // a declaration.
11493       //
11494       LLVM_FALLTHROUGH;
11495
11496     case VarDecl::DeclarationOnly:
11497       // It's only a declaration.
11498
11499       // Block scope. C99 6.7p7: If an identifier for an object is
11500       // declared with no linkage (C99 6.2.2p6), the type for the
11501       // object shall be complete.
11502       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11503           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11504           RequireCompleteType(Var->getLocation(), Type,
11505                               diag::err_typecheck_decl_incomplete_type))
11506         Var->setInvalidDecl();
11507
11508       // Make sure that the type is not abstract.
11509       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11510           RequireNonAbstractType(Var->getLocation(), Type,
11511                                  diag::err_abstract_type_in_decl,
11512                                  AbstractVariableType))
11513         Var->setInvalidDecl();
11514       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11515           Var->getStorageClass() == SC_PrivateExtern) {
11516         Diag(Var->getLocation(), diag::warn_private_extern);
11517         Diag(Var->getLocation(), diag::note_private_extern);
11518       }
11519
11520       return;
11521
11522     case VarDecl::TentativeDefinition:
11523       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11524       // object that has file scope without an initializer, and without a
11525       // storage-class specifier or with the storage-class specifier "static",
11526       // constitutes a tentative definition. Note: A tentative definition with
11527       // external linkage is valid (C99 6.2.2p5).
11528       if (!Var->isInvalidDecl()) {
11529         if (const IncompleteArrayType *ArrayT
11530                                     = Context.getAsIncompleteArrayType(Type)) {
11531           if (RequireCompleteType(Var->getLocation(),
11532                                   ArrayT->getElementType(),
11533                                   diag::err_illegal_decl_array_incomplete_type))
11534             Var->setInvalidDecl();
11535         } else if (Var->getStorageClass() == SC_Static) {
11536           // C99 6.9.2p3: If the declaration of an identifier for an object is
11537           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11538           // declared type shall not be an incomplete type.
11539           // NOTE: code such as the following
11540           //     static struct s;
11541           //     struct s { int a; };
11542           // is accepted by gcc. Hence here we issue a warning instead of
11543           // an error and we do not invalidate the static declaration.
11544           // NOTE: to avoid multiple warnings, only check the first declaration.
11545           if (Var->isFirstDecl())
11546             RequireCompleteType(Var->getLocation(), Type,
11547                                 diag::ext_typecheck_decl_incomplete_type);
11548         }
11549       }
11550
11551       // Record the tentative definition; we're done.
11552       if (!Var->isInvalidDecl())
11553         TentativeDefinitions.push_back(Var);
11554       return;
11555     }
11556
11557     // Provide a specific diagnostic for uninitialized variable
11558     // definitions with incomplete array type.
11559     if (Type->isIncompleteArrayType()) {
11560       Diag(Var->getLocation(),
11561            diag::err_typecheck_incomplete_array_needs_initializer);
11562       Var->setInvalidDecl();
11563       return;
11564     }
11565
11566     // Provide a specific diagnostic for uninitialized variable
11567     // definitions with reference type.
11568     if (Type->isReferenceType()) {
11569       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11570         << Var->getDeclName()
11571         << SourceRange(Var->getLocation(), Var->getLocation());
11572       Var->setInvalidDecl();
11573       return;
11574     }
11575
11576     // Do not attempt to type-check the default initializer for a
11577     // variable with dependent type.
11578     if (Type->isDependentType())
11579       return;
11580
11581     if (Var->isInvalidDecl())
11582       return;
11583
11584     if (!Var->hasAttr<AliasAttr>()) {
11585       if (RequireCompleteType(Var->getLocation(),
11586                               Context.getBaseElementType(Type),
11587                               diag::err_typecheck_decl_incomplete_type)) {
11588         Var->setInvalidDecl();
11589         return;
11590       }
11591     } else {
11592       return;
11593     }
11594
11595     // The variable can not have an abstract class type.
11596     if (RequireNonAbstractType(Var->getLocation(), Type,
11597                                diag::err_abstract_type_in_decl,
11598                                AbstractVariableType)) {
11599       Var->setInvalidDecl();
11600       return;
11601     }
11602
11603     // Check for jumps past the implicit initializer.  C++0x
11604     // clarifies that this applies to a "variable with automatic
11605     // storage duration", not a "local variable".
11606     // C++11 [stmt.dcl]p3
11607     //   A program that jumps from a point where a variable with automatic
11608     //   storage duration is not in scope to a point where it is in scope is
11609     //   ill-formed unless the variable has scalar type, class type with a
11610     //   trivial default constructor and a trivial destructor, a cv-qualified
11611     //   version of one of these types, or an array of one of the preceding
11612     //   types and is declared without an initializer.
11613     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11614       if (const RecordType *Record
11615             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11616         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11617         // Mark the function (if we're in one) for further checking even if the
11618         // looser rules of C++11 do not require such checks, so that we can
11619         // diagnose incompatibilities with C++98.
11620         if (!CXXRecord->isPOD())
11621           setFunctionHasBranchProtectedScope();
11622       }
11623     }
11624
11625     // C++03 [dcl.init]p9:
11626     //   If no initializer is specified for an object, and the
11627     //   object is of (possibly cv-qualified) non-POD class type (or
11628     //   array thereof), the object shall be default-initialized; if
11629     //   the object is of const-qualified type, the underlying class
11630     //   type shall have a user-declared default
11631     //   constructor. Otherwise, if no initializer is specified for
11632     //   a non- static object, the object and its subobjects, if
11633     //   any, have an indeterminate initial value); if the object
11634     //   or any of its subobjects are of const-qualified type, the
11635     //   program is ill-formed.
11636     // C++0x [dcl.init]p11:
11637     //   If no initializer is specified for an object, the object is
11638     //   default-initialized; [...].
11639     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11640     InitializationKind Kind
11641       = InitializationKind::CreateDefault(Var->getLocation());
11642
11643     InitializationSequence InitSeq(*this, Entity, Kind, None);
11644     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11645     if (Init.isInvalid())
11646       Var->setInvalidDecl();
11647     else if (Init.get()) {
11648       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11649       // This is important for template substitution.
11650       Var->setInitStyle(VarDecl::CallInit);
11651     }
11652
11653     CheckCompleteVariableDeclaration(Var);
11654   }
11655 }
11656
11657 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11658   // If there is no declaration, there was an error parsing it. Ignore it.
11659   if (!D)
11660     return;
11661
11662   VarDecl *VD = dyn_cast<VarDecl>(D);
11663   if (!VD) {
11664     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11665     D->setInvalidDecl();
11666     return;
11667   }
11668
11669   VD->setCXXForRangeDecl(true);
11670
11671   // for-range-declaration cannot be given a storage class specifier.
11672   int Error = -1;
11673   switch (VD->getStorageClass()) {
11674   case SC_None:
11675     break;
11676   case SC_Extern:
11677     Error = 0;
11678     break;
11679   case SC_Static:
11680     Error = 1;
11681     break;
11682   case SC_PrivateExtern:
11683     Error = 2;
11684     break;
11685   case SC_Auto:
11686     Error = 3;
11687     break;
11688   case SC_Register:
11689     Error = 4;
11690     break;
11691   }
11692   if (Error != -1) {
11693     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11694       << VD->getDeclName() << Error;
11695     D->setInvalidDecl();
11696   }
11697 }
11698
11699 StmtResult
11700 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11701                                  IdentifierInfo *Ident,
11702                                  ParsedAttributes &Attrs,
11703                                  SourceLocation AttrEnd) {
11704   // C++1y [stmt.iter]p1:
11705   //   A range-based for statement of the form
11706   //      for ( for-range-identifier : for-range-initializer ) statement
11707   //   is equivalent to
11708   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11709   DeclSpec DS(Attrs.getPool().getFactory());
11710
11711   const char *PrevSpec;
11712   unsigned DiagID;
11713   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11714                      getPrintingPolicy());
11715
11716   Declarator D(DS, DeclaratorContext::ForContext);
11717   D.SetIdentifier(Ident, IdentLoc);
11718   D.takeAttributes(Attrs, AttrEnd);
11719
11720   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11721   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11722                 IdentLoc);
11723   Decl *Var = ActOnDeclarator(S, D);
11724   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11725   FinalizeDeclaration(Var);
11726   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11727                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11728 }
11729
11730 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11731   if (var->isInvalidDecl()) return;
11732
11733   if (getLangOpts().OpenCL) {
11734     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11735     // initialiser
11736     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11737         !var->hasInit()) {
11738       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11739           << 1 /*Init*/;
11740       var->setInvalidDecl();
11741       return;
11742     }
11743   }
11744
11745   // In Objective-C, don't allow jumps past the implicit initialization of a
11746   // local retaining variable.
11747   if (getLangOpts().ObjC1 &&
11748       var->hasLocalStorage()) {
11749     switch (var->getType().getObjCLifetime()) {
11750     case Qualifiers::OCL_None:
11751     case Qualifiers::OCL_ExplicitNone:
11752     case Qualifiers::OCL_Autoreleasing:
11753       break;
11754
11755     case Qualifiers::OCL_Weak:
11756     case Qualifiers::OCL_Strong:
11757       setFunctionHasBranchProtectedScope();
11758       break;
11759     }
11760   }
11761
11762   if (var->hasLocalStorage() &&
11763       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11764     setFunctionHasBranchProtectedScope();
11765
11766   // Warn about externally-visible variables being defined without a
11767   // prior declaration.  We only want to do this for global
11768   // declarations, but we also specifically need to avoid doing it for
11769   // class members because the linkage of an anonymous class can
11770   // change if it's later given a typedef name.
11771   if (var->isThisDeclarationADefinition() &&
11772       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11773       var->isExternallyVisible() && var->hasLinkage() &&
11774       !var->isInline() && !var->getDescribedVarTemplate() &&
11775       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11776       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11777                                   var->getLocation())) {
11778     // Find a previous declaration that's not a definition.
11779     VarDecl *prev = var->getPreviousDecl();
11780     while (prev && prev->isThisDeclarationADefinition())
11781       prev = prev->getPreviousDecl();
11782
11783     if (!prev)
11784       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11785   }
11786
11787   // Cache the result of checking for constant initialization.
11788   Optional<bool> CacheHasConstInit;
11789   const Expr *CacheCulprit;
11790   auto checkConstInit = [&]() mutable {
11791     if (!CacheHasConstInit)
11792       CacheHasConstInit = var->getInit()->isConstantInitializer(
11793             Context, var->getType()->isReferenceType(), &CacheCulprit);
11794     return *CacheHasConstInit;
11795   };
11796
11797   if (var->getTLSKind() == VarDecl::TLS_Static) {
11798     if (var->getType().isDestructedType()) {
11799       // GNU C++98 edits for __thread, [basic.start.term]p3:
11800       //   The type of an object with thread storage duration shall not
11801       //   have a non-trivial destructor.
11802       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11803       if (getLangOpts().CPlusPlus11)
11804         Diag(var->getLocation(), diag::note_use_thread_local);
11805     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11806       if (!checkConstInit()) {
11807         // GNU C++98 edits for __thread, [basic.start.init]p4:
11808         //   An object of thread storage duration shall not require dynamic
11809         //   initialization.
11810         // FIXME: Need strict checking here.
11811         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11812           << CacheCulprit->getSourceRange();
11813         if (getLangOpts().CPlusPlus11)
11814           Diag(var->getLocation(), diag::note_use_thread_local);
11815       }
11816     }
11817   }
11818
11819   // Apply section attributes and pragmas to global variables.
11820   bool GlobalStorage = var->hasGlobalStorage();
11821   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11822       !inTemplateInstantiation()) {
11823     PragmaStack<StringLiteral *> *Stack = nullptr;
11824     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11825     if (var->getType().isConstQualified())
11826       Stack = &ConstSegStack;
11827     else if (!var->getInit()) {
11828       Stack = &BSSSegStack;
11829       SectionFlags |= ASTContext::PSF_Write;
11830     } else {
11831       Stack = &DataSegStack;
11832       SectionFlags |= ASTContext::PSF_Write;
11833     }
11834     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11835       var->addAttr(SectionAttr::CreateImplicit(
11836           Context, SectionAttr::Declspec_allocate,
11837           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11838     }
11839     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11840       if (UnifySection(SA->getName(), SectionFlags, var))
11841         var->dropAttr<SectionAttr>();
11842
11843     // Apply the init_seg attribute if this has an initializer.  If the
11844     // initializer turns out to not be dynamic, we'll end up ignoring this
11845     // attribute.
11846     if (CurInitSeg && var->getInit())
11847       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11848                                                CurInitSegLoc));
11849   }
11850
11851   // All the following checks are C++ only.
11852   if (!getLangOpts().CPlusPlus) {
11853       // If this variable must be emitted, add it as an initializer for the
11854       // current module.
11855      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11856        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11857      return;
11858   }
11859
11860   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11861     CheckCompleteDecompositionDeclaration(DD);
11862
11863   QualType type = var->getType();
11864   if (type->isDependentType()) return;
11865
11866   // __block variables might require us to capture a copy-initializer.
11867   if (var->hasAttr<BlocksAttr>()) {
11868     // It's currently invalid to ever have a __block variable with an
11869     // array type; should we diagnose that here?
11870
11871     // Regardless, we don't want to ignore array nesting when
11872     // constructing this copy.
11873     if (type->isStructureOrClassType()) {
11874       EnterExpressionEvaluationContext scope(
11875           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11876       SourceLocation poi = var->getLocation();
11877       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11878       ExprResult result
11879         = PerformMoveOrCopyInitialization(
11880             InitializedEntity::InitializeBlock(poi, type, false),
11881             var, var->getType(), varRef, /*AllowNRVO=*/true);
11882       if (!result.isInvalid()) {
11883         result = MaybeCreateExprWithCleanups(result);
11884         Expr *init = result.getAs<Expr>();
11885         Context.setBlockVarCopyInits(var, init);
11886       }
11887     }
11888   }
11889
11890   Expr *Init = var->getInit();
11891   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11892   QualType baseType = Context.getBaseElementType(type);
11893
11894   if (Init && !Init->isValueDependent()) {
11895     if (var->isConstexpr()) {
11896       SmallVector<PartialDiagnosticAt, 8> Notes;
11897       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11898         SourceLocation DiagLoc = var->getLocation();
11899         // If the note doesn't add any useful information other than a source
11900         // location, fold it into the primary diagnostic.
11901         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11902               diag::note_invalid_subexpr_in_const_expr) {
11903           DiagLoc = Notes[0].first;
11904           Notes.clear();
11905         }
11906         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11907           << var << Init->getSourceRange();
11908         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11909           Diag(Notes[I].first, Notes[I].second);
11910       }
11911     } else if (var->isUsableInConstantExpressions(Context)) {
11912       // Check whether the initializer of a const variable of integral or
11913       // enumeration type is an ICE now, since we can't tell whether it was
11914       // initialized by a constant expression if we check later.
11915       var->checkInitIsICE();
11916     }
11917
11918     // Don't emit further diagnostics about constexpr globals since they
11919     // were just diagnosed.
11920     if (!var->isConstexpr() && GlobalStorage &&
11921             var->hasAttr<RequireConstantInitAttr>()) {
11922       // FIXME: Need strict checking in C++03 here.
11923       bool DiagErr = getLangOpts().CPlusPlus11
11924           ? !var->checkInitIsICE() : !checkConstInit();
11925       if (DiagErr) {
11926         auto attr = var->getAttr<RequireConstantInitAttr>();
11927         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11928           << Init->getSourceRange();
11929         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11930           << attr->getRange();
11931         if (getLangOpts().CPlusPlus11) {
11932           APValue Value;
11933           SmallVector<PartialDiagnosticAt, 8> Notes;
11934           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11935           for (auto &it : Notes)
11936             Diag(it.first, it.second);
11937         } else {
11938           Diag(CacheCulprit->getExprLoc(),
11939                diag::note_invalid_subexpr_in_const_expr)
11940               << CacheCulprit->getSourceRange();
11941         }
11942       }
11943     }
11944     else if (!var->isConstexpr() && IsGlobal &&
11945              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11946                                     var->getLocation())) {
11947       // Warn about globals which don't have a constant initializer.  Don't
11948       // warn about globals with a non-trivial destructor because we already
11949       // warned about them.
11950       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11951       if (!(RD && !RD->hasTrivialDestructor())) {
11952         if (!checkConstInit())
11953           Diag(var->getLocation(), diag::warn_global_constructor)
11954             << Init->getSourceRange();
11955       }
11956     }
11957   }
11958
11959   // Require the destructor.
11960   if (const RecordType *recordType = baseType->getAs<RecordType>())
11961     FinalizeVarWithDestructor(var, recordType);
11962
11963   // If this variable must be emitted, add it as an initializer for the current
11964   // module.
11965   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11966     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11967 }
11968
11969 /// Determines if a variable's alignment is dependent.
11970 static bool hasDependentAlignment(VarDecl *VD) {
11971   if (VD->getType()->isDependentType())
11972     return true;
11973   for (auto *I : VD->specific_attrs<AlignedAttr>())
11974     if (I->isAlignmentDependent())
11975       return true;
11976   return false;
11977 }
11978
11979 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11980 /// any semantic actions necessary after any initializer has been attached.
11981 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11982   // Note that we are no longer parsing the initializer for this declaration.
11983   ParsingInitForAutoVars.erase(ThisDecl);
11984
11985   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11986   if (!VD)
11987     return;
11988
11989   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11990   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11991       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11992     if (PragmaClangBSSSection.Valid)
11993       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11994                                                             PragmaClangBSSSection.SectionName,
11995                                                             PragmaClangBSSSection.PragmaLocation));
11996     if (PragmaClangDataSection.Valid)
11997       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11998                                                              PragmaClangDataSection.SectionName,
11999                                                              PragmaClangDataSection.PragmaLocation));
12000     if (PragmaClangRodataSection.Valid)
12001       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12002                                                                PragmaClangRodataSection.SectionName,
12003                                                                PragmaClangRodataSection.PragmaLocation));
12004   }
12005
12006   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12007     for (auto *BD : DD->bindings()) {
12008       FinalizeDeclaration(BD);
12009     }
12010   }
12011
12012   checkAttributesAfterMerging(*this, *VD);
12013
12014   // Perform TLS alignment check here after attributes attached to the variable
12015   // which may affect the alignment have been processed. Only perform the check
12016   // if the target has a maximum TLS alignment (zero means no constraints).
12017   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12018     // Protect the check so that it's not performed on dependent types and
12019     // dependent alignments (we can't determine the alignment in that case).
12020     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12021         !VD->isInvalidDecl()) {
12022       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12023       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12024         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12025           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12026           << (unsigned)MaxAlignChars.getQuantity();
12027       }
12028     }
12029   }
12030
12031   if (VD->isStaticLocal()) {
12032     if (FunctionDecl *FD =
12033             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12034       // Static locals inherit dll attributes from their function.
12035       if (Attr *A = getDLLAttr(FD)) {
12036         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12037         NewAttr->setInherited(true);
12038         VD->addAttr(NewAttr);
12039       }
12040       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12041       // function, only __shared__ variables or variables without any device
12042       // memory qualifiers may be declared with static storage class.
12043       // Note: It is unclear how a function-scope non-const static variable
12044       // without device memory qualifier is implemented, therefore only static
12045       // const variable without device memory qualifier is allowed.
12046       [&]() {
12047         if (!getLangOpts().CUDA)
12048           return;
12049         if (VD->hasAttr<CUDASharedAttr>())
12050           return;
12051         if (VD->getType().isConstQualified() &&
12052             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12053           return;
12054         if (CUDADiagIfDeviceCode(VD->getLocation(),
12055                                  diag::err_device_static_local_var)
12056             << CurrentCUDATarget())
12057           VD->setInvalidDecl();
12058       }();
12059     }
12060   }
12061
12062   // Perform check for initializers of device-side global variables.
12063   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12064   // 7.5). We must also apply the same checks to all __shared__
12065   // variables whether they are local or not. CUDA also allows
12066   // constant initializers for __constant__ and __device__ variables.
12067   if (getLangOpts().CUDA)
12068     checkAllowedCUDAInitializer(VD);
12069
12070   // Grab the dllimport or dllexport attribute off of the VarDecl.
12071   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12072
12073   // Imported static data members cannot be defined out-of-line.
12074   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12075     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12076         VD->isThisDeclarationADefinition()) {
12077       // We allow definitions of dllimport class template static data members
12078       // with a warning.
12079       CXXRecordDecl *Context =
12080         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12081       bool IsClassTemplateMember =
12082           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12083           Context->getDescribedClassTemplate();
12084
12085       Diag(VD->getLocation(),
12086            IsClassTemplateMember
12087                ? diag::warn_attribute_dllimport_static_field_definition
12088                : diag::err_attribute_dllimport_static_field_definition);
12089       Diag(IA->getLocation(), diag::note_attribute);
12090       if (!IsClassTemplateMember)
12091         VD->setInvalidDecl();
12092     }
12093   }
12094
12095   // dllimport/dllexport variables cannot be thread local, their TLS index
12096   // isn't exported with the variable.
12097   if (DLLAttr && VD->getTLSKind()) {
12098     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12099     if (F && getDLLAttr(F)) {
12100       assert(VD->isStaticLocal());
12101       // But if this is a static local in a dlimport/dllexport function, the
12102       // function will never be inlined, which means the var would never be
12103       // imported, so having it marked import/export is safe.
12104     } else {
12105       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12106                                                                     << DLLAttr;
12107       VD->setInvalidDecl();
12108     }
12109   }
12110
12111   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12112     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12113       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12114       VD->dropAttr<UsedAttr>();
12115     }
12116   }
12117
12118   const DeclContext *DC = VD->getDeclContext();
12119   // If there's a #pragma GCC visibility in scope, and this isn't a class
12120   // member, set the visibility of this variable.
12121   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12122     AddPushedVisibilityAttribute(VD);
12123
12124   // FIXME: Warn on unused var template partial specializations.
12125   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12126     MarkUnusedFileScopedDecl(VD);
12127
12128   // Now we have parsed the initializer and can update the table of magic
12129   // tag values.
12130   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12131       !VD->getType()->isIntegralOrEnumerationType())
12132     return;
12133
12134   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12135     const Expr *MagicValueExpr = VD->getInit();
12136     if (!MagicValueExpr) {
12137       continue;
12138     }
12139     llvm::APSInt MagicValueInt;
12140     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12141       Diag(I->getRange().getBegin(),
12142            diag::err_type_tag_for_datatype_not_ice)
12143         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12144       continue;
12145     }
12146     if (MagicValueInt.getActiveBits() > 64) {
12147       Diag(I->getRange().getBegin(),
12148            diag::err_type_tag_for_datatype_too_large)
12149         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12150       continue;
12151     }
12152     uint64_t MagicValue = MagicValueInt.getZExtValue();
12153     RegisterTypeTagForDatatype(I->getArgumentKind(),
12154                                MagicValue,
12155                                I->getMatchingCType(),
12156                                I->getLayoutCompatible(),
12157                                I->getMustBeNull());
12158   }
12159 }
12160
12161 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12162   auto *VD = dyn_cast<VarDecl>(DD);
12163   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12164 }
12165
12166 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12167                                                    ArrayRef<Decl *> Group) {
12168   SmallVector<Decl*, 8> Decls;
12169
12170   if (DS.isTypeSpecOwned())
12171     Decls.push_back(DS.getRepAsDecl());
12172
12173   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12174   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12175   bool DiagnosedMultipleDecomps = false;
12176   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12177   bool DiagnosedNonDeducedAuto = false;
12178
12179   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12180     if (Decl *D = Group[i]) {
12181       // For declarators, there are some additional syntactic-ish checks we need
12182       // to perform.
12183       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12184         if (!FirstDeclaratorInGroup)
12185           FirstDeclaratorInGroup = DD;
12186         if (!FirstDecompDeclaratorInGroup)
12187           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12188         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12189             !hasDeducedAuto(DD))
12190           FirstNonDeducedAutoInGroup = DD;
12191
12192         if (FirstDeclaratorInGroup != DD) {
12193           // A decomposition declaration cannot be combined with any other
12194           // declaration in the same group.
12195           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12196             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12197                  diag::err_decomp_decl_not_alone)
12198                 << FirstDeclaratorInGroup->getSourceRange()
12199                 << DD->getSourceRange();
12200             DiagnosedMultipleDecomps = true;
12201           }
12202
12203           // A declarator that uses 'auto' in any way other than to declare a
12204           // variable with a deduced type cannot be combined with any other
12205           // declarator in the same group.
12206           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12207             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12208                  diag::err_auto_non_deduced_not_alone)
12209                 << FirstNonDeducedAutoInGroup->getType()
12210                        ->hasAutoForTrailingReturnType()
12211                 << FirstDeclaratorInGroup->getSourceRange()
12212                 << DD->getSourceRange();
12213             DiagnosedNonDeducedAuto = true;
12214           }
12215         }
12216       }
12217
12218       Decls.push_back(D);
12219     }
12220   }
12221
12222   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12223     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12224       handleTagNumbering(Tag, S);
12225       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12226           getLangOpts().CPlusPlus)
12227         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12228     }
12229   }
12230
12231   return BuildDeclaratorGroup(Decls);
12232 }
12233
12234 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12235 /// group, performing any necessary semantic checking.
12236 Sema::DeclGroupPtrTy
12237 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12238   // C++14 [dcl.spec.auto]p7: (DR1347)
12239   //   If the type that replaces the placeholder type is not the same in each
12240   //   deduction, the program is ill-formed.
12241   if (Group.size() > 1) {
12242     QualType Deduced;
12243     VarDecl *DeducedDecl = nullptr;
12244     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12245       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12246       if (!D || D->isInvalidDecl())
12247         break;
12248       DeducedType *DT = D->getType()->getContainedDeducedType();
12249       if (!DT || DT->getDeducedType().isNull())
12250         continue;
12251       if (Deduced.isNull()) {
12252         Deduced = DT->getDeducedType();
12253         DeducedDecl = D;
12254       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12255         auto *AT = dyn_cast<AutoType>(DT);
12256         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12257              diag::err_auto_different_deductions)
12258           << (AT ? (unsigned)AT->getKeyword() : 3)
12259           << Deduced << DeducedDecl->getDeclName()
12260           << DT->getDeducedType() << D->getDeclName()
12261           << DeducedDecl->getInit()->getSourceRange()
12262           << D->getInit()->getSourceRange();
12263         D->setInvalidDecl();
12264         break;
12265       }
12266     }
12267   }
12268
12269   ActOnDocumentableDecls(Group);
12270
12271   return DeclGroupPtrTy::make(
12272       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12273 }
12274
12275 void Sema::ActOnDocumentableDecl(Decl *D) {
12276   ActOnDocumentableDecls(D);
12277 }
12278
12279 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12280   // Don't parse the comment if Doxygen diagnostics are ignored.
12281   if (Group.empty() || !Group[0])
12282     return;
12283
12284   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12285                       Group[0]->getLocation()) &&
12286       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12287                       Group[0]->getLocation()))
12288     return;
12289
12290   if (Group.size() >= 2) {
12291     // This is a decl group.  Normally it will contain only declarations
12292     // produced from declarator list.  But in case we have any definitions or
12293     // additional declaration references:
12294     //   'typedef struct S {} S;'
12295     //   'typedef struct S *S;'
12296     //   'struct S *pS;'
12297     // FinalizeDeclaratorGroup adds these as separate declarations.
12298     Decl *MaybeTagDecl = Group[0];
12299     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12300       Group = Group.slice(1);
12301     }
12302   }
12303
12304   // See if there are any new comments that are not attached to a decl.
12305   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12306   if (!Comments.empty() &&
12307       !Comments.back()->isAttached()) {
12308     // There is at least one comment that not attached to a decl.
12309     // Maybe it should be attached to one of these decls?
12310     //
12311     // Note that this way we pick up not only comments that precede the
12312     // declaration, but also comments that *follow* the declaration -- thanks to
12313     // the lookahead in the lexer: we've consumed the semicolon and looked
12314     // ahead through comments.
12315     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12316       Context.getCommentForDecl(Group[i], &PP);
12317   }
12318 }
12319
12320 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12321 /// to introduce parameters into function prototype scope.
12322 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12323   const DeclSpec &DS = D.getDeclSpec();
12324
12325   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12326
12327   // C++03 [dcl.stc]p2 also permits 'auto'.
12328   StorageClass SC = SC_None;
12329   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12330     SC = SC_Register;
12331     // In C++11, the 'register' storage class specifier is deprecated.
12332     // In C++17, it is not allowed, but we tolerate it as an extension.
12333     if (getLangOpts().CPlusPlus11) {
12334       Diag(DS.getStorageClassSpecLoc(),
12335            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12336                                      : diag::warn_deprecated_register)
12337         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12338     }
12339   } else if (getLangOpts().CPlusPlus &&
12340              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12341     SC = SC_Auto;
12342   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12343     Diag(DS.getStorageClassSpecLoc(),
12344          diag::err_invalid_storage_class_in_func_decl);
12345     D.getMutableDeclSpec().ClearStorageClassSpecs();
12346   }
12347
12348   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12349     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12350       << DeclSpec::getSpecifierName(TSCS);
12351   if (DS.isInlineSpecified())
12352     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12353         << getLangOpts().CPlusPlus17;
12354   if (DS.isConstexprSpecified())
12355     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12356       << 0;
12357
12358   DiagnoseFunctionSpecifiers(DS);
12359
12360   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12361   QualType parmDeclType = TInfo->getType();
12362
12363   if (getLangOpts().CPlusPlus) {
12364     // Check that there are no default arguments inside the type of this
12365     // parameter.
12366     CheckExtraCXXDefaultArguments(D);
12367
12368     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12369     if (D.getCXXScopeSpec().isSet()) {
12370       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12371         << D.getCXXScopeSpec().getRange();
12372       D.getCXXScopeSpec().clear();
12373     }
12374   }
12375
12376   // Ensure we have a valid name
12377   IdentifierInfo *II = nullptr;
12378   if (D.hasName()) {
12379     II = D.getIdentifier();
12380     if (!II) {
12381       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12382         << GetNameForDeclarator(D).getName();
12383       D.setInvalidType(true);
12384     }
12385   }
12386
12387   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12388   if (II) {
12389     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12390                    ForVisibleRedeclaration);
12391     LookupName(R, S);
12392     if (R.isSingleResult()) {
12393       NamedDecl *PrevDecl = R.getFoundDecl();
12394       if (PrevDecl->isTemplateParameter()) {
12395         // Maybe we will complain about the shadowed template parameter.
12396         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12397         // Just pretend that we didn't see the previous declaration.
12398         PrevDecl = nullptr;
12399       } else if (S->isDeclScope(PrevDecl)) {
12400         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12401         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12402
12403         // Recover by removing the name
12404         II = nullptr;
12405         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12406         D.setInvalidType(true);
12407       }
12408     }
12409   }
12410
12411   // Temporarily put parameter variables in the translation unit, not
12412   // the enclosing context.  This prevents them from accidentally
12413   // looking like class members in C++.
12414   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12415                                     D.getLocStart(),
12416                                     D.getIdentifierLoc(), II,
12417                                     parmDeclType, TInfo,
12418                                     SC);
12419
12420   if (D.isInvalidType())
12421     New->setInvalidDecl();
12422
12423   assert(S->isFunctionPrototypeScope());
12424   assert(S->getFunctionPrototypeDepth() >= 1);
12425   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12426                     S->getNextFunctionPrototypeIndex());
12427
12428   // Add the parameter declaration into this scope.
12429   S->AddDecl(New);
12430   if (II)
12431     IdResolver.AddDecl(New);
12432
12433   ProcessDeclAttributes(S, New, D);
12434
12435   if (D.getDeclSpec().isModulePrivateSpecified())
12436     Diag(New->getLocation(), diag::err_module_private_local)
12437       << 1 << New->getDeclName()
12438       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12439       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12440
12441   if (New->hasAttr<BlocksAttr>()) {
12442     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12443   }
12444   return New;
12445 }
12446
12447 /// Synthesizes a variable for a parameter arising from a
12448 /// typedef.
12449 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12450                                               SourceLocation Loc,
12451                                               QualType T) {
12452   /* FIXME: setting StartLoc == Loc.
12453      Would it be worth to modify callers so as to provide proper source
12454      location for the unnamed parameters, embedding the parameter's type? */
12455   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12456                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12457                                            SC_None, nullptr);
12458   Param->setImplicit();
12459   return Param;
12460 }
12461
12462 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12463   // Don't diagnose unused-parameter errors in template instantiations; we
12464   // will already have done so in the template itself.
12465   if (inTemplateInstantiation())
12466     return;
12467
12468   for (const ParmVarDecl *Parameter : Parameters) {
12469     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12470         !Parameter->hasAttr<UnusedAttr>()) {
12471       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12472         << Parameter->getDeclName();
12473     }
12474   }
12475 }
12476
12477 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12478     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12479   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12480     return;
12481
12482   // Warn if the return value is pass-by-value and larger than the specified
12483   // threshold.
12484   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12485     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12486     if (Size > LangOpts.NumLargeByValueCopy)
12487       Diag(D->getLocation(), diag::warn_return_value_size)
12488           << D->getDeclName() << Size;
12489   }
12490
12491   // Warn if any parameter is pass-by-value and larger than the specified
12492   // threshold.
12493   for (const ParmVarDecl *Parameter : Parameters) {
12494     QualType T = Parameter->getType();
12495     if (T->isDependentType() || !T.isPODType(Context))
12496       continue;
12497     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12498     if (Size > LangOpts.NumLargeByValueCopy)
12499       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12500           << Parameter->getDeclName() << Size;
12501   }
12502 }
12503
12504 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12505                                   SourceLocation NameLoc, IdentifierInfo *Name,
12506                                   QualType T, TypeSourceInfo *TSInfo,
12507                                   StorageClass SC) {
12508   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12509   if (getLangOpts().ObjCAutoRefCount &&
12510       T.getObjCLifetime() == Qualifiers::OCL_None &&
12511       T->isObjCLifetimeType()) {
12512
12513     Qualifiers::ObjCLifetime lifetime;
12514
12515     // Special cases for arrays:
12516     //   - if it's const, use __unsafe_unretained
12517     //   - otherwise, it's an error
12518     if (T->isArrayType()) {
12519       if (!T.isConstQualified()) {
12520         DelayedDiagnostics.add(
12521             sema::DelayedDiagnostic::makeForbiddenType(
12522             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12523       }
12524       lifetime = Qualifiers::OCL_ExplicitNone;
12525     } else {
12526       lifetime = T->getObjCARCImplicitLifetime();
12527     }
12528     T = Context.getLifetimeQualifiedType(T, lifetime);
12529   }
12530
12531   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12532                                          Context.getAdjustedParameterType(T),
12533                                          TSInfo, SC, nullptr);
12534
12535   // Parameters can not be abstract class types.
12536   // For record types, this is done by the AbstractClassUsageDiagnoser once
12537   // the class has been completely parsed.
12538   if (!CurContext->isRecord() &&
12539       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12540                              AbstractParamType))
12541     New->setInvalidDecl();
12542
12543   // Parameter declarators cannot be interface types. All ObjC objects are
12544   // passed by reference.
12545   if (T->isObjCObjectType()) {
12546     SourceLocation TypeEndLoc =
12547         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12548     Diag(NameLoc,
12549          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12550       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12551     T = Context.getObjCObjectPointerType(T);
12552     New->setType(T);
12553   }
12554
12555   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12556   // duration shall not be qualified by an address-space qualifier."
12557   // Since all parameters have automatic store duration, they can not have
12558   // an address space.
12559   if (T.getAddressSpace() != LangAS::Default &&
12560       // OpenCL allows function arguments declared to be an array of a type
12561       // to be qualified with an address space.
12562       !(getLangOpts().OpenCL &&
12563         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12564     Diag(NameLoc, diag::err_arg_with_address_space);
12565     New->setInvalidDecl();
12566   }
12567
12568   return New;
12569 }
12570
12571 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12572                                            SourceLocation LocAfterDecls) {
12573   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12574
12575   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12576   // for a K&R function.
12577   if (!FTI.hasPrototype) {
12578     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12579       --i;
12580       if (FTI.Params[i].Param == nullptr) {
12581         SmallString<256> Code;
12582         llvm::raw_svector_ostream(Code)
12583             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12584         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12585             << FTI.Params[i].Ident
12586             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12587
12588         // Implicitly declare the argument as type 'int' for lack of a better
12589         // type.
12590         AttributeFactory attrs;
12591         DeclSpec DS(attrs);
12592         const char* PrevSpec; // unused
12593         unsigned DiagID; // unused
12594         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12595                            DiagID, Context.getPrintingPolicy());
12596         // Use the identifier location for the type source range.
12597         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12598         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12599         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12600         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12601         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12602       }
12603     }
12604   }
12605 }
12606
12607 Decl *
12608 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12609                               MultiTemplateParamsArg TemplateParameterLists,
12610                               SkipBodyInfo *SkipBody) {
12611   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12612   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12613   Scope *ParentScope = FnBodyScope->getParent();
12614
12615   D.setFunctionDefinitionKind(FDK_Definition);
12616   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12617   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12618 }
12619
12620 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12621   Consumer.HandleInlineFunctionDefinition(D);
12622 }
12623
12624 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12625                              const FunctionDecl*& PossibleZeroParamPrototype) {
12626   // Don't warn about invalid declarations.
12627   if (FD->isInvalidDecl())
12628     return false;
12629
12630   // Or declarations that aren't global.
12631   if (!FD->isGlobal())
12632     return false;
12633
12634   // Don't warn about C++ member functions.
12635   if (isa<CXXMethodDecl>(FD))
12636     return false;
12637
12638   // Don't warn about 'main'.
12639   if (FD->isMain())
12640     return false;
12641
12642   // Don't warn about inline functions.
12643   if (FD->isInlined())
12644     return false;
12645
12646   // Don't warn about function templates.
12647   if (FD->getDescribedFunctionTemplate())
12648     return false;
12649
12650   // Don't warn about function template specializations.
12651   if (FD->isFunctionTemplateSpecialization())
12652     return false;
12653
12654   // Don't warn for OpenCL kernels.
12655   if (FD->hasAttr<OpenCLKernelAttr>())
12656     return false;
12657
12658   // Don't warn on explicitly deleted functions.
12659   if (FD->isDeleted())
12660     return false;
12661
12662   bool MissingPrototype = true;
12663   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12664        Prev; Prev = Prev->getPreviousDecl()) {
12665     // Ignore any declarations that occur in function or method
12666     // scope, because they aren't visible from the header.
12667     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12668       continue;
12669
12670     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12671     if (FD->getNumParams() == 0)
12672       PossibleZeroParamPrototype = Prev;
12673     break;
12674   }
12675
12676   return MissingPrototype;
12677 }
12678
12679 void
12680 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12681                                    const FunctionDecl *EffectiveDefinition,
12682                                    SkipBodyInfo *SkipBody) {
12683   const FunctionDecl *Definition = EffectiveDefinition;
12684   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12685     // If this is a friend function defined in a class template, it does not
12686     // have a body until it is used, nevertheless it is a definition, see
12687     // [temp.inst]p2:
12688     //
12689     // ... for the purpose of determining whether an instantiated redeclaration
12690     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12691     // corresponds to a definition in the template is considered to be a
12692     // definition.
12693     //
12694     // The following code must produce redefinition error:
12695     //
12696     //     template<typename T> struct C20 { friend void func_20() {} };
12697     //     C20<int> c20i;
12698     //     void func_20() {}
12699     //
12700     for (auto I : FD->redecls()) {
12701       if (I != FD && !I->isInvalidDecl() &&
12702           I->getFriendObjectKind() != Decl::FOK_None) {
12703         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12704           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12705             // A merged copy of the same function, instantiated as a member of
12706             // the same class, is OK.
12707             if (declaresSameEntity(OrigFD, Original) &&
12708                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12709                                    cast<Decl>(FD->getLexicalDeclContext())))
12710               continue;
12711           }
12712
12713           if (Original->isThisDeclarationADefinition()) {
12714             Definition = I;
12715             break;
12716           }
12717         }
12718       }
12719     }
12720   }
12721   if (!Definition)
12722     return;
12723
12724   if (canRedefineFunction(Definition, getLangOpts()))
12725     return;
12726
12727   // Don't emit an error when this is redefinition of a typo-corrected
12728   // definition.
12729   if (TypoCorrectedFunctionDefinitions.count(Definition))
12730     return;
12731
12732   // If we don't have a visible definition of the function, and it's inline or
12733   // a template, skip the new definition.
12734   if (SkipBody && !hasVisibleDefinition(Definition) &&
12735       (Definition->getFormalLinkage() == InternalLinkage ||
12736        Definition->isInlined() ||
12737        Definition->getDescribedFunctionTemplate() ||
12738        Definition->getNumTemplateParameterLists())) {
12739     SkipBody->ShouldSkip = true;
12740     if (auto *TD = Definition->getDescribedFunctionTemplate())
12741       makeMergedDefinitionVisible(TD);
12742     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12743     return;
12744   }
12745
12746   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12747       Definition->getStorageClass() == SC_Extern)
12748     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12749         << FD->getDeclName() << getLangOpts().CPlusPlus;
12750   else
12751     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12752
12753   Diag(Definition->getLocation(), diag::note_previous_definition);
12754   FD->setInvalidDecl();
12755 }
12756
12757 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12758                                    Sema &S) {
12759   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12760
12761   LambdaScopeInfo *LSI = S.PushLambdaScope();
12762   LSI->CallOperator = CallOperator;
12763   LSI->Lambda = LambdaClass;
12764   LSI->ReturnType = CallOperator->getReturnType();
12765   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12766
12767   if (LCD == LCD_None)
12768     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12769   else if (LCD == LCD_ByCopy)
12770     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12771   else if (LCD == LCD_ByRef)
12772     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12773   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12774
12775   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12776   LSI->Mutable = !CallOperator->isConst();
12777
12778   // Add the captures to the LSI so they can be noted as already
12779   // captured within tryCaptureVar.
12780   auto I = LambdaClass->field_begin();
12781   for (const auto &C : LambdaClass->captures()) {
12782     if (C.capturesVariable()) {
12783       VarDecl *VD = C.getCapturedVar();
12784       if (VD->isInitCapture())
12785         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12786       QualType CaptureType = VD->getType();
12787       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12788       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12789           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12790           /*EllipsisLoc*/C.isPackExpansion()
12791                          ? C.getEllipsisLoc() : SourceLocation(),
12792           CaptureType, /*Expr*/ nullptr);
12793
12794     } else if (C.capturesThis()) {
12795       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12796                               /*Expr*/ nullptr,
12797                               C.getCaptureKind() == LCK_StarThis);
12798     } else {
12799       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12800     }
12801     ++I;
12802   }
12803 }
12804
12805 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12806                                     SkipBodyInfo *SkipBody) {
12807   if (!D) {
12808     // Parsing the function declaration failed in some way. Push on a fake scope
12809     // anyway so we can try to parse the function body.
12810     PushFunctionScope();
12811     return D;
12812   }
12813
12814   FunctionDecl *FD = nullptr;
12815
12816   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12817     FD = FunTmpl->getTemplatedDecl();
12818   else
12819     FD = cast<FunctionDecl>(D);
12820
12821   // Check for defining attributes before the check for redefinition.
12822   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12823     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12824     FD->dropAttr<AliasAttr>();
12825     FD->setInvalidDecl();
12826   }
12827   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12828     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12829     FD->dropAttr<IFuncAttr>();
12830     FD->setInvalidDecl();
12831   }
12832
12833   // See if this is a redefinition. If 'will have body' is already set, then
12834   // these checks were already performed when it was set.
12835   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12836     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12837
12838     // If we're skipping the body, we're done. Don't enter the scope.
12839     if (SkipBody && SkipBody->ShouldSkip)
12840       return D;
12841   }
12842
12843   // Mark this function as "will have a body eventually".  This lets users to
12844   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12845   // this function.
12846   FD->setWillHaveBody();
12847
12848   // If we are instantiating a generic lambda call operator, push
12849   // a LambdaScopeInfo onto the function stack.  But use the information
12850   // that's already been calculated (ActOnLambdaExpr) to prime the current
12851   // LambdaScopeInfo.
12852   // When the template operator is being specialized, the LambdaScopeInfo,
12853   // has to be properly restored so that tryCaptureVariable doesn't try
12854   // and capture any new variables. In addition when calculating potential
12855   // captures during transformation of nested lambdas, it is necessary to
12856   // have the LSI properly restored.
12857   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12858     assert(inTemplateInstantiation() &&
12859            "There should be an active template instantiation on the stack "
12860            "when instantiating a generic lambda!");
12861     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12862   } else {
12863     // Enter a new function scope
12864     PushFunctionScope();
12865   }
12866
12867   // Builtin functions cannot be defined.
12868   if (unsigned BuiltinID = FD->getBuiltinID()) {
12869     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12870         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12871       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12872       FD->setInvalidDecl();
12873     }
12874   }
12875
12876   // The return type of a function definition must be complete
12877   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12878   QualType ResultType = FD->getReturnType();
12879   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12880       !FD->isInvalidDecl() &&
12881       RequireCompleteType(FD->getLocation(), ResultType,
12882                           diag::err_func_def_incomplete_result))
12883     FD->setInvalidDecl();
12884
12885   if (FnBodyScope)
12886     PushDeclContext(FnBodyScope, FD);
12887
12888   // Check the validity of our function parameters
12889   CheckParmsForFunctionDef(FD->parameters(),
12890                            /*CheckParameterNames=*/true);
12891
12892   // Add non-parameter declarations already in the function to the current
12893   // scope.
12894   if (FnBodyScope) {
12895     for (Decl *NPD : FD->decls()) {
12896       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12897       if (!NonParmDecl)
12898         continue;
12899       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12900              "parameters should not be in newly created FD yet");
12901
12902       // If the decl has a name, make it accessible in the current scope.
12903       if (NonParmDecl->getDeclName())
12904         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12905
12906       // Similarly, dive into enums and fish their constants out, making them
12907       // accessible in this scope.
12908       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12909         for (auto *EI : ED->enumerators())
12910           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12911       }
12912     }
12913   }
12914
12915   // Introduce our parameters into the function scope
12916   for (auto Param : FD->parameters()) {
12917     Param->setOwningFunction(FD);
12918
12919     // If this has an identifier, add it to the scope stack.
12920     if (Param->getIdentifier() && FnBodyScope) {
12921       CheckShadow(FnBodyScope, Param);
12922
12923       PushOnScopeChains(Param, FnBodyScope);
12924     }
12925   }
12926
12927   // Ensure that the function's exception specification is instantiated.
12928   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12929     ResolveExceptionSpec(D->getLocation(), FPT);
12930
12931   // dllimport cannot be applied to non-inline function definitions.
12932   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12933       !FD->isTemplateInstantiation()) {
12934     assert(!FD->hasAttr<DLLExportAttr>());
12935     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12936     FD->setInvalidDecl();
12937     return D;
12938   }
12939   // We want to attach documentation to original Decl (which might be
12940   // a function template).
12941   ActOnDocumentableDecl(D);
12942   if (getCurLexicalContext()->isObjCContainer() &&
12943       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12944       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12945     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12946
12947   return D;
12948 }
12949
12950 /// Given the set of return statements within a function body,
12951 /// compute the variables that are subject to the named return value
12952 /// optimization.
12953 ///
12954 /// Each of the variables that is subject to the named return value
12955 /// optimization will be marked as NRVO variables in the AST, and any
12956 /// return statement that has a marked NRVO variable as its NRVO candidate can
12957 /// use the named return value optimization.
12958 ///
12959 /// This function applies a very simplistic algorithm for NRVO: if every return
12960 /// statement in the scope of a variable has the same NRVO candidate, that
12961 /// candidate is an NRVO variable.
12962 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12963   ReturnStmt **Returns = Scope->Returns.data();
12964
12965   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12966     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12967       if (!NRVOCandidate->isNRVOVariable())
12968         Returns[I]->setNRVOCandidate(nullptr);
12969     }
12970   }
12971 }
12972
12973 bool Sema::canDelayFunctionBody(const Declarator &D) {
12974   // We can't delay parsing the body of a constexpr function template (yet).
12975   if (D.getDeclSpec().isConstexprSpecified())
12976     return false;
12977
12978   // We can't delay parsing the body of a function template with a deduced
12979   // return type (yet).
12980   if (D.getDeclSpec().hasAutoTypeSpec()) {
12981     // If the placeholder introduces a non-deduced trailing return type,
12982     // we can still delay parsing it.
12983     if (D.getNumTypeObjects()) {
12984       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12985       if (Outer.Kind == DeclaratorChunk::Function &&
12986           Outer.Fun.hasTrailingReturnType()) {
12987         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12988         return Ty.isNull() || !Ty->isUndeducedType();
12989       }
12990     }
12991     return false;
12992   }
12993
12994   return true;
12995 }
12996
12997 bool Sema::canSkipFunctionBody(Decl *D) {
12998   // We cannot skip the body of a function (or function template) which is
12999   // constexpr, since we may need to evaluate its body in order to parse the
13000   // rest of the file.
13001   // We cannot skip the body of a function with an undeduced return type,
13002   // because any callers of that function need to know the type.
13003   if (const FunctionDecl *FD = D->getAsFunction()) {
13004     if (FD->isConstexpr())
13005       return false;
13006     // We can't simply call Type::isUndeducedType here, because inside template
13007     // auto can be deduced to a dependent type, which is not considered
13008     // "undeduced".
13009     if (FD->getReturnType()->getContainedDeducedType())
13010       return false;
13011   }
13012   return Consumer.shouldSkipFunctionBody(D);
13013 }
13014
13015 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13016   if (!Decl)
13017     return nullptr;
13018   if (FunctionDecl *FD = Decl->getAsFunction())
13019     FD->setHasSkippedBody();
13020   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13021     MD->setHasSkippedBody();
13022   return Decl;
13023 }
13024
13025 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13026   return ActOnFinishFunctionBody(D, BodyArg, false);
13027 }
13028
13029 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13030                                     bool IsInstantiation) {
13031   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13032
13033   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13034   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13035
13036   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
13037     CheckCompletedCoroutineBody(FD, Body);
13038
13039   if (FD) {
13040     FD->setBody(Body);
13041     FD->setWillHaveBody(false);
13042
13043     if (getLangOpts().CPlusPlus14) {
13044       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13045           FD->getReturnType()->isUndeducedType()) {
13046         // If the function has a deduced result type but contains no 'return'
13047         // statements, the result type as written must be exactly 'auto', and
13048         // the deduced result type is 'void'.
13049         if (!FD->getReturnType()->getAs<AutoType>()) {
13050           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13051               << FD->getReturnType();
13052           FD->setInvalidDecl();
13053         } else {
13054           // Substitute 'void' for the 'auto' in the type.
13055           TypeLoc ResultType = getReturnTypeLoc(FD);
13056           Context.adjustDeducedFunctionResultType(
13057               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13058         }
13059       }
13060     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13061       // In C++11, we don't use 'auto' deduction rules for lambda call
13062       // operators because we don't support return type deduction.
13063       auto *LSI = getCurLambda();
13064       if (LSI->HasImplicitReturnType) {
13065         deduceClosureReturnType(*LSI);
13066
13067         // C++11 [expr.prim.lambda]p4:
13068         //   [...] if there are no return statements in the compound-statement
13069         //   [the deduced type is] the type void
13070         QualType RetType =
13071             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13072
13073         // Update the return type to the deduced type.
13074         const FunctionProtoType *Proto =
13075             FD->getType()->getAs<FunctionProtoType>();
13076         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13077                                             Proto->getExtProtoInfo()));
13078       }
13079     }
13080
13081     // If the function implicitly returns zero (like 'main') or is naked,
13082     // don't complain about missing return statements.
13083     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13084       WP.disableCheckFallThrough();
13085
13086     // MSVC permits the use of pure specifier (=0) on function definition,
13087     // defined at class scope, warn about this non-standard construct.
13088     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13089       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13090
13091     if (!FD->isInvalidDecl()) {
13092       // Don't diagnose unused parameters of defaulted or deleted functions.
13093       if (!FD->isDeleted() && !FD->isDefaulted())
13094         DiagnoseUnusedParameters(FD->parameters());
13095       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13096                                              FD->getReturnType(), FD);
13097
13098       // If this is a structor, we need a vtable.
13099       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13100         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13101       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13102         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13103
13104       // Try to apply the named return value optimization. We have to check
13105       // if we can do this here because lambdas keep return statements around
13106       // to deduce an implicit return type.
13107       if (FD->getReturnType()->isRecordType() &&
13108           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13109         computeNRVO(Body, getCurFunction());
13110     }
13111
13112     // GNU warning -Wmissing-prototypes:
13113     //   Warn if a global function is defined without a previous
13114     //   prototype declaration. This warning is issued even if the
13115     //   definition itself provides a prototype. The aim is to detect
13116     //   global functions that fail to be declared in header files.
13117     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13118     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13119       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13120
13121       if (PossibleZeroParamPrototype) {
13122         // We found a declaration that is not a prototype,
13123         // but that could be a zero-parameter prototype
13124         if (TypeSourceInfo *TI =
13125                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13126           TypeLoc TL = TI->getTypeLoc();
13127           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13128             Diag(PossibleZeroParamPrototype->getLocation(),
13129                  diag::note_declaration_not_a_prototype)
13130                 << PossibleZeroParamPrototype
13131                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13132         }
13133       }
13134
13135       // GNU warning -Wstrict-prototypes
13136       //   Warn if K&R function is defined without a previous declaration.
13137       //   This warning is issued only if the definition itself does not provide
13138       //   a prototype. Only K&R definitions do not provide a prototype.
13139       //   An empty list in a function declarator that is part of a definition
13140       //   of that function specifies that the function has no parameters
13141       //   (C99 6.7.5.3p14)
13142       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13143           !LangOpts.CPlusPlus) {
13144         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13145         TypeLoc TL = TI->getTypeLoc();
13146         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13147         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13148       }
13149     }
13150
13151     // Warn on CPUDispatch with an actual body.
13152     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13153       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13154         if (!CmpndBody->body_empty())
13155           Diag(CmpndBody->body_front()->getLocStart(),
13156                diag::warn_dispatch_body_ignored);
13157
13158     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13159       const CXXMethodDecl *KeyFunction;
13160       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13161           MD->isVirtual() &&
13162           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13163           MD == KeyFunction->getCanonicalDecl()) {
13164         // Update the key-function state if necessary for this ABI.
13165         if (FD->isInlined() &&
13166             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13167           Context.setNonKeyFunction(MD);
13168
13169           // If the newly-chosen key function is already defined, then we
13170           // need to mark the vtable as used retroactively.
13171           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13172           const FunctionDecl *Definition;
13173           if (KeyFunction && KeyFunction->isDefined(Definition))
13174             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13175         } else {
13176           // We just defined they key function; mark the vtable as used.
13177           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13178         }
13179       }
13180     }
13181
13182     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13183            "Function parsing confused");
13184   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13185     assert(MD == getCurMethodDecl() && "Method parsing confused");
13186     MD->setBody(Body);
13187     if (!MD->isInvalidDecl()) {
13188       DiagnoseUnusedParameters(MD->parameters());
13189       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13190                                              MD->getReturnType(), MD);
13191
13192       if (Body)
13193         computeNRVO(Body, getCurFunction());
13194     }
13195     if (getCurFunction()->ObjCShouldCallSuper) {
13196       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
13197         << MD->getSelector().getAsString();
13198       getCurFunction()->ObjCShouldCallSuper = false;
13199     }
13200     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13201       const ObjCMethodDecl *InitMethod = nullptr;
13202       bool isDesignated =
13203           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13204       assert(isDesignated && InitMethod);
13205       (void)isDesignated;
13206
13207       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13208         auto IFace = MD->getClassInterface();
13209         if (!IFace)
13210           return false;
13211         auto SuperD = IFace->getSuperClass();
13212         if (!SuperD)
13213           return false;
13214         return SuperD->getIdentifier() ==
13215             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13216       };
13217       // Don't issue this warning for unavailable inits or direct subclasses
13218       // of NSObject.
13219       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13220         Diag(MD->getLocation(),
13221              diag::warn_objc_designated_init_missing_super_call);
13222         Diag(InitMethod->getLocation(),
13223              diag::note_objc_designated_init_marked_here);
13224       }
13225       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13226     }
13227     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13228       // Don't issue this warning for unavaialable inits.
13229       if (!MD->isUnavailable())
13230         Diag(MD->getLocation(),
13231              diag::warn_objc_secondary_init_missing_init_call);
13232       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13233     }
13234   } else {
13235     // Parsing the function declaration failed in some way. Pop the fake scope
13236     // we pushed on.
13237     PopFunctionScopeInfo(ActivePolicy, dcl);
13238     return nullptr;
13239   }
13240
13241   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13242     DiagnoseUnguardedAvailabilityViolations(dcl);
13243
13244   assert(!getCurFunction()->ObjCShouldCallSuper &&
13245          "This should only be set for ObjC methods, which should have been "
13246          "handled in the block above.");
13247
13248   // Verify and clean out per-function state.
13249   if (Body && (!FD || !FD->isDefaulted())) {
13250     // C++ constructors that have function-try-blocks can't have return
13251     // statements in the handlers of that block. (C++ [except.handle]p14)
13252     // Verify this.
13253     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13254       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13255
13256     // Verify that gotos and switch cases don't jump into scopes illegally.
13257     if (getCurFunction()->NeedsScopeChecking() &&
13258         !PP.isCodeCompletionEnabled())
13259       DiagnoseInvalidJumps(Body);
13260
13261     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13262       if (!Destructor->getParent()->isDependentType())
13263         CheckDestructor(Destructor);
13264
13265       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13266                                              Destructor->getParent());
13267     }
13268
13269     // If any errors have occurred, clear out any temporaries that may have
13270     // been leftover. This ensures that these temporaries won't be picked up for
13271     // deletion in some later function.
13272     if (getDiagnostics().hasErrorOccurred() ||
13273         getDiagnostics().getSuppressAllDiagnostics()) {
13274       DiscardCleanupsInEvaluationContext();
13275     }
13276     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13277         !isa<FunctionTemplateDecl>(dcl)) {
13278       // Since the body is valid, issue any analysis-based warnings that are
13279       // enabled.
13280       ActivePolicy = &WP;
13281     }
13282
13283     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13284         (!CheckConstexprFunctionDecl(FD) ||
13285          !CheckConstexprFunctionBody(FD, Body)))
13286       FD->setInvalidDecl();
13287
13288     if (FD && FD->hasAttr<NakedAttr>()) {
13289       for (const Stmt *S : Body->children()) {
13290         // Allow local register variables without initializer as they don't
13291         // require prologue.
13292         bool RegisterVariables = false;
13293         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13294           for (const auto *Decl : DS->decls()) {
13295             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13296               RegisterVariables =
13297                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13298               if (!RegisterVariables)
13299                 break;
13300             }
13301           }
13302         }
13303         if (RegisterVariables)
13304           continue;
13305         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13306           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
13307           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13308           FD->setInvalidDecl();
13309           break;
13310         }
13311       }
13312     }
13313
13314     assert(ExprCleanupObjects.size() ==
13315                ExprEvalContexts.back().NumCleanupObjects &&
13316            "Leftover temporaries in function");
13317     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13318     assert(MaybeODRUseExprs.empty() &&
13319            "Leftover expressions for odr-use checking");
13320   }
13321
13322   if (!IsInstantiation)
13323     PopDeclContext();
13324
13325   PopFunctionScopeInfo(ActivePolicy, dcl);
13326   // If any errors have occurred, clear out any temporaries that may have
13327   // been leftover. This ensures that these temporaries won't be picked up for
13328   // deletion in some later function.
13329   if (getDiagnostics().hasErrorOccurred()) {
13330     DiscardCleanupsInEvaluationContext();
13331   }
13332
13333   return dcl;
13334 }
13335
13336 /// When we finish delayed parsing of an attribute, we must attach it to the
13337 /// relevant Decl.
13338 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13339                                        ParsedAttributes &Attrs) {
13340   // Always attach attributes to the underlying decl.
13341   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13342     D = TD->getTemplatedDecl();
13343   ProcessDeclAttributeList(S, D, Attrs);
13344
13345   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13346     if (Method->isStatic())
13347       checkThisInStaticMemberFunctionAttributes(Method);
13348 }
13349
13350 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13351 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13352 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13353                                           IdentifierInfo &II, Scope *S) {
13354   // Find the scope in which the identifier is injected and the corresponding
13355   // DeclContext.
13356   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13357   // In that case, we inject the declaration into the translation unit scope
13358   // instead.
13359   Scope *BlockScope = S;
13360   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13361     BlockScope = BlockScope->getParent();
13362
13363   Scope *ContextScope = BlockScope;
13364   while (!ContextScope->getEntity())
13365     ContextScope = ContextScope->getParent();
13366   ContextRAII SavedContext(*this, ContextScope->getEntity());
13367
13368   // Before we produce a declaration for an implicitly defined
13369   // function, see whether there was a locally-scoped declaration of
13370   // this name as a function or variable. If so, use that
13371   // (non-visible) declaration, and complain about it.
13372   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13373   if (ExternCPrev) {
13374     // We still need to inject the function into the enclosing block scope so
13375     // that later (non-call) uses can see it.
13376     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13377
13378     // C89 footnote 38:
13379     //   If in fact it is not defined as having type "function returning int",
13380     //   the behavior is undefined.
13381     if (!isa<FunctionDecl>(ExternCPrev) ||
13382         !Context.typesAreCompatible(
13383             cast<FunctionDecl>(ExternCPrev)->getType(),
13384             Context.getFunctionNoProtoType(Context.IntTy))) {
13385       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13386           << ExternCPrev << !getLangOpts().C99;
13387       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13388       return ExternCPrev;
13389     }
13390   }
13391
13392   // Extension in C99.  Legal in C90, but warn about it.
13393   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13394   unsigned diag_id;
13395   if (II.getName().startswith("__builtin_"))
13396     diag_id = diag::warn_builtin_unknown;
13397   else if (getLangOpts().C99 || getLangOpts().OpenCL)
13398     diag_id = diag::ext_implicit_function_decl;
13399   else
13400     diag_id = diag::warn_implicit_function_decl;
13401   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13402
13403   // If we found a prior declaration of this function, don't bother building
13404   // another one. We've already pushed that one into scope, so there's nothing
13405   // more to do.
13406   if (ExternCPrev)
13407     return ExternCPrev;
13408
13409   // Because typo correction is expensive, only do it if the implicit
13410   // function declaration is going to be treated as an error.
13411   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13412     TypoCorrection Corrected;
13413     if (S &&
13414         (Corrected = CorrectTypo(
13415              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13416              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13417       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13418                    /*ErrorRecovery*/false);
13419   }
13420
13421   // Set a Declarator for the implicit definition: int foo();
13422   const char *Dummy;
13423   AttributeFactory attrFactory;
13424   DeclSpec DS(attrFactory);
13425   unsigned DiagID;
13426   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13427                                   Context.getPrintingPolicy());
13428   (void)Error; // Silence warning.
13429   assert(!Error && "Error setting up implicit decl!");
13430   SourceLocation NoLoc;
13431   Declarator D(DS, DeclaratorContext::BlockContext);
13432   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13433                                              /*IsAmbiguous=*/false,
13434                                              /*LParenLoc=*/NoLoc,
13435                                              /*Params=*/nullptr,
13436                                              /*NumParams=*/0,
13437                                              /*EllipsisLoc=*/NoLoc,
13438                                              /*RParenLoc=*/NoLoc,
13439                                              /*TypeQuals=*/0,
13440                                              /*RefQualifierIsLvalueRef=*/true,
13441                                              /*RefQualifierLoc=*/NoLoc,
13442                                              /*ConstQualifierLoc=*/NoLoc,
13443                                              /*VolatileQualifierLoc=*/NoLoc,
13444                                              /*RestrictQualifierLoc=*/NoLoc,
13445                                              /*MutableLoc=*/NoLoc, EST_None,
13446                                              /*ESpecRange=*/SourceRange(),
13447                                              /*Exceptions=*/nullptr,
13448                                              /*ExceptionRanges=*/nullptr,
13449                                              /*NumExceptions=*/0,
13450                                              /*NoexceptExpr=*/nullptr,
13451                                              /*ExceptionSpecTokens=*/nullptr,
13452                                              /*DeclsInPrototype=*/None, Loc,
13453                                              Loc, D),
13454                 std::move(DS.getAttributes()), SourceLocation());
13455   D.SetIdentifier(&II, Loc);
13456
13457   // Insert this function into the enclosing block scope.
13458   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13459   FD->setImplicit();
13460
13461   AddKnownFunctionAttributes(FD);
13462
13463   return FD;
13464 }
13465
13466 /// Adds any function attributes that we know a priori based on
13467 /// the declaration of this function.
13468 ///
13469 /// These attributes can apply both to implicitly-declared builtins
13470 /// (like __builtin___printf_chk) or to library-declared functions
13471 /// like NSLog or printf.
13472 ///
13473 /// We need to check for duplicate attributes both here and where user-written
13474 /// attributes are applied to declarations.
13475 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13476   if (FD->isInvalidDecl())
13477     return;
13478
13479   // If this is a built-in function, map its builtin attributes to
13480   // actual attributes.
13481   if (unsigned BuiltinID = FD->getBuiltinID()) {
13482     // Handle printf-formatting attributes.
13483     unsigned FormatIdx;
13484     bool HasVAListArg;
13485     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13486       if (!FD->hasAttr<FormatAttr>()) {
13487         const char *fmt = "printf";
13488         unsigned int NumParams = FD->getNumParams();
13489         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13490             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13491           fmt = "NSString";
13492         FD->addAttr(FormatAttr::CreateImplicit(Context,
13493                                                &Context.Idents.get(fmt),
13494                                                FormatIdx+1,
13495                                                HasVAListArg ? 0 : FormatIdx+2,
13496                                                FD->getLocation()));
13497       }
13498     }
13499     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13500                                              HasVAListArg)) {
13501      if (!FD->hasAttr<FormatAttr>())
13502        FD->addAttr(FormatAttr::CreateImplicit(Context,
13503                                               &Context.Idents.get("scanf"),
13504                                               FormatIdx+1,
13505                                               HasVAListArg ? 0 : FormatIdx+2,
13506                                               FD->getLocation()));
13507     }
13508
13509     // Mark const if we don't care about errno and that is the only thing
13510     // preventing the function from being const. This allows IRgen to use LLVM
13511     // intrinsics for such functions.
13512     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13513         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13514       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13515
13516     // We make "fma" on some platforms const because we know it does not set
13517     // errno in those environments even though it could set errno based on the
13518     // C standard.
13519     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13520     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13521         !FD->hasAttr<ConstAttr>()) {
13522       switch (BuiltinID) {
13523       case Builtin::BI__builtin_fma:
13524       case Builtin::BI__builtin_fmaf:
13525       case Builtin::BI__builtin_fmal:
13526       case Builtin::BIfma:
13527       case Builtin::BIfmaf:
13528       case Builtin::BIfmal:
13529         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13530         break;
13531       default:
13532         break;
13533       }
13534     }
13535
13536     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13537         !FD->hasAttr<ReturnsTwiceAttr>())
13538       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13539                                          FD->getLocation()));
13540     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13541       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13542     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13543       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13544     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13545       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13546     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13547         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13548       // Add the appropriate attribute, depending on the CUDA compilation mode
13549       // and which target the builtin belongs to. For example, during host
13550       // compilation, aux builtins are __device__, while the rest are __host__.
13551       if (getLangOpts().CUDAIsDevice !=
13552           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13553         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13554       else
13555         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13556     }
13557   }
13558
13559   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13560   // throw, add an implicit nothrow attribute to any extern "C" function we come
13561   // across.
13562   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13563       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13564     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13565     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13566       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13567   }
13568
13569   IdentifierInfo *Name = FD->getIdentifier();
13570   if (!Name)
13571     return;
13572   if ((!getLangOpts().CPlusPlus &&
13573        FD->getDeclContext()->isTranslationUnit()) ||
13574       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13575        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13576        LinkageSpecDecl::lang_c)) {
13577     // Okay: this could be a libc/libm/Objective-C function we know
13578     // about.
13579   } else
13580     return;
13581
13582   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13583     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13584     // target-specific builtins, perhaps?
13585     if (!FD->hasAttr<FormatAttr>())
13586       FD->addAttr(FormatAttr::CreateImplicit(Context,
13587                                              &Context.Idents.get("printf"), 2,
13588                                              Name->isStr("vasprintf") ? 0 : 3,
13589                                              FD->getLocation()));
13590   }
13591
13592   if (Name->isStr("__CFStringMakeConstantString")) {
13593     // We already have a __builtin___CFStringMakeConstantString,
13594     // but builds that use -fno-constant-cfstrings don't go through that.
13595     if (!FD->hasAttr<FormatArgAttr>())
13596       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13597                                                 FD->getLocation()));
13598   }
13599 }
13600
13601 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13602                                     TypeSourceInfo *TInfo) {
13603   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13604   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13605
13606   if (!TInfo) {
13607     assert(D.isInvalidType() && "no declarator info for valid type");
13608     TInfo = Context.getTrivialTypeSourceInfo(T);
13609   }
13610
13611   // Scope manipulation handled by caller.
13612   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13613                                            D.getLocStart(),
13614                                            D.getIdentifierLoc(),
13615                                            D.getIdentifier(),
13616                                            TInfo);
13617
13618   // Bail out immediately if we have an invalid declaration.
13619   if (D.isInvalidType()) {
13620     NewTD->setInvalidDecl();
13621     return NewTD;
13622   }
13623
13624   if (D.getDeclSpec().isModulePrivateSpecified()) {
13625     if (CurContext->isFunctionOrMethod())
13626       Diag(NewTD->getLocation(), diag::err_module_private_local)
13627         << 2 << NewTD->getDeclName()
13628         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13629         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13630     else
13631       NewTD->setModulePrivate();
13632   }
13633
13634   // C++ [dcl.typedef]p8:
13635   //   If the typedef declaration defines an unnamed class (or
13636   //   enum), the first typedef-name declared by the declaration
13637   //   to be that class type (or enum type) is used to denote the
13638   //   class type (or enum type) for linkage purposes only.
13639   // We need to check whether the type was declared in the declaration.
13640   switch (D.getDeclSpec().getTypeSpecType()) {
13641   case TST_enum:
13642   case TST_struct:
13643   case TST_interface:
13644   case TST_union:
13645   case TST_class: {
13646     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13647     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13648     break;
13649   }
13650
13651   default:
13652     break;
13653   }
13654
13655   return NewTD;
13656 }
13657
13658 /// Check that this is a valid underlying type for an enum declaration.
13659 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13660   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13661   QualType T = TI->getType();
13662
13663   if (T->isDependentType())
13664     return false;
13665
13666   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13667     if (BT->isInteger())
13668       return false;
13669
13670   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13671   return true;
13672 }
13673
13674 /// Check whether this is a valid redeclaration of a previous enumeration.
13675 /// \return true if the redeclaration was invalid.
13676 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13677                                   QualType EnumUnderlyingTy, bool IsFixed,
13678                                   const EnumDecl *Prev) {
13679   if (IsScoped != Prev->isScoped()) {
13680     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13681       << Prev->isScoped();
13682     Diag(Prev->getLocation(), diag::note_previous_declaration);
13683     return true;
13684   }
13685
13686   if (IsFixed && Prev->isFixed()) {
13687     if (!EnumUnderlyingTy->isDependentType() &&
13688         !Prev->getIntegerType()->isDependentType() &&
13689         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13690                                         Prev->getIntegerType())) {
13691       // TODO: Highlight the underlying type of the redeclaration.
13692       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13693         << EnumUnderlyingTy << Prev->getIntegerType();
13694       Diag(Prev->getLocation(), diag::note_previous_declaration)
13695           << Prev->getIntegerTypeRange();
13696       return true;
13697     }
13698   } else if (IsFixed != Prev->isFixed()) {
13699     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13700       << Prev->isFixed();
13701     Diag(Prev->getLocation(), diag::note_previous_declaration);
13702     return true;
13703   }
13704
13705   return false;
13706 }
13707
13708 /// Get diagnostic %select index for tag kind for
13709 /// redeclaration diagnostic message.
13710 /// WARNING: Indexes apply to particular diagnostics only!
13711 ///
13712 /// \returns diagnostic %select index.
13713 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13714   switch (Tag) {
13715   case TTK_Struct: return 0;
13716   case TTK_Interface: return 1;
13717   case TTK_Class:  return 2;
13718   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13719   }
13720 }
13721
13722 /// Determine if tag kind is a class-key compatible with
13723 /// class for redeclaration (class, struct, or __interface).
13724 ///
13725 /// \returns true iff the tag kind is compatible.
13726 static bool isClassCompatTagKind(TagTypeKind Tag)
13727 {
13728   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13729 }
13730
13731 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13732                                              TagTypeKind TTK) {
13733   if (isa<TypedefDecl>(PrevDecl))
13734     return NTK_Typedef;
13735   else if (isa<TypeAliasDecl>(PrevDecl))
13736     return NTK_TypeAlias;
13737   else if (isa<ClassTemplateDecl>(PrevDecl))
13738     return NTK_Template;
13739   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13740     return NTK_TypeAliasTemplate;
13741   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13742     return NTK_TemplateTemplateArgument;
13743   switch (TTK) {
13744   case TTK_Struct:
13745   case TTK_Interface:
13746   case TTK_Class:
13747     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13748   case TTK_Union:
13749     return NTK_NonUnion;
13750   case TTK_Enum:
13751     return NTK_NonEnum;
13752   }
13753   llvm_unreachable("invalid TTK");
13754 }
13755
13756 /// Determine whether a tag with a given kind is acceptable
13757 /// as a redeclaration of the given tag declaration.
13758 ///
13759 /// \returns true if the new tag kind is acceptable, false otherwise.
13760 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13761                                         TagTypeKind NewTag, bool isDefinition,
13762                                         SourceLocation NewTagLoc,
13763                                         const IdentifierInfo *Name) {
13764   // C++ [dcl.type.elab]p3:
13765   //   The class-key or enum keyword present in the
13766   //   elaborated-type-specifier shall agree in kind with the
13767   //   declaration to which the name in the elaborated-type-specifier
13768   //   refers. This rule also applies to the form of
13769   //   elaborated-type-specifier that declares a class-name or
13770   //   friend class since it can be construed as referring to the
13771   //   definition of the class. Thus, in any
13772   //   elaborated-type-specifier, the enum keyword shall be used to
13773   //   refer to an enumeration (7.2), the union class-key shall be
13774   //   used to refer to a union (clause 9), and either the class or
13775   //   struct class-key shall be used to refer to a class (clause 9)
13776   //   declared using the class or struct class-key.
13777   TagTypeKind OldTag = Previous->getTagKind();
13778   if (!isDefinition || !isClassCompatTagKind(NewTag))
13779     if (OldTag == NewTag)
13780       return true;
13781
13782   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13783     // Warn about the struct/class tag mismatch.
13784     bool isTemplate = false;
13785     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13786       isTemplate = Record->getDescribedClassTemplate();
13787
13788     if (inTemplateInstantiation()) {
13789       // In a template instantiation, do not offer fix-its for tag mismatches
13790       // since they usually mess up the template instead of fixing the problem.
13791       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13792         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13793         << getRedeclDiagFromTagKind(OldTag);
13794       return true;
13795     }
13796
13797     if (isDefinition) {
13798       // On definitions, check previous tags and issue a fix-it for each
13799       // one that doesn't match the current tag.
13800       if (Previous->getDefinition()) {
13801         // Don't suggest fix-its for redefinitions.
13802         return true;
13803       }
13804
13805       bool previousMismatch = false;
13806       for (auto I : Previous->redecls()) {
13807         if (I->getTagKind() != NewTag) {
13808           if (!previousMismatch) {
13809             previousMismatch = true;
13810             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13811               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13812               << getRedeclDiagFromTagKind(I->getTagKind());
13813           }
13814           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13815             << getRedeclDiagFromTagKind(NewTag)
13816             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13817                  TypeWithKeyword::getTagTypeKindName(NewTag));
13818         }
13819       }
13820       return true;
13821     }
13822
13823     // Check for a previous definition.  If current tag and definition
13824     // are same type, do nothing.  If no definition, but disagree with
13825     // with previous tag type, give a warning, but no fix-it.
13826     const TagDecl *Redecl = Previous->getDefinition() ?
13827                             Previous->getDefinition() : Previous;
13828     if (Redecl->getTagKind() == NewTag) {
13829       return true;
13830     }
13831
13832     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13833       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13834       << getRedeclDiagFromTagKind(OldTag);
13835     Diag(Redecl->getLocation(), diag::note_previous_use);
13836
13837     // If there is a previous definition, suggest a fix-it.
13838     if (Previous->getDefinition()) {
13839         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13840           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13841           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13842                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13843     }
13844
13845     return true;
13846   }
13847   return false;
13848 }
13849
13850 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13851 /// from an outer enclosing namespace or file scope inside a friend declaration.
13852 /// This should provide the commented out code in the following snippet:
13853 ///   namespace N {
13854 ///     struct X;
13855 ///     namespace M {
13856 ///       struct Y { friend struct /*N::*/ X; };
13857 ///     }
13858 ///   }
13859 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13860                                          SourceLocation NameLoc) {
13861   // While the decl is in a namespace, do repeated lookup of that name and see
13862   // if we get the same namespace back.  If we do not, continue until
13863   // translation unit scope, at which point we have a fully qualified NNS.
13864   SmallVector<IdentifierInfo *, 4> Namespaces;
13865   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13866   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13867     // This tag should be declared in a namespace, which can only be enclosed by
13868     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13869     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13870     if (!Namespace || Namespace->isAnonymousNamespace())
13871       return FixItHint();
13872     IdentifierInfo *II = Namespace->getIdentifier();
13873     Namespaces.push_back(II);
13874     NamedDecl *Lookup = SemaRef.LookupSingleName(
13875         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13876     if (Lookup == Namespace)
13877       break;
13878   }
13879
13880   // Once we have all the namespaces, reverse them to go outermost first, and
13881   // build an NNS.
13882   SmallString<64> Insertion;
13883   llvm::raw_svector_ostream OS(Insertion);
13884   if (DC->isTranslationUnit())
13885     OS << "::";
13886   std::reverse(Namespaces.begin(), Namespaces.end());
13887   for (auto *II : Namespaces)
13888     OS << II->getName() << "::";
13889   return FixItHint::CreateInsertion(NameLoc, Insertion);
13890 }
13891
13892 /// Determine whether a tag originally declared in context \p OldDC can
13893 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13894 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13895 /// using-declaration).
13896 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13897                                          DeclContext *NewDC) {
13898   OldDC = OldDC->getRedeclContext();
13899   NewDC = NewDC->getRedeclContext();
13900
13901   if (OldDC->Equals(NewDC))
13902     return true;
13903
13904   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13905   // encloses the other).
13906   if (S.getLangOpts().MSVCCompat &&
13907       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13908     return true;
13909
13910   return false;
13911 }
13912
13913 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
13914 /// former case, Name will be non-null.  In the later case, Name will be null.
13915 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13916 /// reference/declaration/definition of a tag.
13917 ///
13918 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13919 /// trailing-type-specifier) other than one in an alias-declaration.
13920 ///
13921 /// \param SkipBody If non-null, will be set to indicate if the caller should
13922 /// skip the definition of this tag and treat it as if it were a declaration.
13923 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13924                      SourceLocation KWLoc, CXXScopeSpec &SS,
13925                      IdentifierInfo *Name, SourceLocation NameLoc,
13926                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
13927                      SourceLocation ModulePrivateLoc,
13928                      MultiTemplateParamsArg TemplateParameterLists,
13929                      bool &OwnedDecl, bool &IsDependent,
13930                      SourceLocation ScopedEnumKWLoc,
13931                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
13932                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13933                      SkipBodyInfo *SkipBody) {
13934   // If this is not a definition, it must have a name.
13935   IdentifierInfo *OrigName = Name;
13936   assert((Name != nullptr || TUK == TUK_Definition) &&
13937          "Nameless record must be a definition!");
13938   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13939
13940   OwnedDecl = false;
13941   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13942   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13943
13944   // FIXME: Check member specializations more carefully.
13945   bool isMemberSpecialization = false;
13946   bool Invalid = false;
13947
13948   // We only need to do this matching if we have template parameters
13949   // or a scope specifier, which also conveniently avoids this work
13950   // for non-C++ cases.
13951   if (TemplateParameterLists.size() > 0 ||
13952       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13953     if (TemplateParameterList *TemplateParams =
13954             MatchTemplateParametersToScopeSpecifier(
13955                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13956                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13957       if (Kind == TTK_Enum) {
13958         Diag(KWLoc, diag::err_enum_template);
13959         return nullptr;
13960       }
13961
13962       if (TemplateParams->size() > 0) {
13963         // This is a declaration or definition of a class template (which may
13964         // be a member of another template).
13965
13966         if (Invalid)
13967           return nullptr;
13968
13969         OwnedDecl = false;
13970         DeclResult Result = CheckClassTemplate(
13971             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
13972             AS, ModulePrivateLoc,
13973             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
13974             TemplateParameterLists.data(), SkipBody);
13975         return Result.get();
13976       } else {
13977         // The "template<>" header is extraneous.
13978         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13979           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13980         isMemberSpecialization = true;
13981       }
13982     }
13983   }
13984
13985   // Figure out the underlying type if this a enum declaration. We need to do
13986   // this early, because it's needed to detect if this is an incompatible
13987   // redeclaration.
13988   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13989   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13990
13991   if (Kind == TTK_Enum) {
13992     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13993       // No underlying type explicitly specified, or we failed to parse the
13994       // type, default to int.
13995       EnumUnderlying = Context.IntTy.getTypePtr();
13996     } else if (UnderlyingType.get()) {
13997       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13998       // integral type; any cv-qualification is ignored.
13999       TypeSourceInfo *TI = nullptr;
14000       GetTypeFromParser(UnderlyingType.get(), &TI);
14001       EnumUnderlying = TI;
14002
14003       if (CheckEnumUnderlyingType(TI))
14004         // Recover by falling back to int.
14005         EnumUnderlying = Context.IntTy.getTypePtr();
14006
14007       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14008                                           UPPC_FixedUnderlyingType))
14009         EnumUnderlying = Context.IntTy.getTypePtr();
14010
14011     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14012       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14013       // of 'int'. However, if this is an unfixed forward declaration, don't set
14014       // the underlying type unless the user enables -fms-compatibility. This
14015       // makes unfixed forward declared enums incomplete and is more conforming.
14016       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14017         EnumUnderlying = Context.IntTy.getTypePtr();
14018     }
14019   }
14020
14021   DeclContext *SearchDC = CurContext;
14022   DeclContext *DC = CurContext;
14023   bool isStdBadAlloc = false;
14024   bool isStdAlignValT = false;
14025
14026   RedeclarationKind Redecl = forRedeclarationInCurContext();
14027   if (TUK == TUK_Friend || TUK == TUK_Reference)
14028     Redecl = NotForRedeclaration;
14029
14030   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14031   /// implemented asks for structural equivalence checking, the returned decl
14032   /// here is passed back to the parser, allowing the tag body to be parsed.
14033   auto createTagFromNewDecl = [&]() -> TagDecl * {
14034     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14035     // If there is an identifier, use the location of the identifier as the
14036     // location of the decl, otherwise use the location of the struct/union
14037     // keyword.
14038     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14039     TagDecl *New = nullptr;
14040
14041     if (Kind == TTK_Enum) {
14042       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14043                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14044       // If this is an undefined enum, bail.
14045       if (TUK != TUK_Definition && !Invalid)
14046         return nullptr;
14047       if (EnumUnderlying) {
14048         EnumDecl *ED = cast<EnumDecl>(New);
14049         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14050           ED->setIntegerTypeSourceInfo(TI);
14051         else
14052           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14053         ED->setPromotionType(ED->getIntegerType());
14054       }
14055     } else { // struct/union
14056       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14057                                nullptr);
14058     }
14059
14060     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14061       // Add alignment attributes if necessary; these attributes are checked
14062       // when the ASTContext lays out the structure.
14063       //
14064       // It is important for implementing the correct semantics that this
14065       // happen here (in ActOnTag). The #pragma pack stack is
14066       // maintained as a result of parser callbacks which can occur at
14067       // many points during the parsing of a struct declaration (because
14068       // the #pragma tokens are effectively skipped over during the
14069       // parsing of the struct).
14070       if (TUK == TUK_Definition) {
14071         AddAlignmentAttributesForRecord(RD);
14072         AddMsStructLayoutForRecord(RD);
14073       }
14074     }
14075     New->setLexicalDeclContext(CurContext);
14076     return New;
14077   };
14078
14079   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14080   if (Name && SS.isNotEmpty()) {
14081     // We have a nested-name tag ('struct foo::bar').
14082
14083     // Check for invalid 'foo::'.
14084     if (SS.isInvalid()) {
14085       Name = nullptr;
14086       goto CreateNewDecl;
14087     }
14088
14089     // If this is a friend or a reference to a class in a dependent
14090     // context, don't try to make a decl for it.
14091     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14092       DC = computeDeclContext(SS, false);
14093       if (!DC) {
14094         IsDependent = true;
14095         return nullptr;
14096       }
14097     } else {
14098       DC = computeDeclContext(SS, true);
14099       if (!DC) {
14100         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14101           << SS.getRange();
14102         return nullptr;
14103       }
14104     }
14105
14106     if (RequireCompleteDeclContext(SS, DC))
14107       return nullptr;
14108
14109     SearchDC = DC;
14110     // Look-up name inside 'foo::'.
14111     LookupQualifiedName(Previous, DC);
14112
14113     if (Previous.isAmbiguous())
14114       return nullptr;
14115
14116     if (Previous.empty()) {
14117       // Name lookup did not find anything. However, if the
14118       // nested-name-specifier refers to the current instantiation,
14119       // and that current instantiation has any dependent base
14120       // classes, we might find something at instantiation time: treat
14121       // this as a dependent elaborated-type-specifier.
14122       // But this only makes any sense for reference-like lookups.
14123       if (Previous.wasNotFoundInCurrentInstantiation() &&
14124           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14125         IsDependent = true;
14126         return nullptr;
14127       }
14128
14129       // A tag 'foo::bar' must already exist.
14130       Diag(NameLoc, diag::err_not_tag_in_scope)
14131         << Kind << Name << DC << SS.getRange();
14132       Name = nullptr;
14133       Invalid = true;
14134       goto CreateNewDecl;
14135     }
14136   } else if (Name) {
14137     // C++14 [class.mem]p14:
14138     //   If T is the name of a class, then each of the following shall have a
14139     //   name different from T:
14140     //    -- every member of class T that is itself a type
14141     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14142         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14143       return nullptr;
14144
14145     // If this is a named struct, check to see if there was a previous forward
14146     // declaration or definition.
14147     // FIXME: We're looking into outer scopes here, even when we
14148     // shouldn't be. Doing so can result in ambiguities that we
14149     // shouldn't be diagnosing.
14150     LookupName(Previous, S);
14151
14152     // When declaring or defining a tag, ignore ambiguities introduced
14153     // by types using'ed into this scope.
14154     if (Previous.isAmbiguous() &&
14155         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14156       LookupResult::Filter F = Previous.makeFilter();
14157       while (F.hasNext()) {
14158         NamedDecl *ND = F.next();
14159         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14160                 SearchDC->getRedeclContext()))
14161           F.erase();
14162       }
14163       F.done();
14164     }
14165
14166     // C++11 [namespace.memdef]p3:
14167     //   If the name in a friend declaration is neither qualified nor
14168     //   a template-id and the declaration is a function or an
14169     //   elaborated-type-specifier, the lookup to determine whether
14170     //   the entity has been previously declared shall not consider
14171     //   any scopes outside the innermost enclosing namespace.
14172     //
14173     // MSVC doesn't implement the above rule for types, so a friend tag
14174     // declaration may be a redeclaration of a type declared in an enclosing
14175     // scope.  They do implement this rule for friend functions.
14176     //
14177     // Does it matter that this should be by scope instead of by
14178     // semantic context?
14179     if (!Previous.empty() && TUK == TUK_Friend) {
14180       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14181       LookupResult::Filter F = Previous.makeFilter();
14182       bool FriendSawTagOutsideEnclosingNamespace = false;
14183       while (F.hasNext()) {
14184         NamedDecl *ND = F.next();
14185         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14186         if (DC->isFileContext() &&
14187             !EnclosingNS->Encloses(ND->getDeclContext())) {
14188           if (getLangOpts().MSVCCompat)
14189             FriendSawTagOutsideEnclosingNamespace = true;
14190           else
14191             F.erase();
14192         }
14193       }
14194       F.done();
14195
14196       // Diagnose this MSVC extension in the easy case where lookup would have
14197       // unambiguously found something outside the enclosing namespace.
14198       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14199         NamedDecl *ND = Previous.getFoundDecl();
14200         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14201             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14202       }
14203     }
14204
14205     // Note:  there used to be some attempt at recovery here.
14206     if (Previous.isAmbiguous())
14207       return nullptr;
14208
14209     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14210       // FIXME: This makes sure that we ignore the contexts associated
14211       // with C structs, unions, and enums when looking for a matching
14212       // tag declaration or definition. See the similar lookup tweak
14213       // in Sema::LookupName; is there a better way to deal with this?
14214       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14215         SearchDC = SearchDC->getParent();
14216     }
14217   }
14218
14219   if (Previous.isSingleResult() &&
14220       Previous.getFoundDecl()->isTemplateParameter()) {
14221     // Maybe we will complain about the shadowed template parameter.
14222     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14223     // Just pretend that we didn't see the previous declaration.
14224     Previous.clear();
14225   }
14226
14227   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14228       DC->Equals(getStdNamespace())) {
14229     if (Name->isStr("bad_alloc")) {
14230       // This is a declaration of or a reference to "std::bad_alloc".
14231       isStdBadAlloc = true;
14232
14233       // If std::bad_alloc has been implicitly declared (but made invisible to
14234       // name lookup), fill in this implicit declaration as the previous
14235       // declaration, so that the declarations get chained appropriately.
14236       if (Previous.empty() && StdBadAlloc)
14237         Previous.addDecl(getStdBadAlloc());
14238     } else if (Name->isStr("align_val_t")) {
14239       isStdAlignValT = true;
14240       if (Previous.empty() && StdAlignValT)
14241         Previous.addDecl(getStdAlignValT());
14242     }
14243   }
14244
14245   // If we didn't find a previous declaration, and this is a reference
14246   // (or friend reference), move to the correct scope.  In C++, we
14247   // also need to do a redeclaration lookup there, just in case
14248   // there's a shadow friend decl.
14249   if (Name && Previous.empty() &&
14250       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14251     if (Invalid) goto CreateNewDecl;
14252     assert(SS.isEmpty());
14253
14254     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14255       // C++ [basic.scope.pdecl]p5:
14256       //   -- for an elaborated-type-specifier of the form
14257       //
14258       //          class-key identifier
14259       //
14260       //      if the elaborated-type-specifier is used in the
14261       //      decl-specifier-seq or parameter-declaration-clause of a
14262       //      function defined in namespace scope, the identifier is
14263       //      declared as a class-name in the namespace that contains
14264       //      the declaration; otherwise, except as a friend
14265       //      declaration, the identifier is declared in the smallest
14266       //      non-class, non-function-prototype scope that contains the
14267       //      declaration.
14268       //
14269       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14270       // C structs and unions.
14271       //
14272       // It is an error in C++ to declare (rather than define) an enum
14273       // type, including via an elaborated type specifier.  We'll
14274       // diagnose that later; for now, declare the enum in the same
14275       // scope as we would have picked for any other tag type.
14276       //
14277       // GNU C also supports this behavior as part of its incomplete
14278       // enum types extension, while GNU C++ does not.
14279       //
14280       // Find the context where we'll be declaring the tag.
14281       // FIXME: We would like to maintain the current DeclContext as the
14282       // lexical context,
14283       SearchDC = getTagInjectionContext(SearchDC);
14284
14285       // Find the scope where we'll be declaring the tag.
14286       S = getTagInjectionScope(S, getLangOpts());
14287     } else {
14288       assert(TUK == TUK_Friend);
14289       // C++ [namespace.memdef]p3:
14290       //   If a friend declaration in a non-local class first declares a
14291       //   class or function, the friend class or function is a member of
14292       //   the innermost enclosing namespace.
14293       SearchDC = SearchDC->getEnclosingNamespaceContext();
14294     }
14295
14296     // In C++, we need to do a redeclaration lookup to properly
14297     // diagnose some problems.
14298     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14299     // hidden declaration so that we don't get ambiguity errors when using a
14300     // type declared by an elaborated-type-specifier.  In C that is not correct
14301     // and we should instead merge compatible types found by lookup.
14302     if (getLangOpts().CPlusPlus) {
14303       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14304       LookupQualifiedName(Previous, SearchDC);
14305     } else {
14306       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14307       LookupName(Previous, S);
14308     }
14309   }
14310
14311   // If we have a known previous declaration to use, then use it.
14312   if (Previous.empty() && SkipBody && SkipBody->Previous)
14313     Previous.addDecl(SkipBody->Previous);
14314
14315   if (!Previous.empty()) {
14316     NamedDecl *PrevDecl = Previous.getFoundDecl();
14317     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14318
14319     // It's okay to have a tag decl in the same scope as a typedef
14320     // which hides a tag decl in the same scope.  Finding this
14321     // insanity with a redeclaration lookup can only actually happen
14322     // in C++.
14323     //
14324     // This is also okay for elaborated-type-specifiers, which is
14325     // technically forbidden by the current standard but which is
14326     // okay according to the likely resolution of an open issue;
14327     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14328     if (getLangOpts().CPlusPlus) {
14329       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14330         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14331           TagDecl *Tag = TT->getDecl();
14332           if (Tag->getDeclName() == Name &&
14333               Tag->getDeclContext()->getRedeclContext()
14334                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14335             PrevDecl = Tag;
14336             Previous.clear();
14337             Previous.addDecl(Tag);
14338             Previous.resolveKind();
14339           }
14340         }
14341       }
14342     }
14343
14344     // If this is a redeclaration of a using shadow declaration, it must
14345     // declare a tag in the same context. In MSVC mode, we allow a
14346     // redefinition if either context is within the other.
14347     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14348       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14349       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14350           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14351           !(OldTag && isAcceptableTagRedeclContext(
14352                           *this, OldTag->getDeclContext(), SearchDC))) {
14353         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14354         Diag(Shadow->getTargetDecl()->getLocation(),
14355              diag::note_using_decl_target);
14356         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14357             << 0;
14358         // Recover by ignoring the old declaration.
14359         Previous.clear();
14360         goto CreateNewDecl;
14361       }
14362     }
14363
14364     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14365       // If this is a use of a previous tag, or if the tag is already declared
14366       // in the same scope (so that the definition/declaration completes or
14367       // rementions the tag), reuse the decl.
14368       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14369           isDeclInScope(DirectPrevDecl, SearchDC, S,
14370                         SS.isNotEmpty() || isMemberSpecialization)) {
14371         // Make sure that this wasn't declared as an enum and now used as a
14372         // struct or something similar.
14373         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14374                                           TUK == TUK_Definition, KWLoc,
14375                                           Name)) {
14376           bool SafeToContinue
14377             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14378                Kind != TTK_Enum);
14379           if (SafeToContinue)
14380             Diag(KWLoc, diag::err_use_with_wrong_tag)
14381               << Name
14382               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14383                                               PrevTagDecl->getKindName());
14384           else
14385             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14386           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14387
14388           if (SafeToContinue)
14389             Kind = PrevTagDecl->getTagKind();
14390           else {
14391             // Recover by making this an anonymous redefinition.
14392             Name = nullptr;
14393             Previous.clear();
14394             Invalid = true;
14395           }
14396         }
14397
14398         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14399           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14400
14401           // If this is an elaborated-type-specifier for a scoped enumeration,
14402           // the 'class' keyword is not necessary and not permitted.
14403           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14404             if (ScopedEnum)
14405               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14406                 << PrevEnum->isScoped()
14407                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14408             return PrevTagDecl;
14409           }
14410
14411           QualType EnumUnderlyingTy;
14412           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14413             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14414           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14415             EnumUnderlyingTy = QualType(T, 0);
14416
14417           // All conflicts with previous declarations are recovered by
14418           // returning the previous declaration, unless this is a definition,
14419           // in which case we want the caller to bail out.
14420           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14421                                      ScopedEnum, EnumUnderlyingTy,
14422                                      IsFixed, PrevEnum))
14423             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14424         }
14425
14426         // C++11 [class.mem]p1:
14427         //   A member shall not be declared twice in the member-specification,
14428         //   except that a nested class or member class template can be declared
14429         //   and then later defined.
14430         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14431             S->isDeclScope(PrevDecl)) {
14432           Diag(NameLoc, diag::ext_member_redeclared);
14433           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14434         }
14435
14436         if (!Invalid) {
14437           // If this is a use, just return the declaration we found, unless
14438           // we have attributes.
14439           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14440             if (!Attrs.empty()) {
14441               // FIXME: Diagnose these attributes. For now, we create a new
14442               // declaration to hold them.
14443             } else if (TUK == TUK_Reference &&
14444                        (PrevTagDecl->getFriendObjectKind() ==
14445                             Decl::FOK_Undeclared ||
14446                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14447                        SS.isEmpty()) {
14448               // This declaration is a reference to an existing entity, but
14449               // has different visibility from that entity: it either makes
14450               // a friend visible or it makes a type visible in a new module.
14451               // In either case, create a new declaration. We only do this if
14452               // the declaration would have meant the same thing if no prior
14453               // declaration were found, that is, if it was found in the same
14454               // scope where we would have injected a declaration.
14455               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14456                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14457                 return PrevTagDecl;
14458               // This is in the injected scope, create a new declaration in
14459               // that scope.
14460               S = getTagInjectionScope(S, getLangOpts());
14461             } else {
14462               return PrevTagDecl;
14463             }
14464           }
14465
14466           // Diagnose attempts to redefine a tag.
14467           if (TUK == TUK_Definition) {
14468             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14469               // If we're defining a specialization and the previous definition
14470               // is from an implicit instantiation, don't emit an error
14471               // here; we'll catch this in the general case below.
14472               bool IsExplicitSpecializationAfterInstantiation = false;
14473               if (isMemberSpecialization) {
14474                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14475                   IsExplicitSpecializationAfterInstantiation =
14476                     RD->getTemplateSpecializationKind() !=
14477                     TSK_ExplicitSpecialization;
14478                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14479                   IsExplicitSpecializationAfterInstantiation =
14480                     ED->getTemplateSpecializationKind() !=
14481                     TSK_ExplicitSpecialization;
14482               }
14483
14484               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14485               // not keep more that one definition around (merge them). However,
14486               // ensure the decl passes the structural compatibility check in
14487               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14488               NamedDecl *Hidden = nullptr;
14489               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14490                 // There is a definition of this tag, but it is not visible. We
14491                 // explicitly make use of C++'s one definition rule here, and
14492                 // assume that this definition is identical to the hidden one
14493                 // we already have. Make the existing definition visible and
14494                 // use it in place of this one.
14495                 if (!getLangOpts().CPlusPlus) {
14496                   // Postpone making the old definition visible until after we
14497                   // complete parsing the new one and do the structural
14498                   // comparison.
14499                   SkipBody->CheckSameAsPrevious = true;
14500                   SkipBody->New = createTagFromNewDecl();
14501                   SkipBody->Previous = Hidden;
14502                 } else {
14503                   SkipBody->ShouldSkip = true;
14504                   makeMergedDefinitionVisible(Hidden);
14505                 }
14506                 return Def;
14507               } else if (!IsExplicitSpecializationAfterInstantiation) {
14508                 // A redeclaration in function prototype scope in C isn't
14509                 // visible elsewhere, so merely issue a warning.
14510                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14511                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14512                 else
14513                   Diag(NameLoc, diag::err_redefinition) << Name;
14514                 notePreviousDefinition(Def,
14515                                        NameLoc.isValid() ? NameLoc : KWLoc);
14516                 // If this is a redefinition, recover by making this
14517                 // struct be anonymous, which will make any later
14518                 // references get the previous definition.
14519                 Name = nullptr;
14520                 Previous.clear();
14521                 Invalid = true;
14522               }
14523             } else {
14524               // If the type is currently being defined, complain
14525               // about a nested redefinition.
14526               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14527               if (TD->isBeingDefined()) {
14528                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14529                 Diag(PrevTagDecl->getLocation(),
14530                      diag::note_previous_definition);
14531                 Name = nullptr;
14532                 Previous.clear();
14533                 Invalid = true;
14534               }
14535             }
14536
14537             // Okay, this is definition of a previously declared or referenced
14538             // tag. We're going to create a new Decl for it.
14539           }
14540
14541           // Okay, we're going to make a redeclaration.  If this is some kind
14542           // of reference, make sure we build the redeclaration in the same DC
14543           // as the original, and ignore the current access specifier.
14544           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14545             SearchDC = PrevTagDecl->getDeclContext();
14546             AS = AS_none;
14547           }
14548         }
14549         // If we get here we have (another) forward declaration or we
14550         // have a definition.  Just create a new decl.
14551
14552       } else {
14553         // If we get here, this is a definition of a new tag type in a nested
14554         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14555         // new decl/type.  We set PrevDecl to NULL so that the entities
14556         // have distinct types.
14557         Previous.clear();
14558       }
14559       // If we get here, we're going to create a new Decl. If PrevDecl
14560       // is non-NULL, it's a definition of the tag declared by
14561       // PrevDecl. If it's NULL, we have a new definition.
14562
14563     // Otherwise, PrevDecl is not a tag, but was found with tag
14564     // lookup.  This is only actually possible in C++, where a few
14565     // things like templates still live in the tag namespace.
14566     } else {
14567       // Use a better diagnostic if an elaborated-type-specifier
14568       // found the wrong kind of type on the first
14569       // (non-redeclaration) lookup.
14570       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14571           !Previous.isForRedeclaration()) {
14572         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14573         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14574                                                        << Kind;
14575         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14576         Invalid = true;
14577
14578       // Otherwise, only diagnose if the declaration is in scope.
14579       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14580                                 SS.isNotEmpty() || isMemberSpecialization)) {
14581         // do nothing
14582
14583       // Diagnose implicit declarations introduced by elaborated types.
14584       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14585         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14586         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14587         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14588         Invalid = true;
14589
14590       // Otherwise it's a declaration.  Call out a particularly common
14591       // case here.
14592       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14593         unsigned Kind = 0;
14594         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14595         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14596           << Name << Kind << TND->getUnderlyingType();
14597         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14598         Invalid = true;
14599
14600       // Otherwise, diagnose.
14601       } else {
14602         // The tag name clashes with something else in the target scope,
14603         // issue an error and recover by making this tag be anonymous.
14604         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14605         notePreviousDefinition(PrevDecl, NameLoc);
14606         Name = nullptr;
14607         Invalid = true;
14608       }
14609
14610       // The existing declaration isn't relevant to us; we're in a
14611       // new scope, so clear out the previous declaration.
14612       Previous.clear();
14613     }
14614   }
14615
14616 CreateNewDecl:
14617
14618   TagDecl *PrevDecl = nullptr;
14619   if (Previous.isSingleResult())
14620     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14621
14622   // If there is an identifier, use the location of the identifier as the
14623   // location of the decl, otherwise use the location of the struct/union
14624   // keyword.
14625   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14626
14627   // Otherwise, create a new declaration. If there is a previous
14628   // declaration of the same entity, the two will be linked via
14629   // PrevDecl.
14630   TagDecl *New;
14631
14632   if (Kind == TTK_Enum) {
14633     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14634     // enum X { A, B, C } D;    D should chain to X.
14635     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14636                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14637                            ScopedEnumUsesClassTag, IsFixed);
14638
14639     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14640       StdAlignValT = cast<EnumDecl>(New);
14641
14642     // If this is an undefined enum, warn.
14643     if (TUK != TUK_Definition && !Invalid) {
14644       TagDecl *Def;
14645       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14646           cast<EnumDecl>(New)->isFixed()) {
14647         // C++0x: 7.2p2: opaque-enum-declaration.
14648         // Conflicts are diagnosed above. Do nothing.
14649       }
14650       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14651         Diag(Loc, diag::ext_forward_ref_enum_def)
14652           << New;
14653         Diag(Def->getLocation(), diag::note_previous_definition);
14654       } else {
14655         unsigned DiagID = diag::ext_forward_ref_enum;
14656         if (getLangOpts().MSVCCompat)
14657           DiagID = diag::ext_ms_forward_ref_enum;
14658         else if (getLangOpts().CPlusPlus)
14659           DiagID = diag::err_forward_ref_enum;
14660         Diag(Loc, DiagID);
14661       }
14662     }
14663
14664     if (EnumUnderlying) {
14665       EnumDecl *ED = cast<EnumDecl>(New);
14666       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14667         ED->setIntegerTypeSourceInfo(TI);
14668       else
14669         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14670       ED->setPromotionType(ED->getIntegerType());
14671       assert(ED->isComplete() && "enum with type should be complete");
14672     }
14673   } else {
14674     // struct/union/class
14675
14676     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14677     // struct X { int A; } D;    D should chain to X.
14678     if (getLangOpts().CPlusPlus) {
14679       // FIXME: Look for a way to use RecordDecl for simple structs.
14680       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14681                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14682
14683       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14684         StdBadAlloc = cast<CXXRecordDecl>(New);
14685     } else
14686       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14687                                cast_or_null<RecordDecl>(PrevDecl));
14688   }
14689
14690   // C++11 [dcl.type]p3:
14691   //   A type-specifier-seq shall not define a class or enumeration [...].
14692   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14693       TUK == TUK_Definition) {
14694     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14695       << Context.getTagDeclType(New);
14696     Invalid = true;
14697   }
14698
14699   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14700       DC->getDeclKind() == Decl::Enum) {
14701     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14702       << Context.getTagDeclType(New);
14703     Invalid = true;
14704   }
14705
14706   // Maybe add qualifier info.
14707   if (SS.isNotEmpty()) {
14708     if (SS.isSet()) {
14709       // If this is either a declaration or a definition, check the
14710       // nested-name-specifier against the current context.
14711       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14712           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14713                                        isMemberSpecialization))
14714         Invalid = true;
14715
14716       New->setQualifierInfo(SS.getWithLocInContext(Context));
14717       if (TemplateParameterLists.size() > 0) {
14718         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14719       }
14720     }
14721     else
14722       Invalid = true;
14723   }
14724
14725   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14726     // Add alignment attributes if necessary; these attributes are checked when
14727     // the ASTContext lays out the structure.
14728     //
14729     // It is important for implementing the correct semantics that this
14730     // happen here (in ActOnTag). The #pragma pack stack is
14731     // maintained as a result of parser callbacks which can occur at
14732     // many points during the parsing of a struct declaration (because
14733     // the #pragma tokens are effectively skipped over during the
14734     // parsing of the struct).
14735     if (TUK == TUK_Definition) {
14736       AddAlignmentAttributesForRecord(RD);
14737       AddMsStructLayoutForRecord(RD);
14738     }
14739   }
14740
14741   if (ModulePrivateLoc.isValid()) {
14742     if (isMemberSpecialization)
14743       Diag(New->getLocation(), diag::err_module_private_specialization)
14744         << 2
14745         << FixItHint::CreateRemoval(ModulePrivateLoc);
14746     // __module_private__ does not apply to local classes. However, we only
14747     // diagnose this as an error when the declaration specifiers are
14748     // freestanding. Here, we just ignore the __module_private__.
14749     else if (!SearchDC->isFunctionOrMethod())
14750       New->setModulePrivate();
14751   }
14752
14753   // If this is a specialization of a member class (of a class template),
14754   // check the specialization.
14755   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14756     Invalid = true;
14757
14758   // If we're declaring or defining a tag in function prototype scope in C,
14759   // note that this type can only be used within the function and add it to
14760   // the list of decls to inject into the function definition scope.
14761   if ((Name || Kind == TTK_Enum) &&
14762       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14763     if (getLangOpts().CPlusPlus) {
14764       // C++ [dcl.fct]p6:
14765       //   Types shall not be defined in return or parameter types.
14766       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14767         Diag(Loc, diag::err_type_defined_in_param_type)
14768             << Name;
14769         Invalid = true;
14770       }
14771     } else if (!PrevDecl) {
14772       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14773     }
14774   }
14775
14776   if (Invalid)
14777     New->setInvalidDecl();
14778
14779   // Set the lexical context. If the tag has a C++ scope specifier, the
14780   // lexical context will be different from the semantic context.
14781   New->setLexicalDeclContext(CurContext);
14782
14783   // Mark this as a friend decl if applicable.
14784   // In Microsoft mode, a friend declaration also acts as a forward
14785   // declaration so we always pass true to setObjectOfFriendDecl to make
14786   // the tag name visible.
14787   if (TUK == TUK_Friend)
14788     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14789
14790   // Set the access specifier.
14791   if (!Invalid && SearchDC->isRecord())
14792     SetMemberAccessSpecifier(New, PrevDecl, AS);
14793
14794   if (PrevDecl)
14795     CheckRedeclarationModuleOwnership(New, PrevDecl);
14796
14797   if (TUK == TUK_Definition)
14798     New->startDefinition();
14799
14800   ProcessDeclAttributeList(S, New, Attrs);
14801   AddPragmaAttributes(S, New);
14802
14803   // If this has an identifier, add it to the scope stack.
14804   if (TUK == TUK_Friend) {
14805     // We might be replacing an existing declaration in the lookup tables;
14806     // if so, borrow its access specifier.
14807     if (PrevDecl)
14808       New->setAccess(PrevDecl->getAccess());
14809
14810     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14811     DC->makeDeclVisibleInContext(New);
14812     if (Name) // can be null along some error paths
14813       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14814         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14815   } else if (Name) {
14816     S = getNonFieldDeclScope(S);
14817     PushOnScopeChains(New, S, true);
14818   } else {
14819     CurContext->addDecl(New);
14820   }
14821
14822   // If this is the C FILE type, notify the AST context.
14823   if (IdentifierInfo *II = New->getIdentifier())
14824     if (!New->isInvalidDecl() &&
14825         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14826         II->isStr("FILE"))
14827       Context.setFILEDecl(New);
14828
14829   if (PrevDecl)
14830     mergeDeclAttributes(New, PrevDecl);
14831
14832   // If there's a #pragma GCC visibility in scope, set the visibility of this
14833   // record.
14834   AddPushedVisibilityAttribute(New);
14835
14836   if (isMemberSpecialization && !New->isInvalidDecl())
14837     CompleteMemberSpecialization(New, Previous);
14838
14839   OwnedDecl = true;
14840   // In C++, don't return an invalid declaration. We can't recover well from
14841   // the cases where we make the type anonymous.
14842   if (Invalid && getLangOpts().CPlusPlus) {
14843     if (New->isBeingDefined())
14844       if (auto RD = dyn_cast<RecordDecl>(New))
14845         RD->completeDefinition();
14846     return nullptr;
14847   } else {
14848     return New;
14849   }
14850 }
14851
14852 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14853   AdjustDeclIfTemplate(TagD);
14854   TagDecl *Tag = cast<TagDecl>(TagD);
14855
14856   // Enter the tag context.
14857   PushDeclContext(S, Tag);
14858
14859   ActOnDocumentableDecl(TagD);
14860
14861   // If there's a #pragma GCC visibility in scope, set the visibility of this
14862   // record.
14863   AddPushedVisibilityAttribute(Tag);
14864 }
14865
14866 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14867                                     SkipBodyInfo &SkipBody) {
14868   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14869     return false;
14870
14871   // Make the previous decl visible.
14872   makeMergedDefinitionVisible(SkipBody.Previous);
14873   return true;
14874 }
14875
14876 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14877   assert(isa<ObjCContainerDecl>(IDecl) &&
14878          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14879   DeclContext *OCD = cast<DeclContext>(IDecl);
14880   assert(getContainingDC(OCD) == CurContext &&
14881       "The next DeclContext should be lexically contained in the current one.");
14882   CurContext = OCD;
14883   return IDecl;
14884 }
14885
14886 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14887                                            SourceLocation FinalLoc,
14888                                            bool IsFinalSpelledSealed,
14889                                            SourceLocation LBraceLoc) {
14890   AdjustDeclIfTemplate(TagD);
14891   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14892
14893   FieldCollector->StartClass();
14894
14895   if (!Record->getIdentifier())
14896     return;
14897
14898   if (FinalLoc.isValid())
14899     Record->addAttr(new (Context)
14900                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14901
14902   // C++ [class]p2:
14903   //   [...] The class-name is also inserted into the scope of the
14904   //   class itself; this is known as the injected-class-name. For
14905   //   purposes of access checking, the injected-class-name is treated
14906   //   as if it were a public member name.
14907   CXXRecordDecl *InjectedClassName
14908     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14909                             Record->getLocStart(), Record->getLocation(),
14910                             Record->getIdentifier(),
14911                             /*PrevDecl=*/nullptr,
14912                             /*DelayTypeCreation=*/true);
14913   Context.getTypeDeclType(InjectedClassName, Record);
14914   InjectedClassName->setImplicit();
14915   InjectedClassName->setAccess(AS_public);
14916   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14917       InjectedClassName->setDescribedClassTemplate(Template);
14918   PushOnScopeChains(InjectedClassName, S);
14919   assert(InjectedClassName->isInjectedClassName() &&
14920          "Broken injected-class-name");
14921 }
14922
14923 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14924                                     SourceRange BraceRange) {
14925   AdjustDeclIfTemplate(TagD);
14926   TagDecl *Tag = cast<TagDecl>(TagD);
14927   Tag->setBraceRange(BraceRange);
14928
14929   // Make sure we "complete" the definition even it is invalid.
14930   if (Tag->isBeingDefined()) {
14931     assert(Tag->isInvalidDecl() && "We should already have completed it");
14932     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14933       RD->completeDefinition();
14934   }
14935
14936   if (isa<CXXRecordDecl>(Tag)) {
14937     FieldCollector->FinishClass();
14938   }
14939
14940   // Exit this scope of this tag's definition.
14941   PopDeclContext();
14942
14943   if (getCurLexicalContext()->isObjCContainer() &&
14944       Tag->getDeclContext()->isFileContext())
14945     Tag->setTopLevelDeclInObjCContainer();
14946
14947   // Notify the consumer that we've defined a tag.
14948   if (!Tag->isInvalidDecl())
14949     Consumer.HandleTagDeclDefinition(Tag);
14950 }
14951
14952 void Sema::ActOnObjCContainerFinishDefinition() {
14953   // Exit this scope of this interface definition.
14954   PopDeclContext();
14955 }
14956
14957 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14958   assert(DC == CurContext && "Mismatch of container contexts");
14959   OriginalLexicalContext = DC;
14960   ActOnObjCContainerFinishDefinition();
14961 }
14962
14963 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14964   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14965   OriginalLexicalContext = nullptr;
14966 }
14967
14968 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14969   AdjustDeclIfTemplate(TagD);
14970   TagDecl *Tag = cast<TagDecl>(TagD);
14971   Tag->setInvalidDecl();
14972
14973   // Make sure we "complete" the definition even it is invalid.
14974   if (Tag->isBeingDefined()) {
14975     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14976       RD->completeDefinition();
14977   }
14978
14979   // We're undoing ActOnTagStartDefinition here, not
14980   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14981   // the FieldCollector.
14982
14983   PopDeclContext();
14984 }
14985
14986 // Note that FieldName may be null for anonymous bitfields.
14987 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14988                                 IdentifierInfo *FieldName,
14989                                 QualType FieldTy, bool IsMsStruct,
14990                                 Expr *BitWidth, bool *ZeroWidth) {
14991   // Default to true; that shouldn't confuse checks for emptiness
14992   if (ZeroWidth)
14993     *ZeroWidth = true;
14994
14995   // C99 6.7.2.1p4 - verify the field type.
14996   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14997   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14998     // Handle incomplete types with specific error.
14999     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15000       return ExprError();
15001     if (FieldName)
15002       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15003         << FieldName << FieldTy << BitWidth->getSourceRange();
15004     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15005       << FieldTy << BitWidth->getSourceRange();
15006   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15007                                              UPPC_BitFieldWidth))
15008     return ExprError();
15009
15010   // If the bit-width is type- or value-dependent, don't try to check
15011   // it now.
15012   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15013     return BitWidth;
15014
15015   llvm::APSInt Value;
15016   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15017   if (ICE.isInvalid())
15018     return ICE;
15019   BitWidth = ICE.get();
15020
15021   if (Value != 0 && ZeroWidth)
15022     *ZeroWidth = false;
15023
15024   // Zero-width bitfield is ok for anonymous field.
15025   if (Value == 0 && FieldName)
15026     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15027
15028   if (Value.isSigned() && Value.isNegative()) {
15029     if (FieldName)
15030       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15031                << FieldName << Value.toString(10);
15032     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15033       << Value.toString(10);
15034   }
15035
15036   if (!FieldTy->isDependentType()) {
15037     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15038     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15039     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15040
15041     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15042     // ABI.
15043     bool CStdConstraintViolation =
15044         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15045     bool MSBitfieldViolation =
15046         Value.ugt(TypeStorageSize) &&
15047         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15048     if (CStdConstraintViolation || MSBitfieldViolation) {
15049       unsigned DiagWidth =
15050           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15051       if (FieldName)
15052         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15053                << FieldName << (unsigned)Value.getZExtValue()
15054                << !CStdConstraintViolation << DiagWidth;
15055
15056       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15057              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15058              << DiagWidth;
15059     }
15060
15061     // Warn on types where the user might conceivably expect to get all
15062     // specified bits as value bits: that's all integral types other than
15063     // 'bool'.
15064     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15065       if (FieldName)
15066         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15067             << FieldName << (unsigned)Value.getZExtValue()
15068             << (unsigned)TypeWidth;
15069       else
15070         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15071             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15072     }
15073   }
15074
15075   return BitWidth;
15076 }
15077
15078 /// ActOnField - Each field of a C struct/union is passed into this in order
15079 /// to create a FieldDecl object for it.
15080 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15081                        Declarator &D, Expr *BitfieldWidth) {
15082   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15083                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15084                                /*InitStyle=*/ICIS_NoInit, AS_public);
15085   return Res;
15086 }
15087
15088 /// HandleField - Analyze a field of a C struct or a C++ data member.
15089 ///
15090 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15091                              SourceLocation DeclStart,
15092                              Declarator &D, Expr *BitWidth,
15093                              InClassInitStyle InitStyle,
15094                              AccessSpecifier AS) {
15095   if (D.isDecompositionDeclarator()) {
15096     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15097     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15098       << Decomp.getSourceRange();
15099     return nullptr;
15100   }
15101
15102   IdentifierInfo *II = D.getIdentifier();
15103   SourceLocation Loc = DeclStart;
15104   if (II) Loc = D.getIdentifierLoc();
15105
15106   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15107   QualType T = TInfo->getType();
15108   if (getLangOpts().CPlusPlus) {
15109     CheckExtraCXXDefaultArguments(D);
15110
15111     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15112                                         UPPC_DataMemberType)) {
15113       D.setInvalidType();
15114       T = Context.IntTy;
15115       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15116     }
15117   }
15118
15119   // TR 18037 does not allow fields to be declared with address spaces.
15120   if (T.getQualifiers().hasAddressSpace() ||
15121       T->isDependentAddressSpaceType() ||
15122       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15123     Diag(Loc, diag::err_field_with_address_space);
15124     D.setInvalidType();
15125   }
15126
15127   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15128   // used as structure or union field: image, sampler, event or block types.
15129   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
15130                           T->isSamplerT() || T->isBlockPointerType())) {
15131     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15132     D.setInvalidType();
15133   }
15134
15135   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15136
15137   if (D.getDeclSpec().isInlineSpecified())
15138     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15139         << getLangOpts().CPlusPlus17;
15140   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15141     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15142          diag::err_invalid_thread)
15143       << DeclSpec::getSpecifierName(TSCS);
15144
15145   // Check to see if this name was declared as a member previously
15146   NamedDecl *PrevDecl = nullptr;
15147   LookupResult Previous(*this, II, Loc, LookupMemberName,
15148                         ForVisibleRedeclaration);
15149   LookupName(Previous, S);
15150   switch (Previous.getResultKind()) {
15151     case LookupResult::Found:
15152     case LookupResult::FoundUnresolvedValue:
15153       PrevDecl = Previous.getAsSingle<NamedDecl>();
15154       break;
15155
15156     case LookupResult::FoundOverloaded:
15157       PrevDecl = Previous.getRepresentativeDecl();
15158       break;
15159
15160     case LookupResult::NotFound:
15161     case LookupResult::NotFoundInCurrentInstantiation:
15162     case LookupResult::Ambiguous:
15163       break;
15164   }
15165   Previous.suppressDiagnostics();
15166
15167   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15168     // Maybe we will complain about the shadowed template parameter.
15169     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15170     // Just pretend that we didn't see the previous declaration.
15171     PrevDecl = nullptr;
15172   }
15173
15174   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15175     PrevDecl = nullptr;
15176
15177   bool Mutable
15178     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15179   SourceLocation TSSL = D.getLocStart();
15180   FieldDecl *NewFD
15181     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15182                      TSSL, AS, PrevDecl, &D);
15183
15184   if (NewFD->isInvalidDecl())
15185     Record->setInvalidDecl();
15186
15187   if (D.getDeclSpec().isModulePrivateSpecified())
15188     NewFD->setModulePrivate();
15189
15190   if (NewFD->isInvalidDecl() && PrevDecl) {
15191     // Don't introduce NewFD into scope; there's already something
15192     // with the same name in the same scope.
15193   } else if (II) {
15194     PushOnScopeChains(NewFD, S);
15195   } else
15196     Record->addDecl(NewFD);
15197
15198   return NewFD;
15199 }
15200
15201 /// Build a new FieldDecl and check its well-formedness.
15202 ///
15203 /// This routine builds a new FieldDecl given the fields name, type,
15204 /// record, etc. \p PrevDecl should refer to any previous declaration
15205 /// with the same name and in the same scope as the field to be
15206 /// created.
15207 ///
15208 /// \returns a new FieldDecl.
15209 ///
15210 /// \todo The Declarator argument is a hack. It will be removed once
15211 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15212                                 TypeSourceInfo *TInfo,
15213                                 RecordDecl *Record, SourceLocation Loc,
15214                                 bool Mutable, Expr *BitWidth,
15215                                 InClassInitStyle InitStyle,
15216                                 SourceLocation TSSL,
15217                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15218                                 Declarator *D) {
15219   IdentifierInfo *II = Name.getAsIdentifierInfo();
15220   bool InvalidDecl = false;
15221   if (D) InvalidDecl = D->isInvalidType();
15222
15223   // If we receive a broken type, recover by assuming 'int' and
15224   // marking this declaration as invalid.
15225   if (T.isNull()) {
15226     InvalidDecl = true;
15227     T = Context.IntTy;
15228   }
15229
15230   QualType EltTy = Context.getBaseElementType(T);
15231   if (!EltTy->isDependentType()) {
15232     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15233       // Fields of incomplete type force their record to be invalid.
15234       Record->setInvalidDecl();
15235       InvalidDecl = true;
15236     } else {
15237       NamedDecl *Def;
15238       EltTy->isIncompleteType(&Def);
15239       if (Def && Def->isInvalidDecl()) {
15240         Record->setInvalidDecl();
15241         InvalidDecl = true;
15242       }
15243     }
15244   }
15245
15246   // OpenCL v1.2 s6.9.c: bitfields are not supported.
15247   if (BitWidth && getLangOpts().OpenCL) {
15248     Diag(Loc, diag::err_opencl_bitfields);
15249     InvalidDecl = true;
15250   }
15251
15252   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15253   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15254       T.hasQualifiers()) {
15255     InvalidDecl = true;
15256     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15257   }
15258
15259   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15260   // than a variably modified type.
15261   if (!InvalidDecl && T->isVariablyModifiedType()) {
15262     bool SizeIsNegative;
15263     llvm::APSInt Oversized;
15264
15265     TypeSourceInfo *FixedTInfo =
15266       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15267                                                     SizeIsNegative,
15268                                                     Oversized);
15269     if (FixedTInfo) {
15270       Diag(Loc, diag::warn_illegal_constant_array_size);
15271       TInfo = FixedTInfo;
15272       T = FixedTInfo->getType();
15273     } else {
15274       if (SizeIsNegative)
15275         Diag(Loc, diag::err_typecheck_negative_array_size);
15276       else if (Oversized.getBoolValue())
15277         Diag(Loc, diag::err_array_too_large)
15278           << Oversized.toString(10);
15279       else
15280         Diag(Loc, diag::err_typecheck_field_variable_size);
15281       InvalidDecl = true;
15282     }
15283   }
15284
15285   // Fields can not have abstract class types
15286   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15287                                              diag::err_abstract_type_in_decl,
15288                                              AbstractFieldType))
15289     InvalidDecl = true;
15290
15291   bool ZeroWidth = false;
15292   if (InvalidDecl)
15293     BitWidth = nullptr;
15294   // If this is declared as a bit-field, check the bit-field.
15295   if (BitWidth) {
15296     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15297                               &ZeroWidth).get();
15298     if (!BitWidth) {
15299       InvalidDecl = true;
15300       BitWidth = nullptr;
15301       ZeroWidth = false;
15302     }
15303   }
15304
15305   // Check that 'mutable' is consistent with the type of the declaration.
15306   if (!InvalidDecl && Mutable) {
15307     unsigned DiagID = 0;
15308     if (T->isReferenceType())
15309       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15310                                         : diag::err_mutable_reference;
15311     else if (T.isConstQualified())
15312       DiagID = diag::err_mutable_const;
15313
15314     if (DiagID) {
15315       SourceLocation ErrLoc = Loc;
15316       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15317         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15318       Diag(ErrLoc, DiagID);
15319       if (DiagID != diag::ext_mutable_reference) {
15320         Mutable = false;
15321         InvalidDecl = true;
15322       }
15323     }
15324   }
15325
15326   // C++11 [class.union]p8 (DR1460):
15327   //   At most one variant member of a union may have a
15328   //   brace-or-equal-initializer.
15329   if (InitStyle != ICIS_NoInit)
15330     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15331
15332   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15333                                        BitWidth, Mutable, InitStyle);
15334   if (InvalidDecl)
15335     NewFD->setInvalidDecl();
15336
15337   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15338     Diag(Loc, diag::err_duplicate_member) << II;
15339     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15340     NewFD->setInvalidDecl();
15341   }
15342
15343   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15344     if (Record->isUnion()) {
15345       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15346         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15347         if (RDecl->getDefinition()) {
15348           // C++ [class.union]p1: An object of a class with a non-trivial
15349           // constructor, a non-trivial copy constructor, a non-trivial
15350           // destructor, or a non-trivial copy assignment operator
15351           // cannot be a member of a union, nor can an array of such
15352           // objects.
15353           if (CheckNontrivialField(NewFD))
15354             NewFD->setInvalidDecl();
15355         }
15356       }
15357
15358       // C++ [class.union]p1: If a union contains a member of reference type,
15359       // the program is ill-formed, except when compiling with MSVC extensions
15360       // enabled.
15361       if (EltTy->isReferenceType()) {
15362         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15363                                     diag::ext_union_member_of_reference_type :
15364                                     diag::err_union_member_of_reference_type)
15365           << NewFD->getDeclName() << EltTy;
15366         if (!getLangOpts().MicrosoftExt)
15367           NewFD->setInvalidDecl();
15368       }
15369     }
15370   }
15371
15372   // FIXME: We need to pass in the attributes given an AST
15373   // representation, not a parser representation.
15374   if (D) {
15375     // FIXME: The current scope is almost... but not entirely... correct here.
15376     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15377
15378     if (NewFD->hasAttrs())
15379       CheckAlignasUnderalignment(NewFD);
15380   }
15381
15382   // In auto-retain/release, infer strong retension for fields of
15383   // retainable type.
15384   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15385     NewFD->setInvalidDecl();
15386
15387   if (T.isObjCGCWeak())
15388     Diag(Loc, diag::warn_attribute_weak_on_field);
15389
15390   NewFD->setAccess(AS);
15391   return NewFD;
15392 }
15393
15394 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15395   assert(FD);
15396   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15397
15398   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15399     return false;
15400
15401   QualType EltTy = Context.getBaseElementType(FD->getType());
15402   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15403     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15404     if (RDecl->getDefinition()) {
15405       // We check for copy constructors before constructors
15406       // because otherwise we'll never get complaints about
15407       // copy constructors.
15408
15409       CXXSpecialMember member = CXXInvalid;
15410       // We're required to check for any non-trivial constructors. Since the
15411       // implicit default constructor is suppressed if there are any
15412       // user-declared constructors, we just need to check that there is a
15413       // trivial default constructor and a trivial copy constructor. (We don't
15414       // worry about move constructors here, since this is a C++98 check.)
15415       if (RDecl->hasNonTrivialCopyConstructor())
15416         member = CXXCopyConstructor;
15417       else if (!RDecl->hasTrivialDefaultConstructor())
15418         member = CXXDefaultConstructor;
15419       else if (RDecl->hasNonTrivialCopyAssignment())
15420         member = CXXCopyAssignment;
15421       else if (RDecl->hasNonTrivialDestructor())
15422         member = CXXDestructor;
15423
15424       if (member != CXXInvalid) {
15425         if (!getLangOpts().CPlusPlus11 &&
15426             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15427           // Objective-C++ ARC: it is an error to have a non-trivial field of
15428           // a union. However, system headers in Objective-C programs
15429           // occasionally have Objective-C lifetime objects within unions,
15430           // and rather than cause the program to fail, we make those
15431           // members unavailable.
15432           SourceLocation Loc = FD->getLocation();
15433           if (getSourceManager().isInSystemHeader(Loc)) {
15434             if (!FD->hasAttr<UnavailableAttr>())
15435               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15436                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15437             return false;
15438           }
15439         }
15440
15441         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15442                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15443                diag::err_illegal_union_or_anon_struct_member)
15444           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15445         DiagnoseNontrivial(RDecl, member);
15446         return !getLangOpts().CPlusPlus11;
15447       }
15448     }
15449   }
15450
15451   return false;
15452 }
15453
15454 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15455 ///  AST enum value.
15456 static ObjCIvarDecl::AccessControl
15457 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15458   switch (ivarVisibility) {
15459   default: llvm_unreachable("Unknown visitibility kind");
15460   case tok::objc_private: return ObjCIvarDecl::Private;
15461   case tok::objc_public: return ObjCIvarDecl::Public;
15462   case tok::objc_protected: return ObjCIvarDecl::Protected;
15463   case tok::objc_package: return ObjCIvarDecl::Package;
15464   }
15465 }
15466
15467 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15468 /// in order to create an IvarDecl object for it.
15469 Decl *Sema::ActOnIvar(Scope *S,
15470                                 SourceLocation DeclStart,
15471                                 Declarator &D, Expr *BitfieldWidth,
15472                                 tok::ObjCKeywordKind Visibility) {
15473
15474   IdentifierInfo *II = D.getIdentifier();
15475   Expr *BitWidth = (Expr*)BitfieldWidth;
15476   SourceLocation Loc = DeclStart;
15477   if (II) Loc = D.getIdentifierLoc();
15478
15479   // FIXME: Unnamed fields can be handled in various different ways, for
15480   // example, unnamed unions inject all members into the struct namespace!
15481
15482   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15483   QualType T = TInfo->getType();
15484
15485   if (BitWidth) {
15486     // 6.7.2.1p3, 6.7.2.1p4
15487     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15488     if (!BitWidth)
15489       D.setInvalidType();
15490   } else {
15491     // Not a bitfield.
15492
15493     // validate II.
15494
15495   }
15496   if (T->isReferenceType()) {
15497     Diag(Loc, diag::err_ivar_reference_type);
15498     D.setInvalidType();
15499   }
15500   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15501   // than a variably modified type.
15502   else if (T->isVariablyModifiedType()) {
15503     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15504     D.setInvalidType();
15505   }
15506
15507   // Get the visibility (access control) for this ivar.
15508   ObjCIvarDecl::AccessControl ac =
15509     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15510                                         : ObjCIvarDecl::None;
15511   // Must set ivar's DeclContext to its enclosing interface.
15512   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15513   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15514     return nullptr;
15515   ObjCContainerDecl *EnclosingContext;
15516   if (ObjCImplementationDecl *IMPDecl =
15517       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15518     if (LangOpts.ObjCRuntime.isFragile()) {
15519     // Case of ivar declared in an implementation. Context is that of its class.
15520       EnclosingContext = IMPDecl->getClassInterface();
15521       assert(EnclosingContext && "Implementation has no class interface!");
15522     }
15523     else
15524       EnclosingContext = EnclosingDecl;
15525   } else {
15526     if (ObjCCategoryDecl *CDecl =
15527         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15528       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15529         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15530         return nullptr;
15531       }
15532     }
15533     EnclosingContext = EnclosingDecl;
15534   }
15535
15536   // Construct the decl.
15537   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15538                                              DeclStart, Loc, II, T,
15539                                              TInfo, ac, (Expr *)BitfieldWidth);
15540
15541   if (II) {
15542     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15543                                            ForVisibleRedeclaration);
15544     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15545         && !isa<TagDecl>(PrevDecl)) {
15546       Diag(Loc, diag::err_duplicate_member) << II;
15547       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15548       NewID->setInvalidDecl();
15549     }
15550   }
15551
15552   // Process attributes attached to the ivar.
15553   ProcessDeclAttributes(S, NewID, D);
15554
15555   if (D.isInvalidType())
15556     NewID->setInvalidDecl();
15557
15558   // In ARC, infer 'retaining' for ivars of retainable type.
15559   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15560     NewID->setInvalidDecl();
15561
15562   if (D.getDeclSpec().isModulePrivateSpecified())
15563     NewID->setModulePrivate();
15564
15565   if (II) {
15566     // FIXME: When interfaces are DeclContexts, we'll need to add
15567     // these to the interface.
15568     S->AddDecl(NewID);
15569     IdResolver.AddDecl(NewID);
15570   }
15571
15572   if (LangOpts.ObjCRuntime.isNonFragile() &&
15573       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15574     Diag(Loc, diag::warn_ivars_in_interface);
15575
15576   return NewID;
15577 }
15578
15579 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15580 /// class and class extensions. For every class \@interface and class
15581 /// extension \@interface, if the last ivar is a bitfield of any type,
15582 /// then add an implicit `char :0` ivar to the end of that interface.
15583 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15584                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15585   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15586     return;
15587
15588   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15589   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15590
15591   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15592     return;
15593   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15594   if (!ID) {
15595     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15596       if (!CD->IsClassExtension())
15597         return;
15598     }
15599     // No need to add this to end of @implementation.
15600     else
15601       return;
15602   }
15603   // All conditions are met. Add a new bitfield to the tail end of ivars.
15604   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15605   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15606
15607   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15608                               DeclLoc, DeclLoc, nullptr,
15609                               Context.CharTy,
15610                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15611                                                                DeclLoc),
15612                               ObjCIvarDecl::Private, BW,
15613                               true);
15614   AllIvarDecls.push_back(Ivar);
15615 }
15616
15617 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15618                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15619                        SourceLocation RBrac,
15620                        const ParsedAttributesView &Attrs) {
15621   assert(EnclosingDecl && "missing record or interface decl");
15622
15623   // If this is an Objective-C @implementation or category and we have
15624   // new fields here we should reset the layout of the interface since
15625   // it will now change.
15626   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15627     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15628     switch (DC->getKind()) {
15629     default: break;
15630     case Decl::ObjCCategory:
15631       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15632       break;
15633     case Decl::ObjCImplementation:
15634       Context.
15635         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15636       break;
15637     }
15638   }
15639
15640   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15641
15642   // Start counting up the number of named members; make sure to include
15643   // members of anonymous structs and unions in the total.
15644   unsigned NumNamedMembers = 0;
15645   if (Record) {
15646     for (const auto *I : Record->decls()) {
15647       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15648         if (IFD->getDeclName())
15649           ++NumNamedMembers;
15650     }
15651   }
15652
15653   // Verify that all the fields are okay.
15654   SmallVector<FieldDecl*, 32> RecFields;
15655
15656   bool ObjCFieldLifetimeErrReported = false;
15657   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15658        i != end; ++i) {
15659     FieldDecl *FD = cast<FieldDecl>(*i);
15660
15661     // Get the type for the field.
15662     const Type *FDTy = FD->getType().getTypePtr();
15663
15664     if (!FD->isAnonymousStructOrUnion()) {
15665       // Remember all fields written by the user.
15666       RecFields.push_back(FD);
15667     }
15668
15669     // If the field is already invalid for some reason, don't emit more
15670     // diagnostics about it.
15671     if (FD->isInvalidDecl()) {
15672       EnclosingDecl->setInvalidDecl();
15673       continue;
15674     }
15675
15676     // C99 6.7.2.1p2:
15677     //   A structure or union shall not contain a member with
15678     //   incomplete or function type (hence, a structure shall not
15679     //   contain an instance of itself, but may contain a pointer to
15680     //   an instance of itself), except that the last member of a
15681     //   structure with more than one named member may have incomplete
15682     //   array type; such a structure (and any union containing,
15683     //   possibly recursively, a member that is such a structure)
15684     //   shall not be a member of a structure or an element of an
15685     //   array.
15686     bool IsLastField = (i + 1 == Fields.end());
15687     if (FDTy->isFunctionType()) {
15688       // Field declared as a function.
15689       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15690         << FD->getDeclName();
15691       FD->setInvalidDecl();
15692       EnclosingDecl->setInvalidDecl();
15693       continue;
15694     } else if (FDTy->isIncompleteArrayType() &&
15695                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15696       if (Record) {
15697         // Flexible array member.
15698         // Microsoft and g++ is more permissive regarding flexible array.
15699         // It will accept flexible array in union and also
15700         // as the sole element of a struct/class.
15701         unsigned DiagID = 0;
15702         if (!Record->isUnion() && !IsLastField) {
15703           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15704             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15705           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15706           FD->setInvalidDecl();
15707           EnclosingDecl->setInvalidDecl();
15708           continue;
15709         } else if (Record->isUnion())
15710           DiagID = getLangOpts().MicrosoftExt
15711                        ? diag::ext_flexible_array_union_ms
15712                        : getLangOpts().CPlusPlus
15713                              ? diag::ext_flexible_array_union_gnu
15714                              : diag::err_flexible_array_union;
15715         else if (NumNamedMembers < 1)
15716           DiagID = getLangOpts().MicrosoftExt
15717                        ? diag::ext_flexible_array_empty_aggregate_ms
15718                        : getLangOpts().CPlusPlus
15719                              ? diag::ext_flexible_array_empty_aggregate_gnu
15720                              : diag::err_flexible_array_empty_aggregate;
15721
15722         if (DiagID)
15723           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15724                                           << Record->getTagKind();
15725         // While the layout of types that contain virtual bases is not specified
15726         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15727         // virtual bases after the derived members.  This would make a flexible
15728         // array member declared at the end of an object not adjacent to the end
15729         // of the type.
15730         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15731           if (RD->getNumVBases() != 0)
15732             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15733               << FD->getDeclName() << Record->getTagKind();
15734         if (!getLangOpts().C99)
15735           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15736             << FD->getDeclName() << Record->getTagKind();
15737
15738         // If the element type has a non-trivial destructor, we would not
15739         // implicitly destroy the elements, so disallow it for now.
15740         //
15741         // FIXME: GCC allows this. We should probably either implicitly delete
15742         // the destructor of the containing class, or just allow this.
15743         QualType BaseElem = Context.getBaseElementType(FD->getType());
15744         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15745           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15746             << FD->getDeclName() << FD->getType();
15747           FD->setInvalidDecl();
15748           EnclosingDecl->setInvalidDecl();
15749           continue;
15750         }
15751         // Okay, we have a legal flexible array member at the end of the struct.
15752         Record->setHasFlexibleArrayMember(true);
15753       } else {
15754         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15755         // unless they are followed by another ivar. That check is done
15756         // elsewhere, after synthesized ivars are known.
15757       }
15758     } else if (!FDTy->isDependentType() &&
15759                RequireCompleteType(FD->getLocation(), FD->getType(),
15760                                    diag::err_field_incomplete)) {
15761       // Incomplete type
15762       FD->setInvalidDecl();
15763       EnclosingDecl->setInvalidDecl();
15764       continue;
15765     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15766       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15767         // A type which contains a flexible array member is considered to be a
15768         // flexible array member.
15769         Record->setHasFlexibleArrayMember(true);
15770         if (!Record->isUnion()) {
15771           // If this is a struct/class and this is not the last element, reject
15772           // it.  Note that GCC supports variable sized arrays in the middle of
15773           // structures.
15774           if (!IsLastField)
15775             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15776               << FD->getDeclName() << FD->getType();
15777           else {
15778             // We support flexible arrays at the end of structs in
15779             // other structs as an extension.
15780             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15781               << FD->getDeclName();
15782           }
15783         }
15784       }
15785       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15786           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15787                                  diag::err_abstract_type_in_decl,
15788                                  AbstractIvarType)) {
15789         // Ivars can not have abstract class types
15790         FD->setInvalidDecl();
15791       }
15792       if (Record && FDTTy->getDecl()->hasObjectMember())
15793         Record->setHasObjectMember(true);
15794       if (Record && FDTTy->getDecl()->hasVolatileMember())
15795         Record->setHasVolatileMember(true);
15796     } else if (FDTy->isObjCObjectType()) {
15797       /// A field cannot be an Objective-c object
15798       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15799         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15800       QualType T = Context.getObjCObjectPointerType(FD->getType());
15801       FD->setType(T);
15802     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15803                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15804       // It's an error in ARC or Weak if a field has lifetime.
15805       // We don't want to report this in a system header, though,
15806       // so we just make the field unavailable.
15807       // FIXME: that's really not sufficient; we need to make the type
15808       // itself invalid to, say, initialize or copy.
15809       QualType T = FD->getType();
15810       if (T.hasNonTrivialObjCLifetime()) {
15811         SourceLocation loc = FD->getLocation();
15812         if (getSourceManager().isInSystemHeader(loc)) {
15813           if (!FD->hasAttr<UnavailableAttr>()) {
15814             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15815                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15816           }
15817         } else {
15818           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15819             << T->isBlockPointerType() << Record->getTagKind();
15820         }
15821         ObjCFieldLifetimeErrReported = true;
15822       }
15823     } else if (getLangOpts().ObjC1 &&
15824                getLangOpts().getGC() != LangOptions::NonGC &&
15825                Record && !Record->hasObjectMember()) {
15826       if (FD->getType()->isObjCObjectPointerType() ||
15827           FD->getType().isObjCGCStrong())
15828         Record->setHasObjectMember(true);
15829       else if (Context.getAsArrayType(FD->getType())) {
15830         QualType BaseType = Context.getBaseElementType(FD->getType());
15831         if (BaseType->isRecordType() &&
15832             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15833           Record->setHasObjectMember(true);
15834         else if (BaseType->isObjCObjectPointerType() ||
15835                  BaseType.isObjCGCStrong())
15836                Record->setHasObjectMember(true);
15837       }
15838     }
15839
15840     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15841       QualType FT = FD->getType();
15842       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15843         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15844       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15845       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15846         Record->setNonTrivialToPrimitiveCopy(true);
15847       if (FT.isDestructedType()) {
15848         Record->setNonTrivialToPrimitiveDestroy(true);
15849         Record->setParamDestroyedInCallee(true);
15850       }
15851
15852       if (const auto *RT = FT->getAs<RecordType>()) {
15853         if (RT->getDecl()->getArgPassingRestrictions() ==
15854             RecordDecl::APK_CanNeverPassInRegs)
15855           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15856       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15857         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15858     }
15859
15860     if (Record && FD->getType().isVolatileQualified())
15861       Record->setHasVolatileMember(true);
15862     // Keep track of the number of named members.
15863     if (FD->getIdentifier())
15864       ++NumNamedMembers;
15865   }
15866
15867   // Okay, we successfully defined 'Record'.
15868   if (Record) {
15869     bool Completed = false;
15870     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15871       if (!CXXRecord->isInvalidDecl()) {
15872         // Set access bits correctly on the directly-declared conversions.
15873         for (CXXRecordDecl::conversion_iterator
15874                I = CXXRecord->conversion_begin(),
15875                E = CXXRecord->conversion_end(); I != E; ++I)
15876           I.setAccess((*I)->getAccess());
15877       }
15878
15879       if (!CXXRecord->isDependentType()) {
15880         if (CXXRecord->hasUserDeclaredDestructor()) {
15881           // Adjust user-defined destructor exception spec.
15882           if (getLangOpts().CPlusPlus11)
15883             AdjustDestructorExceptionSpec(CXXRecord,
15884                                           CXXRecord->getDestructor());
15885         }
15886
15887         // Add any implicitly-declared members to this class.
15888         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15889
15890         if (!CXXRecord->isInvalidDecl()) {
15891           // If we have virtual base classes, we may end up finding multiple
15892           // final overriders for a given virtual function. Check for this
15893           // problem now.
15894           if (CXXRecord->getNumVBases()) {
15895             CXXFinalOverriderMap FinalOverriders;
15896             CXXRecord->getFinalOverriders(FinalOverriders);
15897
15898             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15899                                              MEnd = FinalOverriders.end();
15900                  M != MEnd; ++M) {
15901               for (OverridingMethods::iterator SO = M->second.begin(),
15902                                             SOEnd = M->second.end();
15903                    SO != SOEnd; ++SO) {
15904                 assert(SO->second.size() > 0 &&
15905                        "Virtual function without overriding functions?");
15906                 if (SO->second.size() == 1)
15907                   continue;
15908
15909                 // C++ [class.virtual]p2:
15910                 //   In a derived class, if a virtual member function of a base
15911                 //   class subobject has more than one final overrider the
15912                 //   program is ill-formed.
15913                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15914                   << (const NamedDecl *)M->first << Record;
15915                 Diag(M->first->getLocation(),
15916                      diag::note_overridden_virtual_function);
15917                 for (OverridingMethods::overriding_iterator
15918                           OM = SO->second.begin(),
15919                        OMEnd = SO->second.end();
15920                      OM != OMEnd; ++OM)
15921                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15922                     << (const NamedDecl *)M->first << OM->Method->getParent();
15923
15924                 Record->setInvalidDecl();
15925               }
15926             }
15927             CXXRecord->completeDefinition(&FinalOverriders);
15928             Completed = true;
15929           }
15930         }
15931       }
15932     }
15933
15934     if (!Completed)
15935       Record->completeDefinition();
15936
15937     // Handle attributes before checking the layout.
15938     ProcessDeclAttributeList(S, Record, Attrs);
15939
15940     // We may have deferred checking for a deleted destructor. Check now.
15941     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15942       auto *Dtor = CXXRecord->getDestructor();
15943       if (Dtor && Dtor->isImplicit() &&
15944           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15945         CXXRecord->setImplicitDestructorIsDeleted();
15946         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15947       }
15948     }
15949
15950     if (Record->hasAttrs()) {
15951       CheckAlignasUnderalignment(Record);
15952
15953       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15954         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15955                                            IA->getRange(), IA->getBestCase(),
15956                                            IA->getSemanticSpelling());
15957     }
15958
15959     // Check if the structure/union declaration is a type that can have zero
15960     // size in C. For C this is a language extension, for C++ it may cause
15961     // compatibility problems.
15962     bool CheckForZeroSize;
15963     if (!getLangOpts().CPlusPlus) {
15964       CheckForZeroSize = true;
15965     } else {
15966       // For C++ filter out types that cannot be referenced in C code.
15967       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15968       CheckForZeroSize =
15969           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15970           !CXXRecord->isDependentType() &&
15971           CXXRecord->isCLike();
15972     }
15973     if (CheckForZeroSize) {
15974       bool ZeroSize = true;
15975       bool IsEmpty = true;
15976       unsigned NonBitFields = 0;
15977       for (RecordDecl::field_iterator I = Record->field_begin(),
15978                                       E = Record->field_end();
15979            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15980         IsEmpty = false;
15981         if (I->isUnnamedBitfield()) {
15982           if (!I->isZeroLengthBitField(Context))
15983             ZeroSize = false;
15984         } else {
15985           ++NonBitFields;
15986           QualType FieldType = I->getType();
15987           if (FieldType->isIncompleteType() ||
15988               !Context.getTypeSizeInChars(FieldType).isZero())
15989             ZeroSize = false;
15990         }
15991       }
15992
15993       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15994       // allowed in C++, but warn if its declaration is inside
15995       // extern "C" block.
15996       if (ZeroSize) {
15997         Diag(RecLoc, getLangOpts().CPlusPlus ?
15998                          diag::warn_zero_size_struct_union_in_extern_c :
15999                          diag::warn_zero_size_struct_union_compat)
16000           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16001       }
16002
16003       // Structs without named members are extension in C (C99 6.7.2.1p7),
16004       // but are accepted by GCC.
16005       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16006         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16007                                diag::ext_no_named_members_in_struct_union)
16008           << Record->isUnion();
16009       }
16010     }
16011   } else {
16012     ObjCIvarDecl **ClsFields =
16013       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16014     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16015       ID->setEndOfDefinitionLoc(RBrac);
16016       // Add ivar's to class's DeclContext.
16017       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16018         ClsFields[i]->setLexicalDeclContext(ID);
16019         ID->addDecl(ClsFields[i]);
16020       }
16021       // Must enforce the rule that ivars in the base classes may not be
16022       // duplicates.
16023       if (ID->getSuperClass())
16024         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16025     } else if (ObjCImplementationDecl *IMPDecl =
16026                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16027       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16028       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16029         // Ivar declared in @implementation never belongs to the implementation.
16030         // Only it is in implementation's lexical context.
16031         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16032       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16033       IMPDecl->setIvarLBraceLoc(LBrac);
16034       IMPDecl->setIvarRBraceLoc(RBrac);
16035     } else if (ObjCCategoryDecl *CDecl =
16036                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16037       // case of ivars in class extension; all other cases have been
16038       // reported as errors elsewhere.
16039       // FIXME. Class extension does not have a LocEnd field.
16040       // CDecl->setLocEnd(RBrac);
16041       // Add ivar's to class extension's DeclContext.
16042       // Diagnose redeclaration of private ivars.
16043       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16044       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16045         if (IDecl) {
16046           if (const ObjCIvarDecl *ClsIvar =
16047               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16048             Diag(ClsFields[i]->getLocation(),
16049                  diag::err_duplicate_ivar_declaration);
16050             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16051             continue;
16052           }
16053           for (const auto *Ext : IDecl->known_extensions()) {
16054             if (const ObjCIvarDecl *ClsExtIvar
16055                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16056               Diag(ClsFields[i]->getLocation(),
16057                    diag::err_duplicate_ivar_declaration);
16058               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16059               continue;
16060             }
16061           }
16062         }
16063         ClsFields[i]->setLexicalDeclContext(CDecl);
16064         CDecl->addDecl(ClsFields[i]);
16065       }
16066       CDecl->setIvarLBraceLoc(LBrac);
16067       CDecl->setIvarRBraceLoc(RBrac);
16068     }
16069   }
16070 }
16071
16072 /// Determine whether the given integral value is representable within
16073 /// the given type T.
16074 static bool isRepresentableIntegerValue(ASTContext &Context,
16075                                         llvm::APSInt &Value,
16076                                         QualType T) {
16077   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16078          "Integral type required!");
16079   unsigned BitWidth = Context.getIntWidth(T);
16080
16081   if (Value.isUnsigned() || Value.isNonNegative()) {
16082     if (T->isSignedIntegerOrEnumerationType())
16083       --BitWidth;
16084     return Value.getActiveBits() <= BitWidth;
16085   }
16086   return Value.getMinSignedBits() <= BitWidth;
16087 }
16088
16089 // Given an integral type, return the next larger integral type
16090 // (or a NULL type of no such type exists).
16091 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16092   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16093   // enum checking below.
16094   assert((T->isIntegralType(Context) ||
16095          T->isEnumeralType()) && "Integral type required!");
16096   const unsigned NumTypes = 4;
16097   QualType SignedIntegralTypes[NumTypes] = {
16098     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16099   };
16100   QualType UnsignedIntegralTypes[NumTypes] = {
16101     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16102     Context.UnsignedLongLongTy
16103   };
16104
16105   unsigned BitWidth = Context.getTypeSize(T);
16106   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16107                                                         : UnsignedIntegralTypes;
16108   for (unsigned I = 0; I != NumTypes; ++I)
16109     if (Context.getTypeSize(Types[I]) > BitWidth)
16110       return Types[I];
16111
16112   return QualType();
16113 }
16114
16115 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16116                                           EnumConstantDecl *LastEnumConst,
16117                                           SourceLocation IdLoc,
16118                                           IdentifierInfo *Id,
16119                                           Expr *Val) {
16120   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16121   llvm::APSInt EnumVal(IntWidth);
16122   QualType EltTy;
16123
16124   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16125     Val = nullptr;
16126
16127   if (Val)
16128     Val = DefaultLvalueConversion(Val).get();
16129
16130   if (Val) {
16131     if (Enum->isDependentType() || Val->isTypeDependent())
16132       EltTy = Context.DependentTy;
16133     else {
16134       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16135           !getLangOpts().MSVCCompat) {
16136         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16137         // constant-expression in the enumerator-definition shall be a converted
16138         // constant expression of the underlying type.
16139         EltTy = Enum->getIntegerType();
16140         ExprResult Converted =
16141           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16142                                            CCEK_Enumerator);
16143         if (Converted.isInvalid())
16144           Val = nullptr;
16145         else
16146           Val = Converted.get();
16147       } else if (!Val->isValueDependent() &&
16148                  !(Val = VerifyIntegerConstantExpression(Val,
16149                                                          &EnumVal).get())) {
16150         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16151       } else {
16152         if (Enum->isComplete()) {
16153           EltTy = Enum->getIntegerType();
16154
16155           // In Obj-C and Microsoft mode, require the enumeration value to be
16156           // representable in the underlying type of the enumeration. In C++11,
16157           // we perform a non-narrowing conversion as part of converted constant
16158           // expression checking.
16159           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16160             if (getLangOpts().MSVCCompat) {
16161               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16162               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16163             } else
16164               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16165           } else
16166             Val = ImpCastExprToType(Val, EltTy,
16167                                     EltTy->isBooleanType() ?
16168                                     CK_IntegralToBoolean : CK_IntegralCast)
16169                     .get();
16170         } else if (getLangOpts().CPlusPlus) {
16171           // C++11 [dcl.enum]p5:
16172           //   If the underlying type is not fixed, the type of each enumerator
16173           //   is the type of its initializing value:
16174           //     - If an initializer is specified for an enumerator, the
16175           //       initializing value has the same type as the expression.
16176           EltTy = Val->getType();
16177         } else {
16178           // C99 6.7.2.2p2:
16179           //   The expression that defines the value of an enumeration constant
16180           //   shall be an integer constant expression that has a value
16181           //   representable as an int.
16182
16183           // Complain if the value is not representable in an int.
16184           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16185             Diag(IdLoc, diag::ext_enum_value_not_int)
16186               << EnumVal.toString(10) << Val->getSourceRange()
16187               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16188           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16189             // Force the type of the expression to 'int'.
16190             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16191           }
16192           EltTy = Val->getType();
16193         }
16194       }
16195     }
16196   }
16197
16198   if (!Val) {
16199     if (Enum->isDependentType())
16200       EltTy = Context.DependentTy;
16201     else if (!LastEnumConst) {
16202       // C++0x [dcl.enum]p5:
16203       //   If the underlying type is not fixed, the type of each enumerator
16204       //   is the type of its initializing value:
16205       //     - If no initializer is specified for the first enumerator, the
16206       //       initializing value has an unspecified integral type.
16207       //
16208       // GCC uses 'int' for its unspecified integral type, as does
16209       // C99 6.7.2.2p3.
16210       if (Enum->isFixed()) {
16211         EltTy = Enum->getIntegerType();
16212       }
16213       else {
16214         EltTy = Context.IntTy;
16215       }
16216     } else {
16217       // Assign the last value + 1.
16218       EnumVal = LastEnumConst->getInitVal();
16219       ++EnumVal;
16220       EltTy = LastEnumConst->getType();
16221
16222       // Check for overflow on increment.
16223       if (EnumVal < LastEnumConst->getInitVal()) {
16224         // C++0x [dcl.enum]p5:
16225         //   If the underlying type is not fixed, the type of each enumerator
16226         //   is the type of its initializing value:
16227         //
16228         //     - Otherwise the type of the initializing value is the same as
16229         //       the type of the initializing value of the preceding enumerator
16230         //       unless the incremented value is not representable in that type,
16231         //       in which case the type is an unspecified integral type
16232         //       sufficient to contain the incremented value. If no such type
16233         //       exists, the program is ill-formed.
16234         QualType T = getNextLargerIntegralType(Context, EltTy);
16235         if (T.isNull() || Enum->isFixed()) {
16236           // There is no integral type larger enough to represent this
16237           // value. Complain, then allow the value to wrap around.
16238           EnumVal = LastEnumConst->getInitVal();
16239           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16240           ++EnumVal;
16241           if (Enum->isFixed())
16242             // When the underlying type is fixed, this is ill-formed.
16243             Diag(IdLoc, diag::err_enumerator_wrapped)
16244               << EnumVal.toString(10)
16245               << EltTy;
16246           else
16247             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16248               << EnumVal.toString(10);
16249         } else {
16250           EltTy = T;
16251         }
16252
16253         // Retrieve the last enumerator's value, extent that type to the
16254         // type that is supposed to be large enough to represent the incremented
16255         // value, then increment.
16256         EnumVal = LastEnumConst->getInitVal();
16257         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16258         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16259         ++EnumVal;
16260
16261         // If we're not in C++, diagnose the overflow of enumerator values,
16262         // which in C99 means that the enumerator value is not representable in
16263         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16264         // permits enumerator values that are representable in some larger
16265         // integral type.
16266         if (!getLangOpts().CPlusPlus && !T.isNull())
16267           Diag(IdLoc, diag::warn_enum_value_overflow);
16268       } else if (!getLangOpts().CPlusPlus &&
16269                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16270         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16271         Diag(IdLoc, diag::ext_enum_value_not_int)
16272           << EnumVal.toString(10) << 1;
16273       }
16274     }
16275   }
16276
16277   if (!EltTy->isDependentType()) {
16278     // Make the enumerator value match the signedness and size of the
16279     // enumerator's type.
16280     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16281     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16282   }
16283
16284   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16285                                   Val, EnumVal);
16286 }
16287
16288 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16289                                                 SourceLocation IILoc) {
16290   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16291       !getLangOpts().CPlusPlus)
16292     return SkipBodyInfo();
16293
16294   // We have an anonymous enum definition. Look up the first enumerator to
16295   // determine if we should merge the definition with an existing one and
16296   // skip the body.
16297   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16298                                          forRedeclarationInCurContext());
16299   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16300   if (!PrevECD)
16301     return SkipBodyInfo();
16302
16303   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16304   NamedDecl *Hidden;
16305   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16306     SkipBodyInfo Skip;
16307     Skip.Previous = Hidden;
16308     return Skip;
16309   }
16310
16311   return SkipBodyInfo();
16312 }
16313
16314 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16315                               SourceLocation IdLoc, IdentifierInfo *Id,
16316                               const ParsedAttributesView &Attrs,
16317                               SourceLocation EqualLoc, Expr *Val) {
16318   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16319   EnumConstantDecl *LastEnumConst =
16320     cast_or_null<EnumConstantDecl>(lastEnumConst);
16321
16322   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16323   // we find one that is.
16324   S = getNonFieldDeclScope(S);
16325
16326   // Verify that there isn't already something declared with this name in this
16327   // scope.
16328   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
16329                                          ForVisibleRedeclaration);
16330   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16331     // Maybe we will complain about the shadowed template parameter.
16332     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16333     // Just pretend that we didn't see the previous declaration.
16334     PrevDecl = nullptr;
16335   }
16336
16337   // C++ [class.mem]p15:
16338   // If T is the name of a class, then each of the following shall have a name
16339   // different from T:
16340   // - every enumerator of every member of class T that is an unscoped
16341   // enumerated type
16342   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16343     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16344                             DeclarationNameInfo(Id, IdLoc));
16345
16346   EnumConstantDecl *New =
16347     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16348   if (!New)
16349     return nullptr;
16350
16351   if (PrevDecl) {
16352     // When in C++, we may get a TagDecl with the same name; in this case the
16353     // enum constant will 'hide' the tag.
16354     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16355            "Received TagDecl when not in C++!");
16356     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16357       if (isa<EnumConstantDecl>(PrevDecl))
16358         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16359       else
16360         Diag(IdLoc, diag::err_redefinition) << Id;
16361       notePreviousDefinition(PrevDecl, IdLoc);
16362       return nullptr;
16363     }
16364   }
16365
16366   // Process attributes.
16367   ProcessDeclAttributeList(S, New, Attrs);
16368   AddPragmaAttributes(S, New);
16369
16370   // Register this decl in the current scope stack.
16371   New->setAccess(TheEnumDecl->getAccess());
16372   PushOnScopeChains(New, S);
16373
16374   ActOnDocumentableDecl(New);
16375
16376   return New;
16377 }
16378
16379 // Returns true when the enum initial expression does not trigger the
16380 // duplicate enum warning.  A few common cases are exempted as follows:
16381 // Element2 = Element1
16382 // Element2 = Element1 + 1
16383 // Element2 = Element1 - 1
16384 // Where Element2 and Element1 are from the same enum.
16385 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16386   Expr *InitExpr = ECD->getInitExpr();
16387   if (!InitExpr)
16388     return true;
16389   InitExpr = InitExpr->IgnoreImpCasts();
16390
16391   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16392     if (!BO->isAdditiveOp())
16393       return true;
16394     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16395     if (!IL)
16396       return true;
16397     if (IL->getValue() != 1)
16398       return true;
16399
16400     InitExpr = BO->getLHS();
16401   }
16402
16403   // This checks if the elements are from the same enum.
16404   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16405   if (!DRE)
16406     return true;
16407
16408   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16409   if (!EnumConstant)
16410     return true;
16411
16412   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16413       Enum)
16414     return true;
16415
16416   return false;
16417 }
16418
16419 // Emits a warning when an element is implicitly set a value that
16420 // a previous element has already been set to.
16421 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16422                                         EnumDecl *Enum, QualType EnumType) {
16423   // Avoid anonymous enums
16424   if (!Enum->getIdentifier())
16425     return;
16426
16427   // Only check for small enums.
16428   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16429     return;
16430
16431   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16432     return;
16433
16434   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16435   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16436
16437   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16438   typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16439
16440   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16441   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16442     llvm::APSInt Val = D->getInitVal();
16443     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16444   };
16445
16446   DuplicatesVector DupVector;
16447   ValueToVectorMap EnumMap;
16448
16449   // Populate the EnumMap with all values represented by enum constants without
16450   // an initializer.
16451   for (auto *Element : Elements) {
16452     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16453
16454     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16455     // this constant.  Skip this enum since it may be ill-formed.
16456     if (!ECD) {
16457       return;
16458     }
16459
16460     // Constants with initalizers are handled in the next loop.
16461     if (ECD->getInitExpr())
16462       continue;
16463
16464     // Duplicate values are handled in the next loop.
16465     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16466   }
16467
16468   if (EnumMap.size() == 0)
16469     return;
16470
16471   // Create vectors for any values that has duplicates.
16472   for (auto *Element : Elements) {
16473     // The last loop returned if any constant was null.
16474     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16475     if (!ValidDuplicateEnum(ECD, Enum))
16476       continue;
16477
16478     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16479     if (Iter == EnumMap.end())
16480       continue;
16481
16482     DeclOrVector& Entry = Iter->second;
16483     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16484       // Ensure constants are different.
16485       if (D == ECD)
16486         continue;
16487
16488       // Create new vector and push values onto it.
16489       auto Vec = llvm::make_unique<ECDVector>();
16490       Vec->push_back(D);
16491       Vec->push_back(ECD);
16492
16493       // Update entry to point to the duplicates vector.
16494       Entry = Vec.get();
16495
16496       // Store the vector somewhere we can consult later for quick emission of
16497       // diagnostics.
16498       DupVector.emplace_back(std::move(Vec));
16499       continue;
16500     }
16501
16502     ECDVector *Vec = Entry.get<ECDVector*>();
16503     // Make sure constants are not added more than once.
16504     if (*Vec->begin() == ECD)
16505       continue;
16506
16507     Vec->push_back(ECD);
16508   }
16509
16510   // Emit diagnostics.
16511   for (const auto &Vec : DupVector) {
16512     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16513
16514     // Emit warning for one enum constant.
16515     auto *FirstECD = Vec->front();
16516     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16517       << FirstECD << FirstECD->getInitVal().toString(10)
16518       << FirstECD->getSourceRange();
16519
16520     // Emit one note for each of the remaining enum constants with
16521     // the same value.
16522     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16523       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16524         << ECD << ECD->getInitVal().toString(10)
16525         << ECD->getSourceRange();
16526   }
16527 }
16528
16529 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16530                              bool AllowMask) const {
16531   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16532   assert(ED->isCompleteDefinition() && "expected enum definition");
16533
16534   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16535   llvm::APInt &FlagBits = R.first->second;
16536
16537   if (R.second) {
16538     for (auto *E : ED->enumerators()) {
16539       const auto &EVal = E->getInitVal();
16540       // Only single-bit enumerators introduce new flag values.
16541       if (EVal.isPowerOf2())
16542         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16543     }
16544   }
16545
16546   // A value is in a flag enum if either its bits are a subset of the enum's
16547   // flag bits (the first condition) or we are allowing masks and the same is
16548   // true of its complement (the second condition). When masks are allowed, we
16549   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16550   //
16551   // While it's true that any value could be used as a mask, the assumption is
16552   // that a mask will have all of the insignificant bits set. Anything else is
16553   // likely a logic error.
16554   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16555   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16556 }
16557
16558 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16559                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16560                          const ParsedAttributesView &Attrs) {
16561   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16562   QualType EnumType = Context.getTypeDeclType(Enum);
16563
16564   ProcessDeclAttributeList(S, Enum, Attrs);
16565
16566   if (Enum->isDependentType()) {
16567     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16568       EnumConstantDecl *ECD =
16569         cast_or_null<EnumConstantDecl>(Elements[i]);
16570       if (!ECD) continue;
16571
16572       ECD->setType(EnumType);
16573     }
16574
16575     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16576     return;
16577   }
16578
16579   // TODO: If the result value doesn't fit in an int, it must be a long or long
16580   // long value.  ISO C does not support this, but GCC does as an extension,
16581   // emit a warning.
16582   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16583   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16584   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16585
16586   // Verify that all the values are okay, compute the size of the values, and
16587   // reverse the list.
16588   unsigned NumNegativeBits = 0;
16589   unsigned NumPositiveBits = 0;
16590
16591   // Keep track of whether all elements have type int.
16592   bool AllElementsInt = true;
16593
16594   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16595     EnumConstantDecl *ECD =
16596       cast_or_null<EnumConstantDecl>(Elements[i]);
16597     if (!ECD) continue;  // Already issued a diagnostic.
16598
16599     const llvm::APSInt &InitVal = ECD->getInitVal();
16600
16601     // Keep track of the size of positive and negative values.
16602     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16603       NumPositiveBits = std::max(NumPositiveBits,
16604                                  (unsigned)InitVal.getActiveBits());
16605     else
16606       NumNegativeBits = std::max(NumNegativeBits,
16607                                  (unsigned)InitVal.getMinSignedBits());
16608
16609     // Keep track of whether every enum element has type int (very commmon).
16610     if (AllElementsInt)
16611       AllElementsInt = ECD->getType() == Context.IntTy;
16612   }
16613
16614   // Figure out the type that should be used for this enum.
16615   QualType BestType;
16616   unsigned BestWidth;
16617
16618   // C++0x N3000 [conv.prom]p3:
16619   //   An rvalue of an unscoped enumeration type whose underlying
16620   //   type is not fixed can be converted to an rvalue of the first
16621   //   of the following types that can represent all the values of
16622   //   the enumeration: int, unsigned int, long int, unsigned long
16623   //   int, long long int, or unsigned long long int.
16624   // C99 6.4.4.3p2:
16625   //   An identifier declared as an enumeration constant has type int.
16626   // The C99 rule is modified by a gcc extension
16627   QualType BestPromotionType;
16628
16629   bool Packed = Enum->hasAttr<PackedAttr>();
16630   // -fshort-enums is the equivalent to specifying the packed attribute on all
16631   // enum definitions.
16632   if (LangOpts.ShortEnums)
16633     Packed = true;
16634
16635   // If the enum already has a type because it is fixed or dictated by the
16636   // target, promote that type instead of analyzing the enumerators.
16637   if (Enum->isComplete()) {
16638     BestType = Enum->getIntegerType();
16639     if (BestType->isPromotableIntegerType())
16640       BestPromotionType = Context.getPromotedIntegerType(BestType);
16641     else
16642       BestPromotionType = BestType;
16643
16644     BestWidth = Context.getIntWidth(BestType);
16645   }
16646   else if (NumNegativeBits) {
16647     // If there is a negative value, figure out the smallest integer type (of
16648     // int/long/longlong) that fits.
16649     // If it's packed, check also if it fits a char or a short.
16650     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16651       BestType = Context.SignedCharTy;
16652       BestWidth = CharWidth;
16653     } else if (Packed && NumNegativeBits <= ShortWidth &&
16654                NumPositiveBits < ShortWidth) {
16655       BestType = Context.ShortTy;
16656       BestWidth = ShortWidth;
16657     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16658       BestType = Context.IntTy;
16659       BestWidth = IntWidth;
16660     } else {
16661       BestWidth = Context.getTargetInfo().getLongWidth();
16662
16663       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16664         BestType = Context.LongTy;
16665       } else {
16666         BestWidth = Context.getTargetInfo().getLongLongWidth();
16667
16668         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16669           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16670         BestType = Context.LongLongTy;
16671       }
16672     }
16673     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16674   } else {
16675     // If there is no negative value, figure out the smallest type that fits
16676     // all of the enumerator values.
16677     // If it's packed, check also if it fits a char or a short.
16678     if (Packed && NumPositiveBits <= CharWidth) {
16679       BestType = Context.UnsignedCharTy;
16680       BestPromotionType = Context.IntTy;
16681       BestWidth = CharWidth;
16682     } else if (Packed && NumPositiveBits <= ShortWidth) {
16683       BestType = Context.UnsignedShortTy;
16684       BestPromotionType = Context.IntTy;
16685       BestWidth = ShortWidth;
16686     } else if (NumPositiveBits <= IntWidth) {
16687       BestType = Context.UnsignedIntTy;
16688       BestWidth = IntWidth;
16689       BestPromotionType
16690         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16691                            ? Context.UnsignedIntTy : Context.IntTy;
16692     } else if (NumPositiveBits <=
16693                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16694       BestType = Context.UnsignedLongTy;
16695       BestPromotionType
16696         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16697                            ? Context.UnsignedLongTy : Context.LongTy;
16698     } else {
16699       BestWidth = Context.getTargetInfo().getLongLongWidth();
16700       assert(NumPositiveBits <= BestWidth &&
16701              "How could an initializer get larger than ULL?");
16702       BestType = Context.UnsignedLongLongTy;
16703       BestPromotionType
16704         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16705                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16706     }
16707   }
16708
16709   // Loop over all of the enumerator constants, changing their types to match
16710   // the type of the enum if needed.
16711   for (auto *D : Elements) {
16712     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16713     if (!ECD) continue;  // Already issued a diagnostic.
16714
16715     // Standard C says the enumerators have int type, but we allow, as an
16716     // extension, the enumerators to be larger than int size.  If each
16717     // enumerator value fits in an int, type it as an int, otherwise type it the
16718     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16719     // that X has type 'int', not 'unsigned'.
16720
16721     // Determine whether the value fits into an int.
16722     llvm::APSInt InitVal = ECD->getInitVal();
16723
16724     // If it fits into an integer type, force it.  Otherwise force it to match
16725     // the enum decl type.
16726     QualType NewTy;
16727     unsigned NewWidth;
16728     bool NewSign;
16729     if (!getLangOpts().CPlusPlus &&
16730         !Enum->isFixed() &&
16731         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16732       NewTy = Context.IntTy;
16733       NewWidth = IntWidth;
16734       NewSign = true;
16735     } else if (ECD->getType() == BestType) {
16736       // Already the right type!
16737       if (getLangOpts().CPlusPlus)
16738         // C++ [dcl.enum]p4: Following the closing brace of an
16739         // enum-specifier, each enumerator has the type of its
16740         // enumeration.
16741         ECD->setType(EnumType);
16742       continue;
16743     } else {
16744       NewTy = BestType;
16745       NewWidth = BestWidth;
16746       NewSign = BestType->isSignedIntegerOrEnumerationType();
16747     }
16748
16749     // Adjust the APSInt value.
16750     InitVal = InitVal.extOrTrunc(NewWidth);
16751     InitVal.setIsSigned(NewSign);
16752     ECD->setInitVal(InitVal);
16753
16754     // Adjust the Expr initializer and type.
16755     if (ECD->getInitExpr() &&
16756         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16757       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16758                                                 CK_IntegralCast,
16759                                                 ECD->getInitExpr(),
16760                                                 /*base paths*/ nullptr,
16761                                                 VK_RValue));
16762     if (getLangOpts().CPlusPlus)
16763       // C++ [dcl.enum]p4: Following the closing brace of an
16764       // enum-specifier, each enumerator has the type of its
16765       // enumeration.
16766       ECD->setType(EnumType);
16767     else
16768       ECD->setType(NewTy);
16769   }
16770
16771   Enum->completeDefinition(BestType, BestPromotionType,
16772                            NumPositiveBits, NumNegativeBits);
16773
16774   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16775
16776   if (Enum->isClosedFlag()) {
16777     for (Decl *D : Elements) {
16778       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16779       if (!ECD) continue;  // Already issued a diagnostic.
16780
16781       llvm::APSInt InitVal = ECD->getInitVal();
16782       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16783           !IsValueInFlagEnum(Enum, InitVal, true))
16784         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16785           << ECD << Enum;
16786     }
16787   }
16788
16789   // Now that the enum type is defined, ensure it's not been underaligned.
16790   if (Enum->hasAttrs())
16791     CheckAlignasUnderalignment(Enum);
16792 }
16793
16794 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16795                                   SourceLocation StartLoc,
16796                                   SourceLocation EndLoc) {
16797   StringLiteral *AsmString = cast<StringLiteral>(expr);
16798
16799   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16800                                                    AsmString, StartLoc,
16801                                                    EndLoc);
16802   CurContext->addDecl(New);
16803   return New;
16804 }
16805
16806 static void checkModuleImportContext(Sema &S, Module *M,
16807                                      SourceLocation ImportLoc, DeclContext *DC,
16808                                      bool FromInclude = false) {
16809   SourceLocation ExternCLoc;
16810
16811   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16812     switch (LSD->getLanguage()) {
16813     case LinkageSpecDecl::lang_c:
16814       if (ExternCLoc.isInvalid())
16815         ExternCLoc = LSD->getLocStart();
16816       break;
16817     case LinkageSpecDecl::lang_cxx:
16818       break;
16819     }
16820     DC = LSD->getParent();
16821   }
16822
16823   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16824     DC = DC->getParent();
16825
16826   if (!isa<TranslationUnitDecl>(DC)) {
16827     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16828                           ? diag::ext_module_import_not_at_top_level_noop
16829                           : diag::err_module_import_not_at_top_level_fatal)
16830         << M->getFullModuleName() << DC;
16831     S.Diag(cast<Decl>(DC)->getLocStart(),
16832            diag::note_module_import_not_at_top_level) << DC;
16833   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16834     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16835       << M->getFullModuleName();
16836     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16837   }
16838 }
16839
16840 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16841                                            SourceLocation ModuleLoc,
16842                                            ModuleDeclKind MDK,
16843                                            ModuleIdPath Path) {
16844   assert(getLangOpts().ModulesTS &&
16845          "should only have module decl in modules TS");
16846
16847   // A module implementation unit requires that we are not compiling a module
16848   // of any kind. A module interface unit requires that we are not compiling a
16849   // module map.
16850   switch (getLangOpts().getCompilingModule()) {
16851   case LangOptions::CMK_None:
16852     // It's OK to compile a module interface as a normal translation unit.
16853     break;
16854
16855   case LangOptions::CMK_ModuleInterface:
16856     if (MDK != ModuleDeclKind::Implementation)
16857       break;
16858
16859     // We were asked to compile a module interface unit but this is a module
16860     // implementation unit. That indicates the 'export' is missing.
16861     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16862       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16863     MDK = ModuleDeclKind::Interface;
16864     break;
16865
16866   case LangOptions::CMK_ModuleMap:
16867     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16868     return nullptr;
16869   }
16870
16871   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16872
16873   // FIXME: Most of this work should be done by the preprocessor rather than
16874   // here, in order to support macro import.
16875
16876   // Only one module-declaration is permitted per source file.
16877   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16878     Diag(ModuleLoc, diag::err_module_redeclaration);
16879     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16880          diag::note_prev_module_declaration);
16881     return nullptr;
16882   }
16883
16884   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16885   // modules, the dots here are just another character that can appear in a
16886   // module name.
16887   std::string ModuleName;
16888   for (auto &Piece : Path) {
16889     if (!ModuleName.empty())
16890       ModuleName += ".";
16891     ModuleName += Piece.first->getName();
16892   }
16893
16894   // If a module name was explicitly specified on the command line, it must be
16895   // correct.
16896   if (!getLangOpts().CurrentModule.empty() &&
16897       getLangOpts().CurrentModule != ModuleName) {
16898     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16899         << SourceRange(Path.front().second, Path.back().second)
16900         << getLangOpts().CurrentModule;
16901     return nullptr;
16902   }
16903   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16904
16905   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16906   Module *Mod;
16907
16908   switch (MDK) {
16909   case ModuleDeclKind::Interface: {
16910     // We can't have parsed or imported a definition of this module or parsed a
16911     // module map defining it already.
16912     if (auto *M = Map.findModule(ModuleName)) {
16913       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16914       if (M->DefinitionLoc.isValid())
16915         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16916       else if (const auto *FE = M->getASTFile())
16917         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16918             << FE->getName();
16919       Mod = M;
16920       break;
16921     }
16922
16923     // Create a Module for the module that we're defining.
16924     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16925                                            ModuleScopes.front().Module);
16926     assert(Mod && "module creation should not fail");
16927     break;
16928   }
16929
16930   case ModuleDeclKind::Partition:
16931     // FIXME: Check we are in a submodule of the named module.
16932     return nullptr;
16933
16934   case ModuleDeclKind::Implementation:
16935     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16936         PP.getIdentifierInfo(ModuleName), Path[0].second);
16937     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16938                                        /*IsIncludeDirective=*/false);
16939     if (!Mod) {
16940       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16941       // Create an empty module interface unit for error recovery.
16942       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16943                                              ModuleScopes.front().Module);
16944     }
16945     break;
16946   }
16947
16948   // Switch from the global module to the named module.
16949   ModuleScopes.back().Module = Mod;
16950   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16951   VisibleModules.setVisible(Mod, ModuleLoc);
16952
16953   // From now on, we have an owning module for all declarations we see.
16954   // However, those declarations are module-private unless explicitly
16955   // exported.
16956   auto *TU = Context.getTranslationUnitDecl();
16957   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16958   TU->setLocalOwningModule(Mod);
16959
16960   // FIXME: Create a ModuleDecl.
16961   return nullptr;
16962 }
16963
16964 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16965                                    SourceLocation ImportLoc,
16966                                    ModuleIdPath Path) {
16967   Module *Mod =
16968       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16969                                    /*IsIncludeDirective=*/false);
16970   if (!Mod)
16971     return true;
16972
16973   VisibleModules.setVisible(Mod, ImportLoc);
16974
16975   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16976
16977   // FIXME: we should support importing a submodule within a different submodule
16978   // of the same top-level module. Until we do, make it an error rather than
16979   // silently ignoring the import.
16980   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16981   // warn on a redundant import of the current module?
16982   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16983       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16984     Diag(ImportLoc, getLangOpts().isCompilingModule()
16985                         ? diag::err_module_self_import
16986                         : diag::err_module_import_in_implementation)
16987         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16988
16989   SmallVector<SourceLocation, 2> IdentifierLocs;
16990   Module *ModCheck = Mod;
16991   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16992     // If we've run out of module parents, just drop the remaining identifiers.
16993     // We need the length to be consistent.
16994     if (!ModCheck)
16995       break;
16996     ModCheck = ModCheck->Parent;
16997
16998     IdentifierLocs.push_back(Path[I].second);
16999   }
17000
17001   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17002                                           Mod, IdentifierLocs);
17003   if (!ModuleScopes.empty())
17004     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17005   CurContext->addDecl(Import);
17006
17007   // Re-export the module if needed.
17008   if (Import->isExported() &&
17009       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17010     getCurrentModule()->Exports.emplace_back(Mod, false);
17011
17012   return Import;
17013 }
17014
17015 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17016   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17017   BuildModuleInclude(DirectiveLoc, Mod);
17018 }
17019
17020 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17021   // Determine whether we're in the #include buffer for a module. The #includes
17022   // in that buffer do not qualify as module imports; they're just an
17023   // implementation detail of us building the module.
17024   //
17025   // FIXME: Should we even get ActOnModuleInclude calls for those?
17026   bool IsInModuleIncludes =
17027       TUKind == TU_Module &&
17028       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17029
17030   bool ShouldAddImport = !IsInModuleIncludes;
17031
17032   // If this module import was due to an inclusion directive, create an
17033   // implicit import declaration to capture it in the AST.
17034   if (ShouldAddImport) {
17035     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17036     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17037                                                      DirectiveLoc, Mod,
17038                                                      DirectiveLoc);
17039     if (!ModuleScopes.empty())
17040       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17041     TU->addDecl(ImportD);
17042     Consumer.HandleImplicitImportDecl(ImportD);
17043   }
17044
17045   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17046   VisibleModules.setVisible(Mod, DirectiveLoc);
17047 }
17048
17049 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17050   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17051
17052   ModuleScopes.push_back({});
17053   ModuleScopes.back().Module = Mod;
17054   if (getLangOpts().ModulesLocalVisibility)
17055     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17056
17057   VisibleModules.setVisible(Mod, DirectiveLoc);
17058
17059   // The enclosing context is now part of this module.
17060   // FIXME: Consider creating a child DeclContext to hold the entities
17061   // lexically within the module.
17062   if (getLangOpts().trackLocalOwningModule()) {
17063     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17064       cast<Decl>(DC)->setModuleOwnershipKind(
17065           getLangOpts().ModulesLocalVisibility
17066               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17067               : Decl::ModuleOwnershipKind::Visible);
17068       cast<Decl>(DC)->setLocalOwningModule(Mod);
17069     }
17070   }
17071 }
17072
17073 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17074   if (getLangOpts().ModulesLocalVisibility) {
17075     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17076     // Leaving a module hides namespace names, so our visible namespace cache
17077     // is now out of date.
17078     VisibleNamespaceCache.clear();
17079   }
17080
17081   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17082          "left the wrong module scope");
17083   ModuleScopes.pop_back();
17084
17085   // We got to the end of processing a local module. Create an
17086   // ImportDecl as we would for an imported module.
17087   FileID File = getSourceManager().getFileID(EomLoc);
17088   SourceLocation DirectiveLoc;
17089   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17090     // We reached the end of a #included module header. Use the #include loc.
17091     assert(File != getSourceManager().getMainFileID() &&
17092            "end of submodule in main source file");
17093     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17094   } else {
17095     // We reached an EOM pragma. Use the pragma location.
17096     DirectiveLoc = EomLoc;
17097   }
17098   BuildModuleInclude(DirectiveLoc, Mod);
17099
17100   // Any further declarations are in whatever module we returned to.
17101   if (getLangOpts().trackLocalOwningModule()) {
17102     // The parser guarantees that this is the same context that we entered
17103     // the module within.
17104     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17105       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17106       if (!getCurrentModule())
17107         cast<Decl>(DC)->setModuleOwnershipKind(
17108             Decl::ModuleOwnershipKind::Unowned);
17109     }
17110   }
17111 }
17112
17113 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17114                                                       Module *Mod) {
17115   // Bail if we're not allowed to implicitly import a module here.
17116   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17117       VisibleModules.isVisible(Mod))
17118     return;
17119
17120   // Create the implicit import declaration.
17121   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17122   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17123                                                    Loc, Mod, Loc);
17124   TU->addDecl(ImportD);
17125   Consumer.HandleImplicitImportDecl(ImportD);
17126
17127   // Make the module visible.
17128   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17129   VisibleModules.setVisible(Mod, Loc);
17130 }
17131
17132 /// We have parsed the start of an export declaration, including the '{'
17133 /// (if present).
17134 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17135                                  SourceLocation LBraceLoc) {
17136   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17137
17138   // C++ Modules TS draft:
17139   //   An export-declaration shall appear in the purview of a module other than
17140   //   the global module.
17141   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17142     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17143
17144   //   An export-declaration [...] shall not contain more than one
17145   //   export keyword.
17146   //
17147   // The intent here is that an export-declaration cannot appear within another
17148   // export-declaration.
17149   if (D->isExported())
17150     Diag(ExportLoc, diag::err_export_within_export);
17151
17152   CurContext->addDecl(D);
17153   PushDeclContext(S, D);
17154   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17155   return D;
17156 }
17157
17158 /// Complete the definition of an export declaration.
17159 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17160   auto *ED = cast<ExportDecl>(D);
17161   if (RBraceLoc.isValid())
17162     ED->setRBraceLoc(RBraceLoc);
17163
17164   // FIXME: Diagnose export of internal-linkage declaration (including
17165   // anonymous namespace).
17166
17167   PopDeclContext();
17168   return D;
17169 }
17170
17171 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17172                                       IdentifierInfo* AliasName,
17173                                       SourceLocation PragmaLoc,
17174                                       SourceLocation NameLoc,
17175                                       SourceLocation AliasNameLoc) {
17176   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17177                                          LookupOrdinaryName);
17178   AsmLabelAttr *Attr =
17179       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17180
17181   // If a declaration that:
17182   // 1) declares a function or a variable
17183   // 2) has external linkage
17184   // already exists, add a label attribute to it.
17185   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17186     if (isDeclExternC(PrevDecl))
17187       PrevDecl->addAttr(Attr);
17188     else
17189       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17190           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17191   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17192   } else
17193     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17194 }
17195
17196 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17197                              SourceLocation PragmaLoc,
17198                              SourceLocation NameLoc) {
17199   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17200
17201   if (PrevDecl) {
17202     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17203   } else {
17204     (void)WeakUndeclaredIdentifiers.insert(
17205       std::pair<IdentifierInfo*,WeakInfo>
17206         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17207   }
17208 }
17209
17210 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17211                                 IdentifierInfo* AliasName,
17212                                 SourceLocation PragmaLoc,
17213                                 SourceLocation NameLoc,
17214                                 SourceLocation AliasNameLoc) {
17215   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17216                                     LookupOrdinaryName);
17217   WeakInfo W = WeakInfo(Name, NameLoc);
17218
17219   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17220     if (!PrevDecl->hasAttr<AliasAttr>())
17221       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17222         DeclApplyPragmaWeak(TUScope, ND, W);
17223   } else {
17224     (void)WeakUndeclaredIdentifiers.insert(
17225       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17226   }
17227 }
17228
17229 Decl *Sema::getObjCDeclContext() const {
17230   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17231 }