]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp
Merge ^/vendor/lvm-project/release-10.x up to its last change (upstream
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "TreeTransform.h"
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/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51
52 using namespace clang;
53 using namespace sema;
54
55 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56   if (OwnedType) {
57     Decl *Group[2] = { OwnedType, Ptr };
58     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
59   }
60
61   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
62 }
63
64 namespace {
65
66 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
67  public:
68    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
69                         bool AllowTemplates = false,
70                         bool AllowNonTemplates = true)
71        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
72          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
73      WantExpressionKeywords = false;
74      WantCXXNamedCasts = false;
75      WantRemainingKeywords = false;
76   }
77
78   bool ValidateCandidate(const TypoCorrection &candidate) override {
79     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
80       if (!AllowInvalidDecl && ND->isInvalidDecl())
81         return false;
82
83       if (getAsTypeTemplateDecl(ND))
84         return AllowTemplates;
85
86       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
87       if (!IsType)
88         return false;
89
90       if (AllowNonTemplates)
91         return true;
92
93       // An injected-class-name of a class template (specialization) is valid
94       // as a template or as a non-template.
95       if (AllowTemplates) {
96         auto *RD = dyn_cast<CXXRecordDecl>(ND);
97         if (!RD || !RD->isInjectedClassName())
98           return false;
99         RD = cast<CXXRecordDecl>(RD->getDeclContext());
100         return RD->getDescribedClassTemplate() ||
101                isa<ClassTemplateSpecializationDecl>(RD);
102       }
103
104       return false;
105     }
106
107     return !WantClassName && candidate.isKeyword();
108   }
109
110   std::unique_ptr<CorrectionCandidateCallback> clone() override {
111     return std::make_unique<TypeNameValidatorCCC>(*this);
112   }
113
114  private:
115   bool AllowInvalidDecl;
116   bool WantClassName;
117   bool AllowTemplates;
118   bool AllowNonTemplates;
119 };
120
121 } // end anonymous namespace
122
123 /// Determine whether the token kind starts a simple-type-specifier.
124 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
125   switch (Kind) {
126   // FIXME: Take into account the current language when deciding whether a
127   // token kind is a valid type specifier
128   case tok::kw_short:
129   case tok::kw_long:
130   case tok::kw___int64:
131   case tok::kw___int128:
132   case tok::kw_signed:
133   case tok::kw_unsigned:
134   case tok::kw_void:
135   case tok::kw_char:
136   case tok::kw_int:
137   case tok::kw_half:
138   case tok::kw_float:
139   case tok::kw_double:
140   case tok::kw__Float16:
141   case tok::kw___float128:
142   case tok::kw_wchar_t:
143   case tok::kw_bool:
144   case tok::kw___underlying_type:
145   case tok::kw___auto_type:
146     return true;
147
148   case tok::annot_typename:
149   case tok::kw_char16_t:
150   case tok::kw_char32_t:
151   case tok::kw_typeof:
152   case tok::annot_decltype:
153   case tok::kw_decltype:
154     return getLangOpts().CPlusPlus;
155
156   case tok::kw_char8_t:
157     return getLangOpts().Char8;
158
159   default:
160     break;
161   }
162
163   return false;
164 }
165
166 namespace {
167 enum class UnqualifiedTypeNameLookupResult {
168   NotFound,
169   FoundNonType,
170   FoundType
171 };
172 } // end anonymous namespace
173
174 /// Tries to perform unqualified lookup of the type decls in bases for
175 /// dependent class.
176 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177 /// type decl, \a FoundType if only type decls are found.
178 static UnqualifiedTypeNameLookupResult
179 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
180                                 SourceLocation NameLoc,
181                                 const CXXRecordDecl *RD) {
182   if (!RD->hasDefinition())
183     return UnqualifiedTypeNameLookupResult::NotFound;
184   // Look for type decls in base classes.
185   UnqualifiedTypeNameLookupResult FoundTypeDecl =
186       UnqualifiedTypeNameLookupResult::NotFound;
187   for (const auto &Base : RD->bases()) {
188     const CXXRecordDecl *BaseRD = nullptr;
189     if (auto *BaseTT = Base.getType()->getAs<TagType>())
190       BaseRD = BaseTT->getAsCXXRecordDecl();
191     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
192       // Look for type decls in dependent base classes that have known primary
193       // templates.
194       if (!TST || !TST->isDependentType())
195         continue;
196       auto *TD = TST->getTemplateName().getAsTemplateDecl();
197       if (!TD)
198         continue;
199       if (auto *BasePrimaryTemplate =
200           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202           BaseRD = BasePrimaryTemplate;
203         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
204           if (const ClassTemplatePartialSpecializationDecl *PS =
205                   CTD->findPartialSpecialization(Base.getType()))
206             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207               BaseRD = PS;
208         }
209       }
210     }
211     if (BaseRD) {
212       for (NamedDecl *ND : BaseRD->lookup(&II)) {
213         if (!isa<TypeDecl>(ND))
214           return UnqualifiedTypeNameLookupResult::FoundNonType;
215         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216       }
217       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219         case UnqualifiedTypeNameLookupResult::FoundNonType:
220           return UnqualifiedTypeNameLookupResult::FoundNonType;
221         case UnqualifiedTypeNameLookupResult::FoundType:
222           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223           break;
224         case UnqualifiedTypeNameLookupResult::NotFound:
225           break;
226         }
227       }
228     }
229   }
230
231   return FoundTypeDecl;
232 }
233
234 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
235                                                       const IdentifierInfo &II,
236                                                       SourceLocation NameLoc) {
237   // Lookup in the parent class template context, if any.
238   const CXXRecordDecl *RD = nullptr;
239   UnqualifiedTypeNameLookupResult FoundTypeDecl =
240       UnqualifiedTypeNameLookupResult::NotFound;
241   for (DeclContext *DC = S.CurContext;
242        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243        DC = DC->getParent()) {
244     // Look for type decls in dependent base classes that have known primary
245     // templates.
246     RD = dyn_cast<CXXRecordDecl>(DC);
247     if (RD && RD->getDescribedClassTemplate())
248       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249   }
250   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251     return nullptr;
252
253   // We found some types in dependent base classes.  Recover as if the user
254   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
255   // lookup during template instantiation.
256   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
257
258   ASTContext &Context = S.Context;
259   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
260                                           cast<Type>(Context.getRecordType(RD)));
261   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
262
263   CXXScopeSpec SS;
264   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
265
266   TypeLocBuilder Builder;
267   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268   DepTL.setNameLoc(NameLoc);
269   DepTL.setElaboratedKeywordLoc(SourceLocation());
270   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
272 }
273
274 /// If the identifier refers to a type name within this scope,
275 /// return the declaration of that type.
276 ///
277 /// This routine performs ordinary name lookup of the identifier II
278 /// within the given scope, with optional C++ scope specifier SS, to
279 /// determine whether the name refers to a type. If so, returns an
280 /// opaque pointer (actually a QualType) corresponding to that
281 /// type. Otherwise, returns NULL.
282 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
283                              Scope *S, CXXScopeSpec *SS,
284                              bool isClassName, bool HasTrailingDot,
285                              ParsedType ObjectTypePtr,
286                              bool IsCtorOrDtorName,
287                              bool WantNontrivialTypeSourceInfo,
288                              bool IsClassTemplateDeductionContext,
289                              IdentifierInfo **CorrectedII) {
290   // FIXME: Consider allowing this outside C++1z mode as an extension.
291   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
292                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
293                               !isClassName && !HasTrailingDot;
294
295   // Determine where we will perform name lookup.
296   DeclContext *LookupCtx = nullptr;
297   if (ObjectTypePtr) {
298     QualType ObjectType = ObjectTypePtr.get();
299     if (ObjectType->isRecordType())
300       LookupCtx = computeDeclContext(ObjectType);
301   } else if (SS && SS->isNotEmpty()) {
302     LookupCtx = computeDeclContext(*SS, false);
303
304     if (!LookupCtx) {
305       if (isDependentScopeSpecifier(*SS)) {
306         // C++ [temp.res]p3:
307         //   A qualified-id that refers to a type and in which the
308         //   nested-name-specifier depends on a template-parameter (14.6.2)
309         //   shall be prefixed by the keyword typename to indicate that the
310         //   qualified-id denotes a type, forming an
311         //   elaborated-type-specifier (7.1.5.3).
312         //
313         // We therefore do not perform any name lookup if the result would
314         // refer to a member of an unknown specialization.
315         if (!isClassName && !IsCtorOrDtorName)
316           return nullptr;
317
318         // We know from the grammar that this name refers to a type,
319         // so build a dependent node to describe the type.
320         if (WantNontrivialTypeSourceInfo)
321           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
322
323         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
324         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
325                                        II, NameLoc);
326         return ParsedType::make(T);
327       }
328
329       return nullptr;
330     }
331
332     if (!LookupCtx->isDependentContext() &&
333         RequireCompleteDeclContext(*SS, LookupCtx))
334       return nullptr;
335   }
336
337   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
338   // lookup for class-names.
339   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
340                                       LookupOrdinaryName;
341   LookupResult Result(*this, &II, NameLoc, Kind);
342   if (LookupCtx) {
343     // Perform "qualified" name lookup into the declaration context we
344     // computed, which is either the type of the base of a member access
345     // expression or the declaration context associated with a prior
346     // nested-name-specifier.
347     LookupQualifiedName(Result, LookupCtx);
348
349     if (ObjectTypePtr && Result.empty()) {
350       // C++ [basic.lookup.classref]p3:
351       //   If the unqualified-id is ~type-name, the type-name is looked up
352       //   in the context of the entire postfix-expression. If the type T of
353       //   the object expression is of a class type C, the type-name is also
354       //   looked up in the scope of class C. At least one of the lookups shall
355       //   find a name that refers to (possibly cv-qualified) T.
356       LookupName(Result, S);
357     }
358   } else {
359     // Perform unqualified name lookup.
360     LookupName(Result, S);
361
362     // For unqualified lookup in a class template in MSVC mode, look into
363     // dependent base classes where the primary class template is known.
364     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
365       if (ParsedType TypeInBase =
366               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
367         return TypeInBase;
368     }
369   }
370
371   NamedDecl *IIDecl = nullptr;
372   switch (Result.getResultKind()) {
373   case LookupResult::NotFound:
374   case LookupResult::NotFoundInCurrentInstantiation:
375     if (CorrectedII) {
376       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
377                                AllowDeducedTemplate);
378       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
379                                               S, SS, CCC, CTK_ErrorRecovery);
380       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
381       TemplateTy Template;
382       bool MemberOfUnknownSpecialization;
383       UnqualifiedId TemplateName;
384       TemplateName.setIdentifier(NewII, NameLoc);
385       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
386       CXXScopeSpec NewSS, *NewSSPtr = SS;
387       if (SS && NNS) {
388         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
389         NewSSPtr = &NewSS;
390       }
391       if (Correction && (NNS || NewII != &II) &&
392           // Ignore a correction to a template type as the to-be-corrected
393           // identifier is not a template (typo correction for template names
394           // is handled elsewhere).
395           !(getLangOpts().CPlusPlus && NewSSPtr &&
396             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
397                            Template, MemberOfUnknownSpecialization))) {
398         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
399                                     isClassName, HasTrailingDot, ObjectTypePtr,
400                                     IsCtorOrDtorName,
401                                     WantNontrivialTypeSourceInfo,
402                                     IsClassTemplateDeductionContext);
403         if (Ty) {
404           diagnoseTypo(Correction,
405                        PDiag(diag::err_unknown_type_or_class_name_suggest)
406                          << Result.getLookupName() << isClassName);
407           if (SS && NNS)
408             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
409           *CorrectedII = NewII;
410           return Ty;
411         }
412       }
413     }
414     // If typo correction failed or was not performed, fall through
415     LLVM_FALLTHROUGH;
416   case LookupResult::FoundOverloaded:
417   case LookupResult::FoundUnresolvedValue:
418     Result.suppressDiagnostics();
419     return nullptr;
420
421   case LookupResult::Ambiguous:
422     // Recover from type-hiding ambiguities by hiding the type.  We'll
423     // do the lookup again when looking for an object, and we can
424     // diagnose the error then.  If we don't do this, then the error
425     // about hiding the type will be immediately followed by an error
426     // that only makes sense if the identifier was treated like a type.
427     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
428       Result.suppressDiagnostics();
429       return nullptr;
430     }
431
432     // Look to see if we have a type anywhere in the list of results.
433     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
434          Res != ResEnd; ++Res) {
435       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
436           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
437         if (!IIDecl ||
438             (*Res)->getLocation().getRawEncoding() <
439               IIDecl->getLocation().getRawEncoding())
440           IIDecl = *Res;
441       }
442     }
443
444     if (!IIDecl) {
445       // None of the entities we found is a type, so there is no way
446       // to even assume that the result is a type. In this case, don't
447       // complain about the ambiguity. The parser will either try to
448       // perform this lookup again (e.g., as an object name), which
449       // will produce the ambiguity, or will complain that it expected
450       // a type name.
451       Result.suppressDiagnostics();
452       return nullptr;
453     }
454
455     // We found a type within the ambiguous lookup; diagnose the
456     // ambiguity and then return that type. This might be the right
457     // answer, or it might not be, but it suppresses any attempt to
458     // perform the name lookup again.
459     break;
460
461   case LookupResult::Found:
462     IIDecl = Result.getFoundDecl();
463     break;
464   }
465
466   assert(IIDecl && "Didn't find decl");
467
468   QualType T;
469   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470     // C++ [class.qual]p2: A lookup that would find the injected-class-name
471     // instead names the constructors of the class, except when naming a class.
472     // This is ill-formed when we're not actually forming a ctor or dtor name.
473     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476         FoundRD->isInjectedClassName() &&
477         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479           << &II << /*Type*/1;
480
481     DiagnoseUseOfDecl(IIDecl, NameLoc);
482
483     T = Context.getTypeDeclType(TD);
484     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487     if (!HasTrailingDot)
488       T = Context.getObjCInterfaceType(IDecl);
489   } else if (AllowDeducedTemplate) {
490     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492                                                        QualType(), false);
493   }
494
495   if (T.isNull()) {
496     // If it's not plausibly a type, suppress diagnostics.
497     Result.suppressDiagnostics();
498     return nullptr;
499   }
500
501   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502   // constructor or destructor name (in such a case, the scope specifier
503   // will be attached to the enclosing Expr or Decl node).
504   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505       !isa<ObjCInterfaceDecl>(IIDecl)) {
506     if (WantNontrivialTypeSourceInfo) {
507       // Construct a type with type-source information.
508       TypeLocBuilder Builder;
509       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510
511       T = getElaboratedType(ETK_None, *SS, T);
512       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513       ElabTL.setElaboratedKeywordLoc(SourceLocation());
514       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516     } else {
517       T = getElaboratedType(ETK_None, *SS, T);
518     }
519   }
520
521   return ParsedType::make(T);
522 }
523
524 // Builds a fake NNS for the given decl context.
525 static NestedNameSpecifier *
526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527   for (;; DC = DC->getLookupParent()) {
528     DC = DC->getPrimaryContext();
529     auto *ND = dyn_cast<NamespaceDecl>(DC);
530     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531       return NestedNameSpecifier::Create(Context, nullptr, ND);
532     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534                                          RD->getTypeForDecl());
535     else if (isa<TranslationUnitDecl>(DC))
536       return NestedNameSpecifier::GlobalSpecifier(Context);
537   }
538   llvm_unreachable("something isn't in TU scope?");
539 }
540
541 /// Find the parent class with dependent bases of the innermost enclosing method
542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543 /// up allowing unqualified dependent type names at class-level, which MSVC
544 /// correctly rejects.
545 static const CXXRecordDecl *
546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548     DC = DC->getPrimaryContext();
549     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550       if (MD->getParent()->hasAnyDependentBases())
551         return MD->getParent();
552   }
553   return nullptr;
554 }
555
556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557                                           SourceLocation NameLoc,
558                                           bool IsTemplateTypeArg) {
559   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
560
561   NestedNameSpecifier *NNS = nullptr;
562   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563     // If we weren't able to parse a default template argument, delay lookup
564     // until instantiation time by making a non-dependent DependentTypeName. We
565     // pretend we saw a NestedNameSpecifier referring to the current scope, and
566     // lookup is retried.
567     // FIXME: This hurts our diagnostic quality, since we get errors like "no
568     // type named 'Foo' in 'current_namespace'" when the user didn't write any
569     // name specifiers.
570     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572   } else if (const CXXRecordDecl *RD =
573                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574     // Build a DependentNameType that will perform lookup into RD at
575     // instantiation time.
576     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577                                       RD->getTypeForDecl());
578
579     // Diagnose that this identifier was undeclared, and retry the lookup during
580     // template instantiation.
581     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582                                                                       << RD;
583   } else {
584     // This is not a situation that we should recover from.
585     return ParsedType();
586   }
587
588   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589
590   // Build type location information.  We synthesized the qualifier, so we have
591   // to build a fake NestedNameSpecifierLoc.
592   NestedNameSpecifierLocBuilder NNSLocBuilder;
593   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595
596   TypeLocBuilder Builder;
597   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598   DepTL.setNameLoc(NameLoc);
599   DepTL.setElaboratedKeywordLoc(SourceLocation());
600   DepTL.setQualifierLoc(QualifierLoc);
601   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602 }
603
604 /// isTagName() - This method is called *for error recovery purposes only*
605 /// to determine if the specified name is a valid tag name ("struct foo").  If
606 /// so, this returns the TST for the tag corresponding to it (TST_enum,
607 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
608 /// cases in C where the user forgot to specify the tag.
609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610   // Do a tag name lookup in this scope.
611   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612   LookupName(R, S, false);
613   R.suppressDiagnostics();
614   if (R.getResultKind() == LookupResult::Found)
615     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616       switch (TD->getTagKind()) {
617       case TTK_Struct: return DeclSpec::TST_struct;
618       case TTK_Interface: return DeclSpec::TST_interface;
619       case TTK_Union:  return DeclSpec::TST_union;
620       case TTK_Class:  return DeclSpec::TST_class;
621       case TTK_Enum:   return DeclSpec::TST_enum;
622       }
623     }
624
625   return DeclSpec::TST_unspecified;
626 }
627
628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
630 /// then downgrade the missing typename error to a warning.
631 /// This is needed for MSVC compatibility; Example:
632 /// @code
633 /// template<class T> class A {
634 /// public:
635 ///   typedef int TYPE;
636 /// };
637 /// template<class T> class B : public A<T> {
638 /// public:
639 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
640 /// };
641 /// @endcode
642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643   if (CurContext->isRecord()) {
644     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645       return true;
646
647     const Type *Ty = SS->getScopeRep()->getAsType();
648
649     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650     for (const auto &Base : RD->bases())
651       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
652         return true;
653     return S->isFunctionPrototypeScope();
654   }
655   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
656 }
657
658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659                                    SourceLocation IILoc,
660                                    Scope *S,
661                                    CXXScopeSpec *SS,
662                                    ParsedType &SuggestedType,
663                                    bool IsTemplateName) {
664   // Don't report typename errors for editor placeholders.
665   if (II->isEditorPlaceholder())
666     return;
667   // We don't have anything to suggest (yet).
668   SuggestedType = nullptr;
669
670   // There may have been a typo in the name of the type. Look up typo
671   // results, in case we have something that we can suggest.
672   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673                            /*AllowTemplates=*/IsTemplateName,
674                            /*AllowNonTemplates=*/!IsTemplateName);
675   if (TypoCorrection Corrected =
676           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677                       CCC, CTK_ErrorRecovery)) {
678     // FIXME: Support error recovery for the template-name case.
679     bool CanRecover = !IsTemplateName;
680     if (Corrected.isKeyword()) {
681       // We corrected to a keyword.
682       diagnoseTypo(Corrected,
683                    PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                         : diag::err_unknown_typename_suggest)
685                        << II);
686       II = Corrected.getCorrectionAsIdentifierInfo();
687     } else {
688       // We found a similarly-named type or interface; suggest that.
689       if (!SS || !SS->isSet()) {
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName ? diag::err_no_template_suggest
692                                           : diag::err_unknown_typename_suggest)
693                          << II, CanRecover);
694       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697                                 II->getName().equals(CorrectedStr);
698         diagnoseTypo(Corrected,
699                      PDiag(IsTemplateName
700                                ? diag::err_no_member_template_suggest
701                                : diag::err_unknown_nested_typename_suggest)
702                          << II << DC << DroppedSpecifier << SS->getRange(),
703                      CanRecover);
704       } else {
705         llvm_unreachable("could not have corrected a typo here");
706       }
707
708       if (!CanRecover)
709         return;
710
711       CXXScopeSpec tmpSS;
712       if (Corrected.getCorrectionSpecifier())
713         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714                           SourceRange(IILoc));
715       // FIXME: Support class template argument deduction here.
716       SuggestedType =
717           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719                       /*IsCtorOrDtorName=*/false,
720                       /*WantNontrivialTypeSourceInfo=*/true);
721     }
722     return;
723   }
724
725   if (getLangOpts().CPlusPlus && !IsTemplateName) {
726     // See if II is a class template that the user forgot to pass arguments to.
727     UnqualifiedId Name;
728     Name.setIdentifier(II, IILoc);
729     CXXScopeSpec EmptySS;
730     TemplateTy TemplateResult;
731     bool MemberOfUnknownSpecialization;
732     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733                        Name, nullptr, true, TemplateResult,
734                        MemberOfUnknownSpecialization) == TNK_Type_template) {
735       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736       return;
737     }
738   }
739
740   // FIXME: Should we move the logic that tries to recover from a missing tag
741   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742
743   if (!SS || (!SS->isSet() && !SS->isInvalid()))
744     Diag(IILoc, IsTemplateName ? diag::err_no_template
745                                : diag::err_unknown_typename)
746         << II;
747   else if (DeclContext *DC = computeDeclContext(*SS, false))
748     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749                                : diag::err_typename_nested_not_found)
750         << II << DC << SS->getRange();
751   else if (isDependentScopeSpecifier(*SS)) {
752     unsigned DiagID = diag::err_typename_missing;
753     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
754       DiagID = diag::ext_typename_missing;
755
756     Diag(SS->getRange().getBegin(), DiagID)
757       << SS->getScopeRep() << II->getName()
758       << SourceRange(SS->getRange().getBegin(), IILoc)
759       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
760     SuggestedType = ActOnTypenameType(S, SourceLocation(),
761                                       *SS, *II, IILoc).get();
762   } else {
763     assert(SS && SS->isInvalid() &&
764            "Invalid scope specifier has already been diagnosed");
765   }
766 }
767
768 /// Determine whether the given result set contains either a type name
769 /// or
770 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
771   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
772                        NextToken.is(tok::less);
773
774   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
775     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
776       return true;
777
778     if (CheckTemplate && isa<TemplateDecl>(*I))
779       return true;
780   }
781
782   return false;
783 }
784
785 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
786                                     Scope *S, CXXScopeSpec &SS,
787                                     IdentifierInfo *&Name,
788                                     SourceLocation NameLoc) {
789   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
790   SemaRef.LookupParsedName(R, S, &SS);
791   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
792     StringRef FixItTagName;
793     switch (Tag->getTagKind()) {
794       case TTK_Class:
795         FixItTagName = "class ";
796         break;
797
798       case TTK_Enum:
799         FixItTagName = "enum ";
800         break;
801
802       case TTK_Struct:
803         FixItTagName = "struct ";
804         break;
805
806       case TTK_Interface:
807         FixItTagName = "__interface ";
808         break;
809
810       case TTK_Union:
811         FixItTagName = "union ";
812         break;
813     }
814
815     StringRef TagName = FixItTagName.drop_back();
816     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
817       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
818       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
819
820     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
821          I != IEnd; ++I)
822       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
823         << Name << TagName;
824
825     // Replace lookup results with just the tag decl.
826     Result.clear(Sema::LookupTagName);
827     SemaRef.LookupParsedName(Result, S, &SS);
828     return true;
829   }
830
831   return false;
832 }
833
834 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
835 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
836                                   QualType T, SourceLocation NameLoc) {
837   ASTContext &Context = S.Context;
838
839   TypeLocBuilder Builder;
840   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
841
842   T = S.getElaboratedType(ETK_None, SS, T);
843   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
844   ElabTL.setElaboratedKeywordLoc(SourceLocation());
845   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
846   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
847 }
848
849 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
850                                             IdentifierInfo *&Name,
851                                             SourceLocation NameLoc,
852                                             const Token &NextToken,
853                                             CorrectionCandidateCallback *CCC) {
854   DeclarationNameInfo NameInfo(Name, NameLoc);
855   ObjCMethodDecl *CurMethod = getCurMethodDecl();
856
857   assert(NextToken.isNot(tok::coloncolon) &&
858          "parse nested name specifiers before calling ClassifyName");
859   if (getLangOpts().CPlusPlus && SS.isSet() &&
860       isCurrentClassName(*Name, S, &SS)) {
861     // Per [class.qual]p2, this names the constructors of SS, not the
862     // injected-class-name. We don't have a classification for that.
863     // There's not much point caching this result, since the parser
864     // will reject it later.
865     return NameClassification::Unknown();
866   }
867
868   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
869   LookupParsedName(Result, S, &SS, !CurMethod);
870
871   if (SS.isInvalid())
872     return NameClassification::Error();
873
874   // For unqualified lookup in a class template in MSVC mode, look into
875   // dependent base classes where the primary class template is known.
876   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
877     if (ParsedType TypeInBase =
878             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
879       return TypeInBase;
880   }
881
882   // Perform lookup for Objective-C instance variables (including automatically
883   // synthesized instance variables), if we're in an Objective-C method.
884   // FIXME: This lookup really, really needs to be folded in to the normal
885   // unqualified lookup mechanism.
886   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
887     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
888     if (Ivar.isInvalid())
889       return NameClassification::Error();
890     if (Ivar.isUsable())
891       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
892
893     // We defer builtin creation until after ivar lookup inside ObjC methods.
894     if (Result.empty())
895       LookupBuiltin(Result);
896   }
897
898   bool SecondTry = false;
899   bool IsFilteredTemplateName = false;
900
901 Corrected:
902   switch (Result.getResultKind()) {
903   case LookupResult::NotFound:
904     // If an unqualified-id is followed by a '(', then we have a function
905     // call.
906     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
907       // In C++, this is an ADL-only call.
908       // FIXME: Reference?
909       if (getLangOpts().CPlusPlus)
910         return NameClassification::UndeclaredNonType();
911
912       // C90 6.3.2.2:
913       //   If the expression that precedes the parenthesized argument list in a
914       //   function call consists solely of an identifier, and if no
915       //   declaration is visible for this identifier, the identifier is
916       //   implicitly declared exactly as if, in the innermost block containing
917       //   the function call, the declaration
918       //
919       //     extern int identifier ();
920       //
921       //   appeared.
922       //
923       // We also allow this in C99 as an extension.
924       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
925         return NameClassification::NonType(D);
926     }
927
928     if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
929       // In C++20 onwards, this could be an ADL-only call to a function
930       // template, and we're required to assume that this is a template name.
931       //
932       // FIXME: Find a way to still do typo correction in this case.
933       TemplateName Template =
934           Context.getAssumedTemplateName(NameInfo.getName());
935       return NameClassification::UndeclaredTemplate(Template);
936     }
937
938     // In C, we first see whether there is a tag type by the same name, in
939     // which case it's likely that the user just forgot to write "enum",
940     // "struct", or "union".
941     if (!getLangOpts().CPlusPlus && !SecondTry &&
942         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
943       break;
944     }
945
946     // Perform typo correction to determine if there is another name that is
947     // close to this name.
948     if (!SecondTry && CCC) {
949       SecondTry = true;
950       if (TypoCorrection Corrected =
951               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
952                           &SS, *CCC, CTK_ErrorRecovery)) {
953         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
954         unsigned QualifiedDiag = diag::err_no_member_suggest;
955
956         NamedDecl *FirstDecl = Corrected.getFoundDecl();
957         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
958         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
959             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
960           UnqualifiedDiag = diag::err_no_template_suggest;
961           QualifiedDiag = diag::err_no_member_template_suggest;
962         } else if (UnderlyingFirstDecl &&
963                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
964                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
965                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
966           UnqualifiedDiag = diag::err_unknown_typename_suggest;
967           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
968         }
969
970         if (SS.isEmpty()) {
971           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
972         } else {// FIXME: is this even reachable? Test it.
973           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
974           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
975                                   Name->getName().equals(CorrectedStr);
976           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
977                                     << Name << computeDeclContext(SS, false)
978                                     << DroppedSpecifier << SS.getRange());
979         }
980
981         // Update the name, so that the caller has the new name.
982         Name = Corrected.getCorrectionAsIdentifierInfo();
983
984         // Typo correction corrected to a keyword.
985         if (Corrected.isKeyword())
986           return Name;
987
988         // Also update the LookupResult...
989         // FIXME: This should probably go away at some point
990         Result.clear();
991         Result.setLookupName(Corrected.getCorrection());
992         if (FirstDecl)
993           Result.addDecl(FirstDecl);
994
995         // If we found an Objective-C instance variable, let
996         // LookupInObjCMethod build the appropriate expression to
997         // reference the ivar.
998         // FIXME: This is a gross hack.
999         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1000           DeclResult R =
1001               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1002           if (R.isInvalid())
1003             return NameClassification::Error();
1004           if (R.isUsable())
1005             return NameClassification::NonType(Ivar);
1006         }
1007
1008         goto Corrected;
1009       }
1010     }
1011
1012     // We failed to correct; just fall through and let the parser deal with it.
1013     Result.suppressDiagnostics();
1014     return NameClassification::Unknown();
1015
1016   case LookupResult::NotFoundInCurrentInstantiation: {
1017     // We performed name lookup into the current instantiation, and there were
1018     // dependent bases, so we treat this result the same way as any other
1019     // dependent nested-name-specifier.
1020
1021     // C++ [temp.res]p2:
1022     //   A name used in a template declaration or definition and that is
1023     //   dependent on a template-parameter is assumed not to name a type
1024     //   unless the applicable name lookup finds a type name or the name is
1025     //   qualified by the keyword typename.
1026     //
1027     // FIXME: If the next token is '<', we might want to ask the parser to
1028     // perform some heroics to see if we actually have a
1029     // template-argument-list, which would indicate a missing 'template'
1030     // keyword here.
1031     return NameClassification::DependentNonType();
1032   }
1033
1034   case LookupResult::Found:
1035   case LookupResult::FoundOverloaded:
1036   case LookupResult::FoundUnresolvedValue:
1037     break;
1038
1039   case LookupResult::Ambiguous:
1040     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1041         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1042                                       /*AllowDependent=*/false)) {
1043       // C++ [temp.local]p3:
1044       //   A lookup that finds an injected-class-name (10.2) can result in an
1045       //   ambiguity in certain cases (for example, if it is found in more than
1046       //   one base class). If all of the injected-class-names that are found
1047       //   refer to specializations of the same class template, and if the name
1048       //   is followed by a template-argument-list, the reference refers to the
1049       //   class template itself and not a specialization thereof, and is not
1050       //   ambiguous.
1051       //
1052       // This filtering can make an ambiguous result into an unambiguous one,
1053       // so try again after filtering out template names.
1054       FilterAcceptableTemplateNames(Result);
1055       if (!Result.isAmbiguous()) {
1056         IsFilteredTemplateName = true;
1057         break;
1058       }
1059     }
1060
1061     // Diagnose the ambiguity and return an error.
1062     return NameClassification::Error();
1063   }
1064
1065   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1066       (IsFilteredTemplateName ||
1067        hasAnyAcceptableTemplateNames(
1068            Result, /*AllowFunctionTemplates=*/true,
1069            /*AllowDependent=*/false,
1070            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1071                getLangOpts().CPlusPlus2a))) {
1072     // C++ [temp.names]p3:
1073     //   After name lookup (3.4) finds that a name is a template-name or that
1074     //   an operator-function-id or a literal- operator-id refers to a set of
1075     //   overloaded functions any member of which is a function template if
1076     //   this is followed by a <, the < is always taken as the delimiter of a
1077     //   template-argument-list and never as the less-than operator.
1078     // C++2a [temp.names]p2:
1079     //   A name is also considered to refer to a template if it is an
1080     //   unqualified-id followed by a < and name lookup finds either one
1081     //   or more functions or finds nothing.
1082     if (!IsFilteredTemplateName)
1083       FilterAcceptableTemplateNames(Result);
1084
1085     bool IsFunctionTemplate;
1086     bool IsVarTemplate;
1087     TemplateName Template;
1088     if (Result.end() - Result.begin() > 1) {
1089       IsFunctionTemplate = true;
1090       Template = Context.getOverloadedTemplateName(Result.begin(),
1091                                                    Result.end());
1092     } else if (!Result.empty()) {
1093       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1094           *Result.begin(), /*AllowFunctionTemplates=*/true,
1095           /*AllowDependent=*/false));
1096       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1097       IsVarTemplate = isa<VarTemplateDecl>(TD);
1098
1099       if (SS.isNotEmpty())
1100         Template =
1101             Context.getQualifiedTemplateName(SS.getScopeRep(),
1102                                              /*TemplateKeyword=*/false, TD);
1103       else
1104         Template = TemplateName(TD);
1105     } else {
1106       // All results were non-template functions. This is a function template
1107       // name.
1108       IsFunctionTemplate = true;
1109       Template = Context.getAssumedTemplateName(NameInfo.getName());
1110     }
1111
1112     if (IsFunctionTemplate) {
1113       // Function templates always go through overload resolution, at which
1114       // point we'll perform the various checks (e.g., accessibility) we need
1115       // to based on which function we selected.
1116       Result.suppressDiagnostics();
1117
1118       return NameClassification::FunctionTemplate(Template);
1119     }
1120
1121     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1122                          : NameClassification::TypeTemplate(Template);
1123   }
1124
1125   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1126   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1127     DiagnoseUseOfDecl(Type, NameLoc);
1128     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1129     QualType T = Context.getTypeDeclType(Type);
1130     if (SS.isNotEmpty())
1131       return buildNestedType(*this, SS, T, NameLoc);
1132     return ParsedType::make(T);
1133   }
1134
1135   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1136   if (!Class) {
1137     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1138     if (ObjCCompatibleAliasDecl *Alias =
1139             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1140       Class = Alias->getClassInterface();
1141   }
1142
1143   if (Class) {
1144     DiagnoseUseOfDecl(Class, NameLoc);
1145
1146     if (NextToken.is(tok::period)) {
1147       // Interface. <something> is parsed as a property reference expression.
1148       // Just return "unknown" as a fall-through for now.
1149       Result.suppressDiagnostics();
1150       return NameClassification::Unknown();
1151     }
1152
1153     QualType T = Context.getObjCInterfaceType(Class);
1154     return ParsedType::make(T);
1155   }
1156
1157   if (isa<ConceptDecl>(FirstDecl))
1158     return NameClassification::Concept(
1159         TemplateName(cast<TemplateDecl>(FirstDecl)));
1160
1161   // We can have a type template here if we're classifying a template argument.
1162   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1163       !isa<VarTemplateDecl>(FirstDecl))
1164     return NameClassification::TypeTemplate(
1165         TemplateName(cast<TemplateDecl>(FirstDecl)));
1166
1167   // Check for a tag type hidden by a non-type decl in a few cases where it
1168   // seems likely a type is wanted instead of the non-type that was found.
1169   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1170   if ((NextToken.is(tok::identifier) ||
1171        (NextIsOp &&
1172         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1173       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1174     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1175     DiagnoseUseOfDecl(Type, NameLoc);
1176     QualType T = Context.getTypeDeclType(Type);
1177     if (SS.isNotEmpty())
1178       return buildNestedType(*this, SS, T, NameLoc);
1179     return ParsedType::make(T);
1180   }
1181
1182   // FIXME: This is context-dependent. We need to defer building the member
1183   // expression until the classification is consumed.
1184   if (FirstDecl->isCXXClassMember())
1185     return NameClassification::ContextIndependentExpr(
1186         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1187                                         S));
1188
1189   // If we already know which single declaration is referenced, just annotate
1190   // that declaration directly.
1191   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192   if (Result.isSingleResult() && !ADL)
1193     return NameClassification::NonType(Result.getRepresentativeDecl());
1194
1195   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1196   // context in which we performed classification, so it's safe to do now.
1197   return NameClassification::ContextIndependentExpr(
1198       BuildDeclarationNameExpr(SS, Result, ADL));
1199 }
1200
1201 ExprResult
1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203                                              SourceLocation NameLoc) {
1204   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1205   CXXScopeSpec SS;
1206   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208 }
1209
1210 ExprResult
1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212                                             IdentifierInfo *Name,
1213                                             SourceLocation NameLoc,
1214                                             bool IsAddressOfOperand) {
1215   DeclarationNameInfo NameInfo(Name, NameLoc);
1216   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217                                     NameInfo, IsAddressOfOperand,
1218                                     /*TemplateArgs=*/nullptr);
1219 }
1220
1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222                                               NamedDecl *Found,
1223                                               SourceLocation NameLoc,
1224                                               const Token &NextToken) {
1225   if (getCurMethodDecl() && SS.isEmpty())
1226     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227       return BuildIvarRefExpr(S, NameLoc, Ivar);
1228
1229   // Reconstruct the lookup result.
1230   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231   Result.addDecl(Found);
1232   Result.resolveKind();
1233
1234   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235   return BuildDeclarationNameExpr(SS, Result, ADL);
1236 }
1237
1238 Sema::TemplateNameKindForDiagnostics
1239 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1240   auto *TD = Name.getAsTemplateDecl();
1241   if (!TD)
1242     return TemplateNameKindForDiagnostics::DependentTemplate;
1243   if (isa<ClassTemplateDecl>(TD))
1244     return TemplateNameKindForDiagnostics::ClassTemplate;
1245   if (isa<FunctionTemplateDecl>(TD))
1246     return TemplateNameKindForDiagnostics::FunctionTemplate;
1247   if (isa<VarTemplateDecl>(TD))
1248     return TemplateNameKindForDiagnostics::VarTemplate;
1249   if (isa<TypeAliasTemplateDecl>(TD))
1250     return TemplateNameKindForDiagnostics::AliasTemplate;
1251   if (isa<TemplateTemplateParmDecl>(TD))
1252     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1253   if (isa<ConceptDecl>(TD))
1254     return TemplateNameKindForDiagnostics::Concept;
1255   return TemplateNameKindForDiagnostics::DependentTemplate;
1256 }
1257
1258 // Determines the context to return to after temporarily entering a
1259 // context.  This depends in an unnecessarily complicated way on the
1260 // exact ordering of callbacks from the parser.
1261 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1262
1263   // Functions defined inline within classes aren't parsed until we've
1264   // finished parsing the top-level class, so the top-level class is
1265   // the context we'll need to return to.
1266   // A Lambda call operator whose parent is a class must not be treated
1267   // as an inline member function.  A Lambda can be used legally
1268   // either as an in-class member initializer or a default argument.  These
1269   // are parsed once the class has been marked complete and so the containing
1270   // context would be the nested class (when the lambda is defined in one);
1271   // If the class is not complete, then the lambda is being used in an
1272   // ill-formed fashion (such as to specify the width of a bit-field, or
1273   // in an array-bound) - in which case we still want to return the
1274   // lexically containing DC (which could be a nested class).
1275   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1276     DC = DC->getLexicalParent();
1277
1278     // A function not defined within a class will always return to its
1279     // lexical context.
1280     if (!isa<CXXRecordDecl>(DC))
1281       return DC;
1282
1283     // A C++ inline method/friend is parsed *after* the topmost class
1284     // it was declared in is fully parsed ("complete");  the topmost
1285     // class is the context we need to return to.
1286     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1287       DC = RD;
1288
1289     // Return the declaration context of the topmost class the inline method is
1290     // declared in.
1291     return DC;
1292   }
1293
1294   return DC->getLexicalParent();
1295 }
1296
1297 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1298   assert(getContainingDC(DC) == CurContext &&
1299       "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = DC;
1301   S->setEntity(DC);
1302 }
1303
1304 void Sema::PopDeclContext() {
1305   assert(CurContext && "DeclContext imbalance!");
1306
1307   CurContext = getContainingDC(CurContext);
1308   assert(CurContext && "Popped translation unit!");
1309 }
1310
1311 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1312                                                                     Decl *D) {
1313   // Unlike PushDeclContext, the context to which we return is not necessarily
1314   // the containing DC of TD, because the new context will be some pre-existing
1315   // TagDecl definition instead of a fresh one.
1316   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1317   CurContext = cast<TagDecl>(D)->getDefinition();
1318   assert(CurContext && "skipping definition of undefined tag");
1319   // Start lookups from the parent of the current context; we don't want to look
1320   // into the pre-existing complete definition.
1321   S->setEntity(CurContext->getLookupParent());
1322   return Result;
1323 }
1324
1325 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1326   CurContext = static_cast<decltype(CurContext)>(Context);
1327 }
1328
1329 /// EnterDeclaratorContext - Used when we must lookup names in the context
1330 /// of a declarator's nested name specifier.
1331 ///
1332 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1333   // C++0x [basic.lookup.unqual]p13:
1334   //   A name used in the definition of a static data member of class
1335   //   X (after the qualified-id of the static member) is looked up as
1336   //   if the name was used in a member function of X.
1337   // C++0x [basic.lookup.unqual]p14:
1338   //   If a variable member of a namespace is defined outside of the
1339   //   scope of its namespace then any name used in the definition of
1340   //   the variable member (after the declarator-id) is looked up as
1341   //   if the definition of the variable member occurred in its
1342   //   namespace.
1343   // Both of these imply that we should push a scope whose context
1344   // is the semantic context of the declaration.  We can't use
1345   // PushDeclContext here because that context is not necessarily
1346   // lexically contained in the current context.  Fortunately,
1347   // the containing scope should have the appropriate information.
1348
1349   assert(!S->getEntity() && "scope already has entity");
1350
1351 #ifndef NDEBUG
1352   Scope *Ancestor = S->getParent();
1353   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1354   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1355 #endif
1356
1357   CurContext = DC;
1358   S->setEntity(DC);
1359 }
1360
1361 void Sema::ExitDeclaratorContext(Scope *S) {
1362   assert(S->getEntity() == CurContext && "Context imbalance!");
1363
1364   // Switch back to the lexical context.  The safety of this is
1365   // enforced by an assert in EnterDeclaratorContext.
1366   Scope *Ancestor = S->getParent();
1367   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1368   CurContext = Ancestor->getEntity();
1369
1370   // We don't need to do anything with the scope, which is going to
1371   // disappear.
1372 }
1373
1374 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1375   // We assume that the caller has already called
1376   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1377   FunctionDecl *FD = D->getAsFunction();
1378   if (!FD)
1379     return;
1380
1381   // Same implementation as PushDeclContext, but enters the context
1382   // from the lexical parent, rather than the top-level class.
1383   assert(CurContext == FD->getLexicalParent() &&
1384     "The next DeclContext should be lexically contained in the current one.");
1385   CurContext = FD;
1386   S->setEntity(CurContext);
1387
1388   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1389     ParmVarDecl *Param = FD->getParamDecl(P);
1390     // If the parameter has an identifier, then add it to the scope
1391     if (Param->getIdentifier()) {
1392       S->AddDecl(Param);
1393       IdResolver.AddDecl(Param);
1394     }
1395   }
1396 }
1397
1398 void Sema::ActOnExitFunctionContext() {
1399   // Same implementation as PopDeclContext, but returns to the lexical parent,
1400   // rather than the top-level class.
1401   assert(CurContext && "DeclContext imbalance!");
1402   CurContext = CurContext->getLexicalParent();
1403   assert(CurContext && "Popped translation unit!");
1404 }
1405
1406 /// Determine whether we allow overloading of the function
1407 /// PrevDecl with another declaration.
1408 ///
1409 /// This routine determines whether overloading is possible, not
1410 /// whether some new function is actually an overload. It will return
1411 /// true in C++ (where we can always provide overloads) or, as an
1412 /// extension, in C when the previous function is already an
1413 /// overloaded function declaration or has the "overloadable"
1414 /// attribute.
1415 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1416                                        ASTContext &Context,
1417                                        const FunctionDecl *New) {
1418   if (Context.getLangOpts().CPlusPlus)
1419     return true;
1420
1421   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1422     return true;
1423
1424   return Previous.getResultKind() == LookupResult::Found &&
1425          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1426           New->hasAttr<OverloadableAttr>());
1427 }
1428
1429 /// Add this decl to the scope shadowed decl chains.
1430 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1431   // Move up the scope chain until we find the nearest enclosing
1432   // non-transparent context. The declaration will be introduced into this
1433   // scope.
1434   while (S->getEntity() && S->getEntity()->isTransparentContext())
1435     S = S->getParent();
1436
1437   // Add scoped declarations into their context, so that they can be
1438   // found later. Declarations without a context won't be inserted
1439   // into any context.
1440   if (AddToContext)
1441     CurContext->addDecl(D);
1442
1443   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1444   // are function-local declarations.
1445   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1446       !D->getDeclContext()->getRedeclContext()->Equals(
1447         D->getLexicalDeclContext()->getRedeclContext()) &&
1448       !D->getLexicalDeclContext()->isFunctionOrMethod())
1449     return;
1450
1451   // Template instantiations should also not be pushed into scope.
1452   if (isa<FunctionDecl>(D) &&
1453       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1454     return;
1455
1456   // If this replaces anything in the current scope,
1457   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1458                                IEnd = IdResolver.end();
1459   for (; I != IEnd; ++I) {
1460     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1461       S->RemoveDecl(*I);
1462       IdResolver.RemoveDecl(*I);
1463
1464       // Should only need to replace one decl.
1465       break;
1466     }
1467   }
1468
1469   S->AddDecl(D);
1470
1471   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1472     // Implicitly-generated labels may end up getting generated in an order that
1473     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1474     // the label at the appropriate place in the identifier chain.
1475     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1476       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1477       if (IDC == CurContext) {
1478         if (!S->isDeclScope(*I))
1479           continue;
1480       } else if (IDC->Encloses(CurContext))
1481         break;
1482     }
1483
1484     IdResolver.InsertDeclAfter(I, D);
1485   } else {
1486     IdResolver.AddDecl(D);
1487   }
1488 }
1489
1490 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1491                          bool AllowInlineNamespace) {
1492   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1493 }
1494
1495 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1496   DeclContext *TargetDC = DC->getPrimaryContext();
1497   do {
1498     if (DeclContext *ScopeDC = S->getEntity())
1499       if (ScopeDC->getPrimaryContext() == TargetDC)
1500         return S;
1501   } while ((S = S->getParent()));
1502
1503   return nullptr;
1504 }
1505
1506 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1507                                             DeclContext*,
1508                                             ASTContext&);
1509
1510 /// Filters out lookup results that don't fall within the given scope
1511 /// as determined by isDeclInScope.
1512 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1513                                 bool ConsiderLinkage,
1514                                 bool AllowInlineNamespace) {
1515   LookupResult::Filter F = R.makeFilter();
1516   while (F.hasNext()) {
1517     NamedDecl *D = F.next();
1518
1519     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1520       continue;
1521
1522     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1523       continue;
1524
1525     F.erase();
1526   }
1527
1528   F.done();
1529 }
1530
1531 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1532 /// have compatible owning modules.
1533 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1534   // FIXME: The Modules TS is not clear about how friend declarations are
1535   // to be treated. It's not meaningful to have different owning modules for
1536   // linkage in redeclarations of the same entity, so for now allow the
1537   // redeclaration and change the owning modules to match.
1538   if (New->getFriendObjectKind() &&
1539       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1540     New->setLocalOwningModule(Old->getOwningModule());
1541     makeMergedDefinitionVisible(New);
1542     return false;
1543   }
1544
1545   Module *NewM = New->getOwningModule();
1546   Module *OldM = Old->getOwningModule();
1547
1548   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1549     NewM = NewM->Parent;
1550   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1551     OldM = OldM->Parent;
1552
1553   if (NewM == OldM)
1554     return false;
1555
1556   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1557   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1558   if (NewIsModuleInterface || OldIsModuleInterface) {
1559     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1560     //   if a declaration of D [...] appears in the purview of a module, all
1561     //   other such declarations shall appear in the purview of the same module
1562     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1563       << New
1564       << NewIsModuleInterface
1565       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1566       << OldIsModuleInterface
1567       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1568     Diag(Old->getLocation(), diag::note_previous_declaration);
1569     New->setInvalidDecl();
1570     return true;
1571   }
1572
1573   return false;
1574 }
1575
1576 static bool isUsingDecl(NamedDecl *D) {
1577   return isa<UsingShadowDecl>(D) ||
1578          isa<UnresolvedUsingTypenameDecl>(D) ||
1579          isa<UnresolvedUsingValueDecl>(D);
1580 }
1581
1582 /// Removes using shadow declarations from the lookup results.
1583 static void RemoveUsingDecls(LookupResult &R) {
1584   LookupResult::Filter F = R.makeFilter();
1585   while (F.hasNext())
1586     if (isUsingDecl(F.next()))
1587       F.erase();
1588
1589   F.done();
1590 }
1591
1592 /// Check for this common pattern:
1593 /// @code
1594 /// class S {
1595 ///   S(const S&); // DO NOT IMPLEMENT
1596 ///   void operator=(const S&); // DO NOT IMPLEMENT
1597 /// };
1598 /// @endcode
1599 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1600   // FIXME: Should check for private access too but access is set after we get
1601   // the decl here.
1602   if (D->doesThisDeclarationHaveABody())
1603     return false;
1604
1605   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1606     return CD->isCopyConstructor();
1607   return D->isCopyAssignmentOperator();
1608 }
1609
1610 // We need this to handle
1611 //
1612 // typedef struct {
1613 //   void *foo() { return 0; }
1614 // } A;
1615 //
1616 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1617 // for example. If 'A', foo will have external linkage. If we have '*A',
1618 // foo will have no linkage. Since we can't know until we get to the end
1619 // of the typedef, this function finds out if D might have non-external linkage.
1620 // Callers should verify at the end of the TU if it D has external linkage or
1621 // not.
1622 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1623   const DeclContext *DC = D->getDeclContext();
1624   while (!DC->isTranslationUnit()) {
1625     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1626       if (!RD->hasNameForLinkage())
1627         return true;
1628     }
1629     DC = DC->getParent();
1630   }
1631
1632   return !D->isExternallyVisible();
1633 }
1634
1635 // FIXME: This needs to be refactored; some other isInMainFile users want
1636 // these semantics.
1637 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1638   if (S.TUKind != TU_Complete)
1639     return false;
1640   return S.SourceMgr.isInMainFile(Loc);
1641 }
1642
1643 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1644   assert(D);
1645
1646   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1647     return false;
1648
1649   // Ignore all entities declared within templates, and out-of-line definitions
1650   // of members of class templates.
1651   if (D->getDeclContext()->isDependentContext() ||
1652       D->getLexicalDeclContext()->isDependentContext())
1653     return false;
1654
1655   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1656     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1657       return false;
1658     // A non-out-of-line declaration of a member specialization was implicitly
1659     // instantiated; it's the out-of-line declaration that we're interested in.
1660     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1661         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1662       return false;
1663
1664     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1665       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1666         return false;
1667     } else {
1668       // 'static inline' functions are defined in headers; don't warn.
1669       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1670         return false;
1671     }
1672
1673     if (FD->doesThisDeclarationHaveABody() &&
1674         Context.DeclMustBeEmitted(FD))
1675       return false;
1676   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1677     // Constants and utility variables are defined in headers with internal
1678     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1679     // like "inline".)
1680     if (!isMainFileLoc(*this, VD->getLocation()))
1681       return false;
1682
1683     if (Context.DeclMustBeEmitted(VD))
1684       return false;
1685
1686     if (VD->isStaticDataMember() &&
1687         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688       return false;
1689     if (VD->isStaticDataMember() &&
1690         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1691         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1692       return false;
1693
1694     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1695       return false;
1696   } else {
1697     return false;
1698   }
1699
1700   // Only warn for unused decls internal to the translation unit.
1701   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1702   // for inline functions defined in the main source file, for instance.
1703   return mightHaveNonExternalLinkage(D);
1704 }
1705
1706 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1707   if (!D)
1708     return;
1709
1710   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1711     const FunctionDecl *First = FD->getFirstDecl();
1712     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1713       return; // First should already be in the vector.
1714   }
1715
1716   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1717     const VarDecl *First = VD->getFirstDecl();
1718     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1719       return; // First should already be in the vector.
1720   }
1721
1722   if (ShouldWarnIfUnusedFileScopedDecl(D))
1723     UnusedFileScopedDecls.push_back(D);
1724 }
1725
1726 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1727   if (D->isInvalidDecl())
1728     return false;
1729
1730   bool Referenced = false;
1731   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1732     // For a decomposition declaration, warn if none of the bindings are
1733     // referenced, instead of if the variable itself is referenced (which
1734     // it is, by the bindings' expressions).
1735     for (auto *BD : DD->bindings()) {
1736       if (BD->isReferenced()) {
1737         Referenced = true;
1738         break;
1739       }
1740     }
1741   } else if (!D->getDeclName()) {
1742     return false;
1743   } else if (D->isReferenced() || D->isUsed()) {
1744     Referenced = true;
1745   }
1746
1747   if (Referenced || D->hasAttr<UnusedAttr>() ||
1748       D->hasAttr<ObjCPreciseLifetimeAttr>())
1749     return false;
1750
1751   if (isa<LabelDecl>(D))
1752     return true;
1753
1754   // Except for labels, we only care about unused decls that are local to
1755   // functions.
1756   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1757   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1758     // For dependent types, the diagnostic is deferred.
1759     WithinFunction =
1760         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1761   if (!WithinFunction)
1762     return false;
1763
1764   if (isa<TypedefNameDecl>(D))
1765     return true;
1766
1767   // White-list anything that isn't a local variable.
1768   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1769     return false;
1770
1771   // Types of valid local variables should be complete, so this should succeed.
1772   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1773
1774     // White-list anything with an __attribute__((unused)) type.
1775     const auto *Ty = VD->getType().getTypePtr();
1776
1777     // Only look at the outermost level of typedef.
1778     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1779       if (TT->getDecl()->hasAttr<UnusedAttr>())
1780         return false;
1781     }
1782
1783     // If we failed to complete the type for some reason, or if the type is
1784     // dependent, don't diagnose the variable.
1785     if (Ty->isIncompleteType() || Ty->isDependentType())
1786       return false;
1787
1788     // Look at the element type to ensure that the warning behaviour is
1789     // consistent for both scalars and arrays.
1790     Ty = Ty->getBaseElementTypeUnsafe();
1791
1792     if (const TagType *TT = Ty->getAs<TagType>()) {
1793       const TagDecl *Tag = TT->getDecl();
1794       if (Tag->hasAttr<UnusedAttr>())
1795         return false;
1796
1797       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1798         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1799           return false;
1800
1801         if (const Expr *Init = VD->getInit()) {
1802           if (const ExprWithCleanups *Cleanups =
1803                   dyn_cast<ExprWithCleanups>(Init))
1804             Init = Cleanups->getSubExpr();
1805           const CXXConstructExpr *Construct =
1806             dyn_cast<CXXConstructExpr>(Init);
1807           if (Construct && !Construct->isElidable()) {
1808             CXXConstructorDecl *CD = Construct->getConstructor();
1809             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1810                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1811               return false;
1812           }
1813
1814           // Suppress the warning if we don't know how this is constructed, and
1815           // it could possibly be non-trivial constructor.
1816           if (Init->isTypeDependent())
1817             for (const CXXConstructorDecl *Ctor : RD->ctors())
1818               if (!Ctor->isTrivial())
1819                 return false;
1820         }
1821       }
1822     }
1823
1824     // TODO: __attribute__((unused)) templates?
1825   }
1826
1827   return true;
1828 }
1829
1830 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1831                                      FixItHint &Hint) {
1832   if (isa<LabelDecl>(D)) {
1833     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1834         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1835         true);
1836     if (AfterColon.isInvalid())
1837       return;
1838     Hint = FixItHint::CreateRemoval(
1839         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1840   }
1841 }
1842
1843 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1844   if (D->getTypeForDecl()->isDependentType())
1845     return;
1846
1847   for (auto *TmpD : D->decls()) {
1848     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1849       DiagnoseUnusedDecl(T);
1850     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1851       DiagnoseUnusedNestedTypedefs(R);
1852   }
1853 }
1854
1855 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1856 /// unless they are marked attr(unused).
1857 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1858   if (!ShouldDiagnoseUnusedDecl(D))
1859     return;
1860
1861   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1862     // typedefs can be referenced later on, so the diagnostics are emitted
1863     // at end-of-translation-unit.
1864     UnusedLocalTypedefNameCandidates.insert(TD);
1865     return;
1866   }
1867
1868   FixItHint Hint;
1869   GenerateFixForUnusedDecl(D, Context, Hint);
1870
1871   unsigned DiagID;
1872   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1873     DiagID = diag::warn_unused_exception_param;
1874   else if (isa<LabelDecl>(D))
1875     DiagID = diag::warn_unused_label;
1876   else
1877     DiagID = diag::warn_unused_variable;
1878
1879   Diag(D->getLocation(), DiagID) << D << Hint;
1880 }
1881
1882 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1883   // Verify that we have no forward references left.  If so, there was a goto
1884   // or address of a label taken, but no definition of it.  Label fwd
1885   // definitions are indicated with a null substmt which is also not a resolved
1886   // MS inline assembly label name.
1887   bool Diagnose = false;
1888   if (L->isMSAsmLabel())
1889     Diagnose = !L->isResolvedMSAsmLabel();
1890   else
1891     Diagnose = L->getStmt() == nullptr;
1892   if (Diagnose)
1893     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1894 }
1895
1896 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1897   S->mergeNRVOIntoParent();
1898
1899   if (S->decl_empty()) return;
1900   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1901          "Scope shouldn't contain decls!");
1902
1903   for (auto *TmpD : S->decls()) {
1904     assert(TmpD && "This decl didn't get pushed??");
1905
1906     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1907     NamedDecl *D = cast<NamedDecl>(TmpD);
1908
1909     // Diagnose unused variables in this scope.
1910     if (!S->hasUnrecoverableErrorOccurred()) {
1911       DiagnoseUnusedDecl(D);
1912       if (const auto *RD = dyn_cast<RecordDecl>(D))
1913         DiagnoseUnusedNestedTypedefs(RD);
1914     }
1915
1916     if (!D->getDeclName()) continue;
1917
1918     // If this was a forward reference to a label, verify it was defined.
1919     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1920       CheckPoppedLabel(LD, *this);
1921
1922     // Remove this name from our lexical scope, and warn on it if we haven't
1923     // already.
1924     IdResolver.RemoveDecl(D);
1925     auto ShadowI = ShadowingDecls.find(D);
1926     if (ShadowI != ShadowingDecls.end()) {
1927       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1928         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1929             << D << FD << FD->getParent();
1930         Diag(FD->getLocation(), diag::note_previous_declaration);
1931       }
1932       ShadowingDecls.erase(ShadowI);
1933     }
1934   }
1935 }
1936
1937 /// Look for an Objective-C class in the translation unit.
1938 ///
1939 /// \param Id The name of the Objective-C class we're looking for. If
1940 /// typo-correction fixes this name, the Id will be updated
1941 /// to the fixed name.
1942 ///
1943 /// \param IdLoc The location of the name in the translation unit.
1944 ///
1945 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1946 /// if there is no class with the given name.
1947 ///
1948 /// \returns The declaration of the named Objective-C class, or NULL if the
1949 /// class could not be found.
1950 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1951                                               SourceLocation IdLoc,
1952                                               bool DoTypoCorrection) {
1953   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1954   // creation from this context.
1955   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1956
1957   if (!IDecl && DoTypoCorrection) {
1958     // Perform typo correction at the given location, but only if we
1959     // find an Objective-C class name.
1960     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1961     if (TypoCorrection C =
1962             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1963                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1964       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1965       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1966       Id = IDecl->getIdentifier();
1967     }
1968   }
1969   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1970   // This routine must always return a class definition, if any.
1971   if (Def && Def->getDefinition())
1972       Def = Def->getDefinition();
1973   return Def;
1974 }
1975
1976 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1977 /// from S, where a non-field would be declared. This routine copes
1978 /// with the difference between C and C++ scoping rules in structs and
1979 /// unions. For example, the following code is well-formed in C but
1980 /// ill-formed in C++:
1981 /// @code
1982 /// struct S6 {
1983 ///   enum { BAR } e;
1984 /// };
1985 ///
1986 /// void test_S6() {
1987 ///   struct S6 a;
1988 ///   a.e = BAR;
1989 /// }
1990 /// @endcode
1991 /// For the declaration of BAR, this routine will return a different
1992 /// scope. The scope S will be the scope of the unnamed enumeration
1993 /// within S6. In C++, this routine will return the scope associated
1994 /// with S6, because the enumeration's scope is a transparent
1995 /// context but structures can contain non-field names. In C, this
1996 /// routine will return the translation unit scope, since the
1997 /// enumeration's scope is a transparent context and structures cannot
1998 /// contain non-field names.
1999 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2000   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2001          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2002          (S->isClassScope() && !getLangOpts().CPlusPlus))
2003     S = S->getParent();
2004   return S;
2005 }
2006
2007 /// Looks up the declaration of "struct objc_super" and
2008 /// saves it for later use in building builtin declaration of
2009 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2010 /// pre-existing declaration exists no action takes place.
2011 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2012                                         IdentifierInfo *II) {
2013   if (!II->isStr("objc_msgSendSuper"))
2014     return;
2015   ASTContext &Context = ThisSema.Context;
2016
2017   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2018                       SourceLocation(), Sema::LookupTagName);
2019   ThisSema.LookupName(Result, S);
2020   if (Result.getResultKind() == LookupResult::Found)
2021     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2022       Context.setObjCSuperType(Context.getTagDeclType(TD));
2023 }
2024
2025 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2026                                ASTContext::GetBuiltinTypeError Error) {
2027   switch (Error) {
2028   case ASTContext::GE_None:
2029     return "";
2030   case ASTContext::GE_Missing_type:
2031     return BuiltinInfo.getHeaderName(ID);
2032   case ASTContext::GE_Missing_stdio:
2033     return "stdio.h";
2034   case ASTContext::GE_Missing_setjmp:
2035     return "setjmp.h";
2036   case ASTContext::GE_Missing_ucontext:
2037     return "ucontext.h";
2038   }
2039   llvm_unreachable("unhandled error kind");
2040 }
2041
2042 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2043 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2044 /// if we're creating this built-in in anticipation of redeclaring the
2045 /// built-in.
2046 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2047                                      Scope *S, bool ForRedeclaration,
2048                                      SourceLocation Loc) {
2049   LookupPredefedObjCSuperType(*this, S, II);
2050
2051   ASTContext::GetBuiltinTypeError Error;
2052   QualType R = Context.GetBuiltinType(ID, Error);
2053   if (Error) {
2054     if (!ForRedeclaration)
2055       return nullptr;
2056
2057     // If we have a builtin without an associated type we should not emit a
2058     // warning when we were not able to find a type for it.
2059     if (Error == ASTContext::GE_Missing_type)
2060       return nullptr;
2061
2062     // If we could not find a type for setjmp it is because the jmp_buf type was
2063     // not defined prior to the setjmp declaration.
2064     if (Error == ASTContext::GE_Missing_setjmp) {
2065       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2066           << Context.BuiltinInfo.getName(ID);
2067       return nullptr;
2068     }
2069
2070     // Generally, we emit a warning that the declaration requires the
2071     // appropriate header.
2072     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2073         << getHeaderName(Context.BuiltinInfo, ID, Error)
2074         << Context.BuiltinInfo.getName(ID);
2075     return nullptr;
2076   }
2077
2078   if (!ForRedeclaration &&
2079       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2080        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2081     Diag(Loc, diag::ext_implicit_lib_function_decl)
2082         << Context.BuiltinInfo.getName(ID) << R;
2083     if (Context.BuiltinInfo.getHeaderName(ID) &&
2084         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2085       Diag(Loc, diag::note_include_header_or_declare)
2086           << Context.BuiltinInfo.getHeaderName(ID)
2087           << Context.BuiltinInfo.getName(ID);
2088   }
2089
2090   if (R.isNull())
2091     return nullptr;
2092
2093   DeclContext *Parent = Context.getTranslationUnitDecl();
2094   if (getLangOpts().CPlusPlus) {
2095     LinkageSpecDecl *CLinkageDecl =
2096         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2097                                 LinkageSpecDecl::lang_c, false);
2098     CLinkageDecl->setImplicit();
2099     Parent->addDecl(CLinkageDecl);
2100     Parent = CLinkageDecl;
2101   }
2102
2103   FunctionDecl *New = FunctionDecl::Create(Context,
2104                                            Parent,
2105                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2106                                            SC_Extern,
2107                                            false,
2108                                            R->isFunctionProtoType());
2109   New->setImplicit();
2110
2111   // Create Decl objects for each parameter, adding them to the
2112   // FunctionDecl.
2113   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2114     SmallVector<ParmVarDecl*, 16> Params;
2115     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2116       ParmVarDecl *parm =
2117           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2118                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2119                               SC_None, nullptr);
2120       parm->setScopeInfo(0, i);
2121       Params.push_back(parm);
2122     }
2123     New->setParams(Params);
2124   }
2125
2126   AddKnownFunctionAttributes(New);
2127   RegisterLocallyScopedExternCDecl(New, S);
2128
2129   // TUScope is the translation-unit scope to insert this function into.
2130   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2131   // relate Scopes to DeclContexts, and probably eliminate CurContext
2132   // entirely, but we're not there yet.
2133   DeclContext *SavedContext = CurContext;
2134   CurContext = Parent;
2135   PushOnScopeChains(New, TUScope);
2136   CurContext = SavedContext;
2137   return New;
2138 }
2139
2140 /// Typedef declarations don't have linkage, but they still denote the same
2141 /// entity if their types are the same.
2142 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2143 /// isSameEntity.
2144 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2145                                                      TypedefNameDecl *Decl,
2146                                                      LookupResult &Previous) {
2147   // This is only interesting when modules are enabled.
2148   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2149     return;
2150
2151   // Empty sets are uninteresting.
2152   if (Previous.empty())
2153     return;
2154
2155   LookupResult::Filter Filter = Previous.makeFilter();
2156   while (Filter.hasNext()) {
2157     NamedDecl *Old = Filter.next();
2158
2159     // Non-hidden declarations are never ignored.
2160     if (S.isVisible(Old))
2161       continue;
2162
2163     // Declarations of the same entity are not ignored, even if they have
2164     // different linkages.
2165     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2166       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2167                                 Decl->getUnderlyingType()))
2168         continue;
2169
2170       // If both declarations give a tag declaration a typedef name for linkage
2171       // purposes, then they declare the same entity.
2172       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2173           Decl->getAnonDeclWithTypedefName())
2174         continue;
2175     }
2176
2177     Filter.erase();
2178   }
2179
2180   Filter.done();
2181 }
2182
2183 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2184   QualType OldType;
2185   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2186     OldType = OldTypedef->getUnderlyingType();
2187   else
2188     OldType = Context.getTypeDeclType(Old);
2189   QualType NewType = New->getUnderlyingType();
2190
2191   if (NewType->isVariablyModifiedType()) {
2192     // Must not redefine a typedef with a variably-modified type.
2193     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2194     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2195       << Kind << NewType;
2196     if (Old->getLocation().isValid())
2197       notePreviousDefinition(Old, New->getLocation());
2198     New->setInvalidDecl();
2199     return true;
2200   }
2201
2202   if (OldType != NewType &&
2203       !OldType->isDependentType() &&
2204       !NewType->isDependentType() &&
2205       !Context.hasSameType(OldType, NewType)) {
2206     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2207     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2208       << Kind << NewType << OldType;
2209     if (Old->getLocation().isValid())
2210       notePreviousDefinition(Old, New->getLocation());
2211     New->setInvalidDecl();
2212     return true;
2213   }
2214   return false;
2215 }
2216
2217 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2218 /// same name and scope as a previous declaration 'Old'.  Figure out
2219 /// how to resolve this situation, merging decls or emitting
2220 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2221 ///
2222 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2223                                 LookupResult &OldDecls) {
2224   // If the new decl is known invalid already, don't bother doing any
2225   // merging checks.
2226   if (New->isInvalidDecl()) return;
2227
2228   // Allow multiple definitions for ObjC built-in typedefs.
2229   // FIXME: Verify the underlying types are equivalent!
2230   if (getLangOpts().ObjC) {
2231     const IdentifierInfo *TypeID = New->getIdentifier();
2232     switch (TypeID->getLength()) {
2233     default: break;
2234     case 2:
2235       {
2236         if (!TypeID->isStr("id"))
2237           break;
2238         QualType T = New->getUnderlyingType();
2239         if (!T->isPointerType())
2240           break;
2241         if (!T->isVoidPointerType()) {
2242           QualType PT = T->castAs<PointerType>()->getPointeeType();
2243           if (!PT->isStructureType())
2244             break;
2245         }
2246         Context.setObjCIdRedefinitionType(T);
2247         // Install the built-in type for 'id', ignoring the current definition.
2248         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2249         return;
2250       }
2251     case 5:
2252       if (!TypeID->isStr("Class"))
2253         break;
2254       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2255       // Install the built-in type for 'Class', ignoring the current definition.
2256       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2257       return;
2258     case 3:
2259       if (!TypeID->isStr("SEL"))
2260         break;
2261       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2262       // Install the built-in type for 'SEL', ignoring the current definition.
2263       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2264       return;
2265     }
2266     // Fall through - the typedef name was not a builtin type.
2267   }
2268
2269   // Verify the old decl was also a type.
2270   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2271   if (!Old) {
2272     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2273       << New->getDeclName();
2274
2275     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2276     if (OldD->getLocation().isValid())
2277       notePreviousDefinition(OldD, New->getLocation());
2278
2279     return New->setInvalidDecl();
2280   }
2281
2282   // If the old declaration is invalid, just give up here.
2283   if (Old->isInvalidDecl())
2284     return New->setInvalidDecl();
2285
2286   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2287     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2288     auto *NewTag = New->getAnonDeclWithTypedefName();
2289     NamedDecl *Hidden = nullptr;
2290     if (OldTag && NewTag &&
2291         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2292         !hasVisibleDefinition(OldTag, &Hidden)) {
2293       // There is a definition of this tag, but it is not visible. Use it
2294       // instead of our tag.
2295       New->setTypeForDecl(OldTD->getTypeForDecl());
2296       if (OldTD->isModed())
2297         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2298                                     OldTD->getUnderlyingType());
2299       else
2300         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2301
2302       // Make the old tag definition visible.
2303       makeMergedDefinitionVisible(Hidden);
2304
2305       // If this was an unscoped enumeration, yank all of its enumerators
2306       // out of the scope.
2307       if (isa<EnumDecl>(NewTag)) {
2308         Scope *EnumScope = getNonFieldDeclScope(S);
2309         for (auto *D : NewTag->decls()) {
2310           auto *ED = cast<EnumConstantDecl>(D);
2311           assert(EnumScope->isDeclScope(ED));
2312           EnumScope->RemoveDecl(ED);
2313           IdResolver.RemoveDecl(ED);
2314           ED->getLexicalDeclContext()->removeDecl(ED);
2315         }
2316       }
2317     }
2318   }
2319
2320   // If the typedef types are not identical, reject them in all languages and
2321   // with any extensions enabled.
2322   if (isIncompatibleTypedef(Old, New))
2323     return;
2324
2325   // The types match.  Link up the redeclaration chain and merge attributes if
2326   // the old declaration was a typedef.
2327   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2328     New->setPreviousDecl(Typedef);
2329     mergeDeclAttributes(New, Old);
2330   }
2331
2332   if (getLangOpts().MicrosoftExt)
2333     return;
2334
2335   if (getLangOpts().CPlusPlus) {
2336     // C++ [dcl.typedef]p2:
2337     //   In a given non-class scope, a typedef specifier can be used to
2338     //   redefine the name of any type declared in that scope to refer
2339     //   to the type to which it already refers.
2340     if (!isa<CXXRecordDecl>(CurContext))
2341       return;
2342
2343     // C++0x [dcl.typedef]p4:
2344     //   In a given class scope, a typedef specifier can be used to redefine
2345     //   any class-name declared in that scope that is not also a typedef-name
2346     //   to refer to the type to which it already refers.
2347     //
2348     // This wording came in via DR424, which was a correction to the
2349     // wording in DR56, which accidentally banned code like:
2350     //
2351     //   struct S {
2352     //     typedef struct A { } A;
2353     //   };
2354     //
2355     // in the C++03 standard. We implement the C++0x semantics, which
2356     // allow the above but disallow
2357     //
2358     //   struct S {
2359     //     typedef int I;
2360     //     typedef int I;
2361     //   };
2362     //
2363     // since that was the intent of DR56.
2364     if (!isa<TypedefNameDecl>(Old))
2365       return;
2366
2367     Diag(New->getLocation(), diag::err_redefinition)
2368       << New->getDeclName();
2369     notePreviousDefinition(Old, New->getLocation());
2370     return New->setInvalidDecl();
2371   }
2372
2373   // Modules always permit redefinition of typedefs, as does C11.
2374   if (getLangOpts().Modules || getLangOpts().C11)
2375     return;
2376
2377   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2378   // is normally mapped to an error, but can be controlled with
2379   // -Wtypedef-redefinition.  If either the original or the redefinition is
2380   // in a system header, don't emit this for compatibility with GCC.
2381   if (getDiagnostics().getSuppressSystemWarnings() &&
2382       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2383       (Old->isImplicit() ||
2384        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2385        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2386     return;
2387
2388   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2389     << New->getDeclName();
2390   notePreviousDefinition(Old, New->getLocation());
2391 }
2392
2393 /// DeclhasAttr - returns true if decl Declaration already has the target
2394 /// attribute.
2395 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2396   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2397   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2398   for (const auto *i : D->attrs())
2399     if (i->getKind() == A->getKind()) {
2400       if (Ann) {
2401         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2402           return true;
2403         continue;
2404       }
2405       // FIXME: Don't hardcode this check
2406       if (OA && isa<OwnershipAttr>(i))
2407         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2408       return true;
2409     }
2410
2411   return false;
2412 }
2413
2414 static bool isAttributeTargetADefinition(Decl *D) {
2415   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2416     return VD->isThisDeclarationADefinition();
2417   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2418     return TD->isCompleteDefinition() || TD->isBeingDefined();
2419   return true;
2420 }
2421
2422 /// Merge alignment attributes from \p Old to \p New, taking into account the
2423 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2424 ///
2425 /// \return \c true if any attributes were added to \p New.
2426 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2427   // Look for alignas attributes on Old, and pick out whichever attribute
2428   // specifies the strictest alignment requirement.
2429   AlignedAttr *OldAlignasAttr = nullptr;
2430   AlignedAttr *OldStrictestAlignAttr = nullptr;
2431   unsigned OldAlign = 0;
2432   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2433     // FIXME: We have no way of representing inherited dependent alignments
2434     // in a case like:
2435     //   template<int A, int B> struct alignas(A) X;
2436     //   template<int A, int B> struct alignas(B) X {};
2437     // For now, we just ignore any alignas attributes which are not on the
2438     // definition in such a case.
2439     if (I->isAlignmentDependent())
2440       return false;
2441
2442     if (I->isAlignas())
2443       OldAlignasAttr = I;
2444
2445     unsigned Align = I->getAlignment(S.Context);
2446     if (Align > OldAlign) {
2447       OldAlign = Align;
2448       OldStrictestAlignAttr = I;
2449     }
2450   }
2451
2452   // Look for alignas attributes on New.
2453   AlignedAttr *NewAlignasAttr = nullptr;
2454   unsigned NewAlign = 0;
2455   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2456     if (I->isAlignmentDependent())
2457       return false;
2458
2459     if (I->isAlignas())
2460       NewAlignasAttr = I;
2461
2462     unsigned Align = I->getAlignment(S.Context);
2463     if (Align > NewAlign)
2464       NewAlign = Align;
2465   }
2466
2467   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2468     // Both declarations have 'alignas' attributes. We require them to match.
2469     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2470     // fall short. (If two declarations both have alignas, they must both match
2471     // every definition, and so must match each other if there is a definition.)
2472
2473     // If either declaration only contains 'alignas(0)' specifiers, then it
2474     // specifies the natural alignment for the type.
2475     if (OldAlign == 0 || NewAlign == 0) {
2476       QualType Ty;
2477       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2478         Ty = VD->getType();
2479       else
2480         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2481
2482       if (OldAlign == 0)
2483         OldAlign = S.Context.getTypeAlign(Ty);
2484       if (NewAlign == 0)
2485         NewAlign = S.Context.getTypeAlign(Ty);
2486     }
2487
2488     if (OldAlign != NewAlign) {
2489       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2490         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2491         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2492       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2493     }
2494   }
2495
2496   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2497     // C++11 [dcl.align]p6:
2498     //   if any declaration of an entity has an alignment-specifier,
2499     //   every defining declaration of that entity shall specify an
2500     //   equivalent alignment.
2501     // C11 6.7.5/7:
2502     //   If the definition of an object does not have an alignment
2503     //   specifier, any other declaration of that object shall also
2504     //   have no alignment specifier.
2505     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2506       << OldAlignasAttr;
2507     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2508       << OldAlignasAttr;
2509   }
2510
2511   bool AnyAdded = false;
2512
2513   // Ensure we have an attribute representing the strictest alignment.
2514   if (OldAlign > NewAlign) {
2515     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2516     Clone->setInherited(true);
2517     New->addAttr(Clone);
2518     AnyAdded = true;
2519   }
2520
2521   // Ensure we have an alignas attribute if the old declaration had one.
2522   if (OldAlignasAttr && !NewAlignasAttr &&
2523       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2524     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2525     Clone->setInherited(true);
2526     New->addAttr(Clone);
2527     AnyAdded = true;
2528   }
2529
2530   return AnyAdded;
2531 }
2532
2533 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2534                                const InheritableAttr *Attr,
2535                                Sema::AvailabilityMergeKind AMK) {
2536   // This function copies an attribute Attr from a previous declaration to the
2537   // new declaration D if the new declaration doesn't itself have that attribute
2538   // yet or if that attribute allows duplicates.
2539   // If you're adding a new attribute that requires logic different from
2540   // "use explicit attribute on decl if present, else use attribute from
2541   // previous decl", for example if the attribute needs to be consistent
2542   // between redeclarations, you need to call a custom merge function here.
2543   InheritableAttr *NewAttr = nullptr;
2544   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2545     NewAttr = S.mergeAvailabilityAttr(
2546         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2547         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2548         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2549         AA->getPriority());
2550   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2551     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2552   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2553     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2554   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2555     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2556   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2557     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2558   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2559     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2560                                 FA->getFirstArg());
2561   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2562     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2563   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2564     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2565   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2566     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2567                                        IA->getInheritanceModel());
2568   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2569     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2570                                       &S.Context.Idents.get(AA->getSpelling()));
2571   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2572            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2573             isa<CUDAGlobalAttr>(Attr))) {
2574     // CUDA target attributes are part of function signature for
2575     // overloading purposes and must not be merged.
2576     return false;
2577   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2578     NewAttr = S.mergeMinSizeAttr(D, *MA);
2579   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2580     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2581   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2582     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2583   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2584     NewAttr = S.mergeCommonAttr(D, *CommonA);
2585   else if (isa<AlignedAttr>(Attr))
2586     // AlignedAttrs are handled separately, because we need to handle all
2587     // such attributes on a declaration at the same time.
2588     NewAttr = nullptr;
2589   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2590            (AMK == Sema::AMK_Override ||
2591             AMK == Sema::AMK_ProtocolImplementation))
2592     NewAttr = nullptr;
2593   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2594     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2595   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2596     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2597   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2598     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2599   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2600     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2601
2602   if (NewAttr) {
2603     NewAttr->setInherited(true);
2604     D->addAttr(NewAttr);
2605     if (isa<MSInheritanceAttr>(NewAttr))
2606       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2607     return true;
2608   }
2609
2610   return false;
2611 }
2612
2613 static const NamedDecl *getDefinition(const Decl *D) {
2614   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2615     return TD->getDefinition();
2616   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2617     const VarDecl *Def = VD->getDefinition();
2618     if (Def)
2619       return Def;
2620     return VD->getActingDefinition();
2621   }
2622   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2623     return FD->getDefinition();
2624   return nullptr;
2625 }
2626
2627 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2628   for (const auto *Attribute : D->attrs())
2629     if (Attribute->getKind() == Kind)
2630       return true;
2631   return false;
2632 }
2633
2634 /// checkNewAttributesAfterDef - If we already have a definition, check that
2635 /// there are no new attributes in this declaration.
2636 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2637   if (!New->hasAttrs())
2638     return;
2639
2640   const NamedDecl *Def = getDefinition(Old);
2641   if (!Def || Def == New)
2642     return;
2643
2644   AttrVec &NewAttributes = New->getAttrs();
2645   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2646     const Attr *NewAttribute = NewAttributes[I];
2647
2648     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2649       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2650         Sema::SkipBodyInfo SkipBody;
2651         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2652
2653         // If we're skipping this definition, drop the "alias" attribute.
2654         if (SkipBody.ShouldSkip) {
2655           NewAttributes.erase(NewAttributes.begin() + I);
2656           --E;
2657           continue;
2658         }
2659       } else {
2660         VarDecl *VD = cast<VarDecl>(New);
2661         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2662                                 VarDecl::TentativeDefinition
2663                             ? diag::err_alias_after_tentative
2664                             : diag::err_redefinition;
2665         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2666         if (Diag == diag::err_redefinition)
2667           S.notePreviousDefinition(Def, VD->getLocation());
2668         else
2669           S.Diag(Def->getLocation(), diag::note_previous_definition);
2670         VD->setInvalidDecl();
2671       }
2672       ++I;
2673       continue;
2674     }
2675
2676     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2677       // Tentative definitions are only interesting for the alias check above.
2678       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2679         ++I;
2680         continue;
2681       }
2682     }
2683
2684     if (hasAttribute(Def, NewAttribute->getKind())) {
2685       ++I;
2686       continue; // regular attr merging will take care of validating this.
2687     }
2688
2689     if (isa<C11NoReturnAttr>(NewAttribute)) {
2690       // C's _Noreturn is allowed to be added to a function after it is defined.
2691       ++I;
2692       continue;
2693     } else if (isa<UuidAttr>(NewAttribute)) {
2694       // msvc will allow a subsequent definition to add an uuid to a class
2695       ++I;
2696       continue;
2697     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2698       if (AA->isAlignas()) {
2699         // C++11 [dcl.align]p6:
2700         //   if any declaration of an entity has an alignment-specifier,
2701         //   every defining declaration of that entity shall specify an
2702         //   equivalent alignment.
2703         // C11 6.7.5/7:
2704         //   If the definition of an object does not have an alignment
2705         //   specifier, any other declaration of that object shall also
2706         //   have no alignment specifier.
2707         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2708           << AA;
2709         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2710           << AA;
2711         NewAttributes.erase(NewAttributes.begin() + I);
2712         --E;
2713         continue;
2714       }
2715     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2716                cast<VarDecl>(New)->isInline() &&
2717                !cast<VarDecl>(New)->isInlineSpecified()) {
2718       // Don't warn about applying selectany to implicitly inline variables.
2719       // Older compilers and language modes would require the use of selectany
2720       // to make such variables inline, and it would have no effect if we
2721       // honored it.
2722       ++I;
2723       continue;
2724     }
2725
2726     S.Diag(NewAttribute->getLocation(),
2727            diag::warn_attribute_precede_definition);
2728     S.Diag(Def->getLocation(), diag::note_previous_definition);
2729     NewAttributes.erase(NewAttributes.begin() + I);
2730     --E;
2731   }
2732 }
2733
2734 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2735                                      const ConstInitAttr *CIAttr,
2736                                      bool AttrBeforeInit) {
2737   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2738
2739   // Figure out a good way to write this specifier on the old declaration.
2740   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2741   // enough of the attribute list spelling information to extract that without
2742   // heroics.
2743   std::string SuitableSpelling;
2744   if (S.getLangOpts().CPlusPlus2a)
2745     SuitableSpelling =
2746         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2747   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2748     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2749         InsertLoc,
2750         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2751          tok::coloncolon,
2752          S.PP.getIdentifierInfo("require_constant_initialization"),
2753          tok::r_square, tok::r_square});
2754   if (SuitableSpelling.empty())
2755     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2756         InsertLoc,
2757         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2758          S.PP.getIdentifierInfo("require_constant_initialization"),
2759          tok::r_paren, tok::r_paren});
2760   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2761     SuitableSpelling = "constinit";
2762   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2763     SuitableSpelling = "[[clang::require_constant_initialization]]";
2764   if (SuitableSpelling.empty())
2765     SuitableSpelling = "__attribute__((require_constant_initialization))";
2766   SuitableSpelling += " ";
2767
2768   if (AttrBeforeInit) {
2769     // extern constinit int a;
2770     // int a = 0; // error (missing 'constinit'), accepted as extension
2771     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2772     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2773         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2774     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2775   } else {
2776     // int a = 0;
2777     // constinit extern int a; // error (missing 'constinit')
2778     S.Diag(CIAttr->getLocation(),
2779            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2780                                  : diag::warn_require_const_init_added_too_late)
2781         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2782     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2783         << CIAttr->isConstinit()
2784         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2785   }
2786 }
2787
2788 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2789 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2790                                AvailabilityMergeKind AMK) {
2791   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2792     UsedAttr *NewAttr = OldAttr->clone(Context);
2793     NewAttr->setInherited(true);
2794     New->addAttr(NewAttr);
2795   }
2796
2797   if (!Old->hasAttrs() && !New->hasAttrs())
2798     return;
2799
2800   // [dcl.constinit]p1:
2801   //   If the [constinit] specifier is applied to any declaration of a
2802   //   variable, it shall be applied to the initializing declaration.
2803   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2804   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2805   if (bool(OldConstInit) != bool(NewConstInit)) {
2806     const auto *OldVD = cast<VarDecl>(Old);
2807     auto *NewVD = cast<VarDecl>(New);
2808
2809     // Find the initializing declaration. Note that we might not have linked
2810     // the new declaration into the redeclaration chain yet.
2811     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2812     if (!InitDecl &&
2813         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2814       InitDecl = NewVD;
2815
2816     if (InitDecl == NewVD) {
2817       // This is the initializing declaration. If it would inherit 'constinit',
2818       // that's ill-formed. (Note that we do not apply this to the attribute
2819       // form).
2820       if (OldConstInit && OldConstInit->isConstinit())
2821         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2822                                  /*AttrBeforeInit=*/true);
2823     } else if (NewConstInit) {
2824       // This is the first time we've been told that this declaration should
2825       // have a constant initializer. If we already saw the initializing
2826       // declaration, this is too late.
2827       if (InitDecl && InitDecl != NewVD) {
2828         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2829                                  /*AttrBeforeInit=*/false);
2830         NewVD->dropAttr<ConstInitAttr>();
2831       }
2832     }
2833   }
2834
2835   // Attributes declared post-definition are currently ignored.
2836   checkNewAttributesAfterDef(*this, New, Old);
2837
2838   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2839     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2840       if (!OldA->isEquivalent(NewA)) {
2841         // This redeclaration changes __asm__ label.
2842         Diag(New->getLocation(), diag::err_different_asm_label);
2843         Diag(OldA->getLocation(), diag::note_previous_declaration);
2844       }
2845     } else if (Old->isUsed()) {
2846       // This redeclaration adds an __asm__ label to a declaration that has
2847       // already been ODR-used.
2848       Diag(New->getLocation(), diag::err_late_asm_label_name)
2849         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2850     }
2851   }
2852
2853   // Re-declaration cannot add abi_tag's.
2854   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2855     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2856       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2857         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2858                       NewTag) == OldAbiTagAttr->tags_end()) {
2859           Diag(NewAbiTagAttr->getLocation(),
2860                diag::err_new_abi_tag_on_redeclaration)
2861               << NewTag;
2862           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2863         }
2864       }
2865     } else {
2866       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2867       Diag(Old->getLocation(), diag::note_previous_declaration);
2868     }
2869   }
2870
2871   // This redeclaration adds a section attribute.
2872   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2873     if (auto *VD = dyn_cast<VarDecl>(New)) {
2874       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2875         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2876         Diag(Old->getLocation(), diag::note_previous_declaration);
2877       }
2878     }
2879   }
2880
2881   // Redeclaration adds code-seg attribute.
2882   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2883   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2884       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2885     Diag(New->getLocation(), diag::warn_mismatched_section)
2886          << 0 /*codeseg*/;
2887     Diag(Old->getLocation(), diag::note_previous_declaration);
2888   }
2889
2890   if (!Old->hasAttrs())
2891     return;
2892
2893   bool foundAny = New->hasAttrs();
2894
2895   // Ensure that any moving of objects within the allocated map is done before
2896   // we process them.
2897   if (!foundAny) New->setAttrs(AttrVec());
2898
2899   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2900     // Ignore deprecated/unavailable/availability attributes if requested.
2901     AvailabilityMergeKind LocalAMK = AMK_None;
2902     if (isa<DeprecatedAttr>(I) ||
2903         isa<UnavailableAttr>(I) ||
2904         isa<AvailabilityAttr>(I)) {
2905       switch (AMK) {
2906       case AMK_None:
2907         continue;
2908
2909       case AMK_Redeclaration:
2910       case AMK_Override:
2911       case AMK_ProtocolImplementation:
2912         LocalAMK = AMK;
2913         break;
2914       }
2915     }
2916
2917     // Already handled.
2918     if (isa<UsedAttr>(I))
2919       continue;
2920
2921     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2922       foundAny = true;
2923   }
2924
2925   if (mergeAlignedAttrs(*this, New, Old))
2926     foundAny = true;
2927
2928   if (!foundAny) New->dropAttrs();
2929 }
2930
2931 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2932 /// to the new one.
2933 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2934                                      const ParmVarDecl *oldDecl,
2935                                      Sema &S) {
2936   // C++11 [dcl.attr.depend]p2:
2937   //   The first declaration of a function shall specify the
2938   //   carries_dependency attribute for its declarator-id if any declaration
2939   //   of the function specifies the carries_dependency attribute.
2940   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2941   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2942     S.Diag(CDA->getLocation(),
2943            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2944     // Find the first declaration of the parameter.
2945     // FIXME: Should we build redeclaration chains for function parameters?
2946     const FunctionDecl *FirstFD =
2947       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2948     const ParmVarDecl *FirstVD =
2949       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2950     S.Diag(FirstVD->getLocation(),
2951            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2952   }
2953
2954   if (!oldDecl->hasAttrs())
2955     return;
2956
2957   bool foundAny = newDecl->hasAttrs();
2958
2959   // Ensure that any moving of objects within the allocated map is
2960   // done before we process them.
2961   if (!foundAny) newDecl->setAttrs(AttrVec());
2962
2963   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2964     if (!DeclHasAttr(newDecl, I)) {
2965       InheritableAttr *newAttr =
2966         cast<InheritableParamAttr>(I->clone(S.Context));
2967       newAttr->setInherited(true);
2968       newDecl->addAttr(newAttr);
2969       foundAny = true;
2970     }
2971   }
2972
2973   if (!foundAny) newDecl->dropAttrs();
2974 }
2975
2976 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2977                                 const ParmVarDecl *OldParam,
2978                                 Sema &S) {
2979   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2980     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2981       if (*Oldnullability != *Newnullability) {
2982         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2983           << DiagNullabilityKind(
2984                *Newnullability,
2985                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2986                 != 0))
2987           << DiagNullabilityKind(
2988                *Oldnullability,
2989                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2990                 != 0));
2991         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2992       }
2993     } else {
2994       QualType NewT = NewParam->getType();
2995       NewT = S.Context.getAttributedType(
2996                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2997                          NewT, NewT);
2998       NewParam->setType(NewT);
2999     }
3000   }
3001 }
3002
3003 namespace {
3004
3005 /// Used in MergeFunctionDecl to keep track of function parameters in
3006 /// C.
3007 struct GNUCompatibleParamWarning {
3008   ParmVarDecl *OldParm;
3009   ParmVarDecl *NewParm;
3010   QualType PromotedType;
3011 };
3012
3013 } // end anonymous namespace
3014
3015 // Determine whether the previous declaration was a definition, implicit
3016 // declaration, or a declaration.
3017 template <typename T>
3018 static std::pair<diag::kind, SourceLocation>
3019 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3020   diag::kind PrevDiag;
3021   SourceLocation OldLocation = Old->getLocation();
3022   if (Old->isThisDeclarationADefinition())
3023     PrevDiag = diag::note_previous_definition;
3024   else if (Old->isImplicit()) {
3025     PrevDiag = diag::note_previous_implicit_declaration;
3026     if (OldLocation.isInvalid())
3027       OldLocation = New->getLocation();
3028   } else
3029     PrevDiag = diag::note_previous_declaration;
3030   return std::make_pair(PrevDiag, OldLocation);
3031 }
3032
3033 /// canRedefineFunction - checks if a function can be redefined. Currently,
3034 /// only extern inline functions can be redefined, and even then only in
3035 /// GNU89 mode.
3036 static bool canRedefineFunction(const FunctionDecl *FD,
3037                                 const LangOptions& LangOpts) {
3038   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3039           !LangOpts.CPlusPlus &&
3040           FD->isInlineSpecified() &&
3041           FD->getStorageClass() == SC_Extern);
3042 }
3043
3044 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3045   const AttributedType *AT = T->getAs<AttributedType>();
3046   while (AT && !AT->isCallingConv())
3047     AT = AT->getModifiedType()->getAs<AttributedType>();
3048   return AT;
3049 }
3050
3051 template <typename T>
3052 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3053   const DeclContext *DC = Old->getDeclContext();
3054   if (DC->isRecord())
3055     return false;
3056
3057   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3058   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3059     return true;
3060   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3061     return true;
3062   return false;
3063 }
3064
3065 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3066 static bool isExternC(VarTemplateDecl *) { return false; }
3067
3068 /// Check whether a redeclaration of an entity introduced by a
3069 /// using-declaration is valid, given that we know it's not an overload
3070 /// (nor a hidden tag declaration).
3071 template<typename ExpectedDecl>
3072 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3073                                    ExpectedDecl *New) {
3074   // C++11 [basic.scope.declarative]p4:
3075   //   Given a set of declarations in a single declarative region, each of
3076   //   which specifies the same unqualified name,
3077   //   -- they shall all refer to the same entity, or all refer to functions
3078   //      and function templates; or
3079   //   -- exactly one declaration shall declare a class name or enumeration
3080   //      name that is not a typedef name and the other declarations shall all
3081   //      refer to the same variable or enumerator, or all refer to functions
3082   //      and function templates; in this case the class name or enumeration
3083   //      name is hidden (3.3.10).
3084
3085   // C++11 [namespace.udecl]p14:
3086   //   If a function declaration in namespace scope or block scope has the
3087   //   same name and the same parameter-type-list as a function introduced
3088   //   by a using-declaration, and the declarations do not declare the same
3089   //   function, the program is ill-formed.
3090
3091   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3092   if (Old &&
3093       !Old->getDeclContext()->getRedeclContext()->Equals(
3094           New->getDeclContext()->getRedeclContext()) &&
3095       !(isExternC(Old) && isExternC(New)))
3096     Old = nullptr;
3097
3098   if (!Old) {
3099     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3100     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3101     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3102     return true;
3103   }
3104   return false;
3105 }
3106
3107 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3108                                             const FunctionDecl *B) {
3109   assert(A->getNumParams() == B->getNumParams());
3110
3111   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3112     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3113     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3114     if (AttrA == AttrB)
3115       return true;
3116     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3117            AttrA->isDynamic() == AttrB->isDynamic();
3118   };
3119
3120   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3121 }
3122
3123 /// If necessary, adjust the semantic declaration context for a qualified
3124 /// declaration to name the correct inline namespace within the qualifier.
3125 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3126                                                DeclaratorDecl *OldD) {
3127   // The only case where we need to update the DeclContext is when
3128   // redeclaration lookup for a qualified name finds a declaration
3129   // in an inline namespace within the context named by the qualifier:
3130   //
3131   //   inline namespace N { int f(); }
3132   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3133   //
3134   // For unqualified declarations, the semantic context *can* change
3135   // along the redeclaration chain (for local extern declarations,
3136   // extern "C" declarations, and friend declarations in particular).
3137   if (!NewD->getQualifier())
3138     return;
3139
3140   // NewD is probably already in the right context.
3141   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3142   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3143   if (NamedDC->Equals(SemaDC))
3144     return;
3145
3146   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3147           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3148          "unexpected context for redeclaration");
3149
3150   auto *LexDC = NewD->getLexicalDeclContext();
3151   auto FixSemaDC = [=](NamedDecl *D) {
3152     if (!D)
3153       return;
3154     D->setDeclContext(SemaDC);
3155     D->setLexicalDeclContext(LexDC);
3156   };
3157
3158   FixSemaDC(NewD);
3159   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3160     FixSemaDC(FD->getDescribedFunctionTemplate());
3161   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3162     FixSemaDC(VD->getDescribedVarTemplate());
3163 }
3164
3165 /// MergeFunctionDecl - We just parsed a function 'New' from
3166 /// declarator D which has the same name and scope as a previous
3167 /// declaration 'Old'.  Figure out how to resolve this situation,
3168 /// merging decls or emitting diagnostics as appropriate.
3169 ///
3170 /// In C++, New and Old must be declarations that are not
3171 /// overloaded. Use IsOverload to determine whether New and Old are
3172 /// overloaded, and to select the Old declaration that New should be
3173 /// merged with.
3174 ///
3175 /// Returns true if there was an error, false otherwise.
3176 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3177                              Scope *S, bool MergeTypeWithOld) {
3178   // Verify the old decl was also a function.
3179   FunctionDecl *Old = OldD->getAsFunction();
3180   if (!Old) {
3181     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3182       if (New->getFriendObjectKind()) {
3183         Diag(New->getLocation(), diag::err_using_decl_friend);
3184         Diag(Shadow->getTargetDecl()->getLocation(),
3185              diag::note_using_decl_target);
3186         Diag(Shadow->getUsingDecl()->getLocation(),
3187              diag::note_using_decl) << 0;
3188         return true;
3189       }
3190
3191       // Check whether the two declarations might declare the same function.
3192       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3193         return true;
3194       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3195     } else {
3196       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3197         << New->getDeclName();
3198       notePreviousDefinition(OldD, New->getLocation());
3199       return true;
3200     }
3201   }
3202
3203   // If the old declaration is invalid, just give up here.
3204   if (Old->isInvalidDecl())
3205     return true;
3206
3207   // Disallow redeclaration of some builtins.
3208   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3209     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3210     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3211         << Old << Old->getType();
3212     return true;
3213   }
3214
3215   diag::kind PrevDiag;
3216   SourceLocation OldLocation;
3217   std::tie(PrevDiag, OldLocation) =
3218       getNoteDiagForInvalidRedeclaration(Old, New);
3219
3220   // Don't complain about this if we're in GNU89 mode and the old function
3221   // is an extern inline function.
3222   // Don't complain about specializations. They are not supposed to have
3223   // storage classes.
3224   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3225       New->getStorageClass() == SC_Static &&
3226       Old->hasExternalFormalLinkage() &&
3227       !New->getTemplateSpecializationInfo() &&
3228       !canRedefineFunction(Old, getLangOpts())) {
3229     if (getLangOpts().MicrosoftExt) {
3230       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3231       Diag(OldLocation, PrevDiag);
3232     } else {
3233       Diag(New->getLocation(), diag::err_static_non_static) << New;
3234       Diag(OldLocation, PrevDiag);
3235       return true;
3236     }
3237   }
3238
3239   if (New->hasAttr<InternalLinkageAttr>() &&
3240       !Old->hasAttr<InternalLinkageAttr>()) {
3241     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3242         << New->getDeclName();
3243     notePreviousDefinition(Old, New->getLocation());
3244     New->dropAttr<InternalLinkageAttr>();
3245   }
3246
3247   if (CheckRedeclarationModuleOwnership(New, Old))
3248     return true;
3249
3250   if (!getLangOpts().CPlusPlus) {
3251     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3252     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3253       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3254         << New << OldOvl;
3255
3256       // Try our best to find a decl that actually has the overloadable
3257       // attribute for the note. In most cases (e.g. programs with only one
3258       // broken declaration/definition), this won't matter.
3259       //
3260       // FIXME: We could do this if we juggled some extra state in
3261       // OverloadableAttr, rather than just removing it.
3262       const Decl *DiagOld = Old;
3263       if (OldOvl) {
3264         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3265           const auto *A = D->getAttr<OverloadableAttr>();
3266           return A && !A->isImplicit();
3267         });
3268         // If we've implicitly added *all* of the overloadable attrs to this
3269         // chain, emitting a "previous redecl" note is pointless.
3270         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3271       }
3272
3273       if (DiagOld)
3274         Diag(DiagOld->getLocation(),
3275              diag::note_attribute_overloadable_prev_overload)
3276           << OldOvl;
3277
3278       if (OldOvl)
3279         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3280       else
3281         New->dropAttr<OverloadableAttr>();
3282     }
3283   }
3284
3285   // If a function is first declared with a calling convention, but is later
3286   // declared or defined without one, all following decls assume the calling
3287   // convention of the first.
3288   //
3289   // It's OK if a function is first declared without a calling convention,
3290   // but is later declared or defined with the default calling convention.
3291   //
3292   // To test if either decl has an explicit calling convention, we look for
3293   // AttributedType sugar nodes on the type as written.  If they are missing or
3294   // were canonicalized away, we assume the calling convention was implicit.
3295   //
3296   // Note also that we DO NOT return at this point, because we still have
3297   // other tests to run.
3298   QualType OldQType = Context.getCanonicalType(Old->getType());
3299   QualType NewQType = Context.getCanonicalType(New->getType());
3300   const FunctionType *OldType = cast<FunctionType>(OldQType);
3301   const FunctionType *NewType = cast<FunctionType>(NewQType);
3302   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3303   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3304   bool RequiresAdjustment = false;
3305
3306   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3307     FunctionDecl *First = Old->getFirstDecl();
3308     const FunctionType *FT =
3309         First->getType().getCanonicalType()->castAs<FunctionType>();
3310     FunctionType::ExtInfo FI = FT->getExtInfo();
3311     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3312     if (!NewCCExplicit) {
3313       // Inherit the CC from the previous declaration if it was specified
3314       // there but not here.
3315       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3316       RequiresAdjustment = true;
3317     } else if (New->getBuiltinID()) {
3318       // Calling Conventions on a Builtin aren't really useful and setting a
3319       // default calling convention and cdecl'ing some builtin redeclarations is
3320       // common, so warn and ignore the calling convention on the redeclaration.
3321       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3322           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3323           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3324       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3325       RequiresAdjustment = true;
3326     } else {
3327       // Calling conventions aren't compatible, so complain.
3328       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3329       Diag(New->getLocation(), diag::err_cconv_change)
3330         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3331         << !FirstCCExplicit
3332         << (!FirstCCExplicit ? "" :
3333             FunctionType::getNameForCallConv(FI.getCC()));
3334
3335       // Put the note on the first decl, since it is the one that matters.
3336       Diag(First->getLocation(), diag::note_previous_declaration);
3337       return true;
3338     }
3339   }
3340
3341   // FIXME: diagnose the other way around?
3342   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3343     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3344     RequiresAdjustment = true;
3345   }
3346
3347   // Merge regparm attribute.
3348   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3349       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3350     if (NewTypeInfo.getHasRegParm()) {
3351       Diag(New->getLocation(), diag::err_regparm_mismatch)
3352         << NewType->getRegParmType()
3353         << OldType->getRegParmType();
3354       Diag(OldLocation, diag::note_previous_declaration);
3355       return true;
3356     }
3357
3358     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3359     RequiresAdjustment = true;
3360   }
3361
3362   // Merge ns_returns_retained attribute.
3363   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3364     if (NewTypeInfo.getProducesResult()) {
3365       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3366           << "'ns_returns_retained'";
3367       Diag(OldLocation, diag::note_previous_declaration);
3368       return true;
3369     }
3370
3371     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3372     RequiresAdjustment = true;
3373   }
3374
3375   if (OldTypeInfo.getNoCallerSavedRegs() !=
3376       NewTypeInfo.getNoCallerSavedRegs()) {
3377     if (NewTypeInfo.getNoCallerSavedRegs()) {
3378       AnyX86NoCallerSavedRegistersAttr *Attr =
3379         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3380       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3381       Diag(OldLocation, diag::note_previous_declaration);
3382       return true;
3383     }
3384
3385     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3386     RequiresAdjustment = true;
3387   }
3388
3389   if (RequiresAdjustment) {
3390     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3391     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3392     New->setType(QualType(AdjustedType, 0));
3393     NewQType = Context.getCanonicalType(New->getType());
3394   }
3395
3396   // If this redeclaration makes the function inline, we may need to add it to
3397   // UndefinedButUsed.
3398   if (!Old->isInlined() && New->isInlined() &&
3399       !New->hasAttr<GNUInlineAttr>() &&
3400       !getLangOpts().GNUInline &&
3401       Old->isUsed(false) &&
3402       !Old->isDefined() && !New->isThisDeclarationADefinition())
3403     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3404                                            SourceLocation()));
3405
3406   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3407   // about it.
3408   if (New->hasAttr<GNUInlineAttr>() &&
3409       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3410     UndefinedButUsed.erase(Old->getCanonicalDecl());
3411   }
3412
3413   // If pass_object_size params don't match up perfectly, this isn't a valid
3414   // redeclaration.
3415   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3416       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3417     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3418         << New->getDeclName();
3419     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3420     return true;
3421   }
3422
3423   if (getLangOpts().CPlusPlus) {
3424     // C++1z [over.load]p2
3425     //   Certain function declarations cannot be overloaded:
3426     //     -- Function declarations that differ only in the return type,
3427     //        the exception specification, or both cannot be overloaded.
3428
3429     // Check the exception specifications match. This may recompute the type of
3430     // both Old and New if it resolved exception specifications, so grab the
3431     // types again after this. Because this updates the type, we do this before
3432     // any of the other checks below, which may update the "de facto" NewQType
3433     // but do not necessarily update the type of New.
3434     if (CheckEquivalentExceptionSpec(Old, New))
3435       return true;
3436     OldQType = Context.getCanonicalType(Old->getType());
3437     NewQType = Context.getCanonicalType(New->getType());
3438
3439     // Go back to the type source info to compare the declared return types,
3440     // per C++1y [dcl.type.auto]p13:
3441     //   Redeclarations or specializations of a function or function template
3442     //   with a declared return type that uses a placeholder type shall also
3443     //   use that placeholder, not a deduced type.
3444     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3445     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3446     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3447         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3448                                        OldDeclaredReturnType)) {
3449       QualType ResQT;
3450       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3451           OldDeclaredReturnType->isObjCObjectPointerType())
3452         // FIXME: This does the wrong thing for a deduced return type.
3453         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3454       if (ResQT.isNull()) {
3455         if (New->isCXXClassMember() && New->isOutOfLine())
3456           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3457               << New << New->getReturnTypeSourceRange();
3458         else
3459           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3460               << New->getReturnTypeSourceRange();
3461         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3462                                     << Old->getReturnTypeSourceRange();
3463         return true;
3464       }
3465       else
3466         NewQType = ResQT;
3467     }
3468
3469     QualType OldReturnType = OldType->getReturnType();
3470     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3471     if (OldReturnType != NewReturnType) {
3472       // If this function has a deduced return type and has already been
3473       // defined, copy the deduced value from the old declaration.
3474       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3475       if (OldAT && OldAT->isDeduced()) {
3476         New->setType(
3477             SubstAutoType(New->getType(),
3478                           OldAT->isDependentType() ? Context.DependentTy
3479                                                    : OldAT->getDeducedType()));
3480         NewQType = Context.getCanonicalType(
3481             SubstAutoType(NewQType,
3482                           OldAT->isDependentType() ? Context.DependentTy
3483                                                    : OldAT->getDeducedType()));
3484       }
3485     }
3486
3487     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3488     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3489     if (OldMethod && NewMethod) {
3490       // Preserve triviality.
3491       NewMethod->setTrivial(OldMethod->isTrivial());
3492
3493       // MSVC allows explicit template specialization at class scope:
3494       // 2 CXXMethodDecls referring to the same function will be injected.
3495       // We don't want a redeclaration error.
3496       bool IsClassScopeExplicitSpecialization =
3497                               OldMethod->isFunctionTemplateSpecialization() &&
3498                               NewMethod->isFunctionTemplateSpecialization();
3499       bool isFriend = NewMethod->getFriendObjectKind();
3500
3501       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3502           !IsClassScopeExplicitSpecialization) {
3503         //    -- Member function declarations with the same name and the
3504         //       same parameter types cannot be overloaded if any of them
3505         //       is a static member function declaration.
3506         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3507           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3508           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3509           return true;
3510         }
3511
3512         // C++ [class.mem]p1:
3513         //   [...] A member shall not be declared twice in the
3514         //   member-specification, except that a nested class or member
3515         //   class template can be declared and then later defined.
3516         if (!inTemplateInstantiation()) {
3517           unsigned NewDiag;
3518           if (isa<CXXConstructorDecl>(OldMethod))
3519             NewDiag = diag::err_constructor_redeclared;
3520           else if (isa<CXXDestructorDecl>(NewMethod))
3521             NewDiag = diag::err_destructor_redeclared;
3522           else if (isa<CXXConversionDecl>(NewMethod))
3523             NewDiag = diag::err_conv_function_redeclared;
3524           else
3525             NewDiag = diag::err_member_redeclared;
3526
3527           Diag(New->getLocation(), NewDiag);
3528         } else {
3529           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3530             << New << New->getType();
3531         }
3532         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3533         return true;
3534
3535       // Complain if this is an explicit declaration of a special
3536       // member that was initially declared implicitly.
3537       //
3538       // As an exception, it's okay to befriend such methods in order
3539       // to permit the implicit constructor/destructor/operator calls.
3540       } else if (OldMethod->isImplicit()) {
3541         if (isFriend) {
3542           NewMethod->setImplicit();
3543         } else {
3544           Diag(NewMethod->getLocation(),
3545                diag::err_definition_of_implicitly_declared_member)
3546             << New << getSpecialMember(OldMethod);
3547           return true;
3548         }
3549       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3550         Diag(NewMethod->getLocation(),
3551              diag::err_definition_of_explicitly_defaulted_member)
3552           << getSpecialMember(OldMethod);
3553         return true;
3554       }
3555     }
3556
3557     // C++11 [dcl.attr.noreturn]p1:
3558     //   The first declaration of a function shall specify the noreturn
3559     //   attribute if any declaration of that function specifies the noreturn
3560     //   attribute.
3561     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3562     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3563       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3564       Diag(Old->getFirstDecl()->getLocation(),
3565            diag::note_noreturn_missing_first_decl);
3566     }
3567
3568     // C++11 [dcl.attr.depend]p2:
3569     //   The first declaration of a function shall specify the
3570     //   carries_dependency attribute for its declarator-id if any declaration
3571     //   of the function specifies the carries_dependency attribute.
3572     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3573     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3574       Diag(CDA->getLocation(),
3575            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3576       Diag(Old->getFirstDecl()->getLocation(),
3577            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3578     }
3579
3580     // (C++98 8.3.5p3):
3581     //   All declarations for a function shall agree exactly in both the
3582     //   return type and the parameter-type-list.
3583     // We also want to respect all the extended bits except noreturn.
3584
3585     // noreturn should now match unless the old type info didn't have it.
3586     QualType OldQTypeForComparison = OldQType;
3587     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3588       auto *OldType = OldQType->castAs<FunctionProtoType>();
3589       const FunctionType *OldTypeForComparison
3590         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3591       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3592       assert(OldQTypeForComparison.isCanonical());
3593     }
3594
3595     if (haveIncompatibleLanguageLinkages(Old, New)) {
3596       // As a special case, retain the language linkage from previous
3597       // declarations of a friend function as an extension.
3598       //
3599       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3600       // and is useful because there's otherwise no way to specify language
3601       // linkage within class scope.
3602       //
3603       // Check cautiously as the friend object kind isn't yet complete.
3604       if (New->getFriendObjectKind() != Decl::FOK_None) {
3605         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3606         Diag(OldLocation, PrevDiag);
3607       } else {
3608         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3609         Diag(OldLocation, PrevDiag);
3610         return true;
3611       }
3612     }
3613
3614     // If the function types are compatible, merge the declarations. Ignore the
3615     // exception specifier because it was already checked above in
3616     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3617     // about incompatible types under -fms-compatibility.
3618     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3619                                                          NewQType))
3620       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3621
3622     // If the types are imprecise (due to dependent constructs in friends or
3623     // local extern declarations), it's OK if they differ. We'll check again
3624     // during instantiation.
3625     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3626       return false;
3627
3628     // Fall through for conflicting redeclarations and redefinitions.
3629   }
3630
3631   // C: Function types need to be compatible, not identical. This handles
3632   // duplicate function decls like "void f(int); void f(enum X);" properly.
3633   if (!getLangOpts().CPlusPlus &&
3634       Context.typesAreCompatible(OldQType, NewQType)) {
3635     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3636     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3637     const FunctionProtoType *OldProto = nullptr;
3638     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3639         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3640       // The old declaration provided a function prototype, but the
3641       // new declaration does not. Merge in the prototype.
3642       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3643       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3644       NewQType =
3645           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3646                                   OldProto->getExtProtoInfo());
3647       New->setType(NewQType);
3648       New->setHasInheritedPrototype();
3649
3650       // Synthesize parameters with the same types.
3651       SmallVector<ParmVarDecl*, 16> Params;
3652       for (const auto &ParamType : OldProto->param_types()) {
3653         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3654                                                  SourceLocation(), nullptr,
3655                                                  ParamType, /*TInfo=*/nullptr,
3656                                                  SC_None, nullptr);
3657         Param->setScopeInfo(0, Params.size());
3658         Param->setImplicit();
3659         Params.push_back(Param);
3660       }
3661
3662       New->setParams(Params);
3663     }
3664
3665     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3666   }
3667
3668   // Check if the function types are compatible when pointer size address
3669   // spaces are ignored.
3670   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3671     return false;
3672
3673   // GNU C permits a K&R definition to follow a prototype declaration
3674   // if the declared types of the parameters in the K&R definition
3675   // match the types in the prototype declaration, even when the
3676   // promoted types of the parameters from the K&R definition differ
3677   // from the types in the prototype. GCC then keeps the types from
3678   // the prototype.
3679   //
3680   // If a variadic prototype is followed by a non-variadic K&R definition,
3681   // the K&R definition becomes variadic.  This is sort of an edge case, but
3682   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3683   // C99 6.9.1p8.
3684   if (!getLangOpts().CPlusPlus &&
3685       Old->hasPrototype() && !New->hasPrototype() &&
3686       New->getType()->getAs<FunctionProtoType>() &&
3687       Old->getNumParams() == New->getNumParams()) {
3688     SmallVector<QualType, 16> ArgTypes;
3689     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3690     const FunctionProtoType *OldProto
3691       = Old->getType()->getAs<FunctionProtoType>();
3692     const FunctionProtoType *NewProto
3693       = New->getType()->getAs<FunctionProtoType>();
3694
3695     // Determine whether this is the GNU C extension.
3696     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3697                                                NewProto->getReturnType());
3698     bool LooseCompatible = !MergedReturn.isNull();
3699     for (unsigned Idx = 0, End = Old->getNumParams();
3700          LooseCompatible && Idx != End; ++Idx) {
3701       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3702       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3703       if (Context.typesAreCompatible(OldParm->getType(),
3704                                      NewProto->getParamType(Idx))) {
3705         ArgTypes.push_back(NewParm->getType());
3706       } else if (Context.typesAreCompatible(OldParm->getType(),
3707                                             NewParm->getType(),
3708                                             /*CompareUnqualified=*/true)) {
3709         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3710                                            NewProto->getParamType(Idx) };
3711         Warnings.push_back(Warn);
3712         ArgTypes.push_back(NewParm->getType());
3713       } else
3714         LooseCompatible = false;
3715     }
3716
3717     if (LooseCompatible) {
3718       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3719         Diag(Warnings[Warn].NewParm->getLocation(),
3720              diag::ext_param_promoted_not_compatible_with_prototype)
3721           << Warnings[Warn].PromotedType
3722           << Warnings[Warn].OldParm->getType();
3723         if (Warnings[Warn].OldParm->getLocation().isValid())
3724           Diag(Warnings[Warn].OldParm->getLocation(),
3725                diag::note_previous_declaration);
3726       }
3727
3728       if (MergeTypeWithOld)
3729         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3730                                              OldProto->getExtProtoInfo()));
3731       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3732     }
3733
3734     // Fall through to diagnose conflicting types.
3735   }
3736
3737   // A function that has already been declared has been redeclared or
3738   // defined with a different type; show an appropriate diagnostic.
3739
3740   // If the previous declaration was an implicitly-generated builtin
3741   // declaration, then at the very least we should use a specialized note.
3742   unsigned BuiltinID;
3743   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3744     // If it's actually a library-defined builtin function like 'malloc'
3745     // or 'printf', just warn about the incompatible redeclaration.
3746     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3747       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3748       Diag(OldLocation, diag::note_previous_builtin_declaration)
3749         << Old << Old->getType();
3750
3751       // If this is a global redeclaration, just forget hereafter
3752       // about the "builtin-ness" of the function.
3753       //
3754       // Doing this for local extern declarations is problematic.  If
3755       // the builtin declaration remains visible, a second invalid
3756       // local declaration will produce a hard error; if it doesn't
3757       // remain visible, a single bogus local redeclaration (which is
3758       // actually only a warning) could break all the downstream code.
3759       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3760         New->getIdentifier()->revertBuiltin();
3761
3762       return false;
3763     }
3764
3765     PrevDiag = diag::note_previous_builtin_declaration;
3766   }
3767
3768   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3769   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3770   return true;
3771 }
3772
3773 /// Completes the merge of two function declarations that are
3774 /// known to be compatible.
3775 ///
3776 /// This routine handles the merging of attributes and other
3777 /// properties of function declarations from the old declaration to
3778 /// the new declaration, once we know that New is in fact a
3779 /// redeclaration of Old.
3780 ///
3781 /// \returns false
3782 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3783                                         Scope *S, bool MergeTypeWithOld) {
3784   // Merge the attributes
3785   mergeDeclAttributes(New, Old);
3786
3787   // Merge "pure" flag.
3788   if (Old->isPure())
3789     New->setPure();
3790
3791   // Merge "used" flag.
3792   if (Old->getMostRecentDecl()->isUsed(false))
3793     New->setIsUsed();
3794
3795   // Merge attributes from the parameters.  These can mismatch with K&R
3796   // declarations.
3797   if (New->getNumParams() == Old->getNumParams())
3798       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3799         ParmVarDecl *NewParam = New->getParamDecl(i);
3800         ParmVarDecl *OldParam = Old->getParamDecl(i);
3801         mergeParamDeclAttributes(NewParam, OldParam, *this);
3802         mergeParamDeclTypes(NewParam, OldParam, *this);
3803       }
3804
3805   if (getLangOpts().CPlusPlus)
3806     return MergeCXXFunctionDecl(New, Old, S);
3807
3808   // Merge the function types so the we get the composite types for the return
3809   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3810   // was visible.
3811   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3812   if (!Merged.isNull() && MergeTypeWithOld)
3813     New->setType(Merged);
3814
3815   return false;
3816 }
3817
3818 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3819                                 ObjCMethodDecl *oldMethod) {
3820   // Merge the attributes, including deprecated/unavailable
3821   AvailabilityMergeKind MergeKind =
3822     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3823       ? AMK_ProtocolImplementation
3824       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3825                                                        : AMK_Override;
3826
3827   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3828
3829   // Merge attributes from the parameters.
3830   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3831                                        oe = oldMethod->param_end();
3832   for (ObjCMethodDecl::param_iterator
3833          ni = newMethod->param_begin(), ne = newMethod->param_end();
3834        ni != ne && oi != oe; ++ni, ++oi)
3835     mergeParamDeclAttributes(*ni, *oi, *this);
3836
3837   CheckObjCMethodOverride(newMethod, oldMethod);
3838 }
3839
3840 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3841   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3842
3843   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3844          ? diag::err_redefinition_different_type
3845          : diag::err_redeclaration_different_type)
3846     << New->getDeclName() << New->getType() << Old->getType();
3847
3848   diag::kind PrevDiag;
3849   SourceLocation OldLocation;
3850   std::tie(PrevDiag, OldLocation)
3851     = getNoteDiagForInvalidRedeclaration(Old, New);
3852   S.Diag(OldLocation, PrevDiag);
3853   New->setInvalidDecl();
3854 }
3855
3856 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3857 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3858 /// emitting diagnostics as appropriate.
3859 ///
3860 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3861 /// to here in AddInitializerToDecl. We can't check them before the initializer
3862 /// is attached.
3863 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3864                              bool MergeTypeWithOld) {
3865   if (New->isInvalidDecl() || Old->isInvalidDecl())
3866     return;
3867
3868   QualType MergedT;
3869   if (getLangOpts().CPlusPlus) {
3870     if (New->getType()->isUndeducedType()) {
3871       // We don't know what the new type is until the initializer is attached.
3872       return;
3873     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3874       // These could still be something that needs exception specs checked.
3875       return MergeVarDeclExceptionSpecs(New, Old);
3876     }
3877     // C++ [basic.link]p10:
3878     //   [...] the types specified by all declarations referring to a given
3879     //   object or function shall be identical, except that declarations for an
3880     //   array object can specify array types that differ by the presence or
3881     //   absence of a major array bound (8.3.4).
3882     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3883       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3884       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3885
3886       // We are merging a variable declaration New into Old. If it has an array
3887       // bound, and that bound differs from Old's bound, we should diagnose the
3888       // mismatch.
3889       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3890         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3891              PrevVD = PrevVD->getPreviousDecl()) {
3892           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3893           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3894             continue;
3895
3896           if (!Context.hasSameType(NewArray, PrevVDTy))
3897             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3898         }
3899       }
3900
3901       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3902         if (Context.hasSameType(OldArray->getElementType(),
3903                                 NewArray->getElementType()))
3904           MergedT = New->getType();
3905       }
3906       // FIXME: Check visibility. New is hidden but has a complete type. If New
3907       // has no array bound, it should not inherit one from Old, if Old is not
3908       // visible.
3909       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3910         if (Context.hasSameType(OldArray->getElementType(),
3911                                 NewArray->getElementType()))
3912           MergedT = Old->getType();
3913       }
3914     }
3915     else if (New->getType()->isObjCObjectPointerType() &&
3916                Old->getType()->isObjCObjectPointerType()) {
3917       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3918                                               Old->getType());
3919     }
3920   } else {
3921     // C 6.2.7p2:
3922     //   All declarations that refer to the same object or function shall have
3923     //   compatible type.
3924     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3925   }
3926   if (MergedT.isNull()) {
3927     // It's OK if we couldn't merge types if either type is dependent, for a
3928     // block-scope variable. In other cases (static data members of class
3929     // templates, variable templates, ...), we require the types to be
3930     // equivalent.
3931     // FIXME: The C++ standard doesn't say anything about this.
3932     if ((New->getType()->isDependentType() ||
3933          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3934       // If the old type was dependent, we can't merge with it, so the new type
3935       // becomes dependent for now. We'll reproduce the original type when we
3936       // instantiate the TypeSourceInfo for the variable.
3937       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3938         New->setType(Context.DependentTy);
3939       return;
3940     }
3941     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3942   }
3943
3944   // Don't actually update the type on the new declaration if the old
3945   // declaration was an extern declaration in a different scope.
3946   if (MergeTypeWithOld)
3947     New->setType(MergedT);
3948 }
3949
3950 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3951                                   LookupResult &Previous) {
3952   // C11 6.2.7p4:
3953   //   For an identifier with internal or external linkage declared
3954   //   in a scope in which a prior declaration of that identifier is
3955   //   visible, if the prior declaration specifies internal or
3956   //   external linkage, the type of the identifier at the later
3957   //   declaration becomes the composite type.
3958   //
3959   // If the variable isn't visible, we do not merge with its type.
3960   if (Previous.isShadowed())
3961     return false;
3962
3963   if (S.getLangOpts().CPlusPlus) {
3964     // C++11 [dcl.array]p3:
3965     //   If there is a preceding declaration of the entity in the same
3966     //   scope in which the bound was specified, an omitted array bound
3967     //   is taken to be the same as in that earlier declaration.
3968     return NewVD->isPreviousDeclInSameBlockScope() ||
3969            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3970             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3971   } else {
3972     // If the old declaration was function-local, don't merge with its
3973     // type unless we're in the same function.
3974     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3975            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3976   }
3977 }
3978
3979 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3980 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3981 /// situation, merging decls or emitting diagnostics as appropriate.
3982 ///
3983 /// Tentative definition rules (C99 6.9.2p2) are checked by
3984 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3985 /// definitions here, since the initializer hasn't been attached.
3986 ///
3987 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3988   // If the new decl is already invalid, don't do any other checking.
3989   if (New->isInvalidDecl())
3990     return;
3991
3992   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3993     return;
3994
3995   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3996
3997   // Verify the old decl was also a variable or variable template.
3998   VarDecl *Old = nullptr;
3999   VarTemplateDecl *OldTemplate = nullptr;
4000   if (Previous.isSingleResult()) {
4001     if (NewTemplate) {
4002       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4003       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4004
4005       if (auto *Shadow =
4006               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4007         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4008           return New->setInvalidDecl();
4009     } else {
4010       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4011
4012       if (auto *Shadow =
4013               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4014         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4015           return New->setInvalidDecl();
4016     }
4017   }
4018   if (!Old) {
4019     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4020         << New->getDeclName();
4021     notePreviousDefinition(Previous.getRepresentativeDecl(),
4022                            New->getLocation());
4023     return New->setInvalidDecl();
4024   }
4025
4026   // Ensure the template parameters are compatible.
4027   if (NewTemplate &&
4028       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4029                                       OldTemplate->getTemplateParameters(),
4030                                       /*Complain=*/true, TPL_TemplateMatch))
4031     return New->setInvalidDecl();
4032
4033   // C++ [class.mem]p1:
4034   //   A member shall not be declared twice in the member-specification [...]
4035   //
4036   // Here, we need only consider static data members.
4037   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4038     Diag(New->getLocation(), diag::err_duplicate_member)
4039       << New->getIdentifier();
4040     Diag(Old->getLocation(), diag::note_previous_declaration);
4041     New->setInvalidDecl();
4042   }
4043
4044   mergeDeclAttributes(New, Old);
4045   // Warn if an already-declared variable is made a weak_import in a subsequent
4046   // declaration
4047   if (New->hasAttr<WeakImportAttr>() &&
4048       Old->getStorageClass() == SC_None &&
4049       !Old->hasAttr<WeakImportAttr>()) {
4050     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4051     notePreviousDefinition(Old, New->getLocation());
4052     // Remove weak_import attribute on new declaration.
4053     New->dropAttr<WeakImportAttr>();
4054   }
4055
4056   if (New->hasAttr<InternalLinkageAttr>() &&
4057       !Old->hasAttr<InternalLinkageAttr>()) {
4058     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4059         << New->getDeclName();
4060     notePreviousDefinition(Old, New->getLocation());
4061     New->dropAttr<InternalLinkageAttr>();
4062   }
4063
4064   // Merge the types.
4065   VarDecl *MostRecent = Old->getMostRecentDecl();
4066   if (MostRecent != Old) {
4067     MergeVarDeclTypes(New, MostRecent,
4068                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4069     if (New->isInvalidDecl())
4070       return;
4071   }
4072
4073   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4074   if (New->isInvalidDecl())
4075     return;
4076
4077   diag::kind PrevDiag;
4078   SourceLocation OldLocation;
4079   std::tie(PrevDiag, OldLocation) =
4080       getNoteDiagForInvalidRedeclaration(Old, New);
4081
4082   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4083   if (New->getStorageClass() == SC_Static &&
4084       !New->isStaticDataMember() &&
4085       Old->hasExternalFormalLinkage()) {
4086     if (getLangOpts().MicrosoftExt) {
4087       Diag(New->getLocation(), diag::ext_static_non_static)
4088           << New->getDeclName();
4089       Diag(OldLocation, PrevDiag);
4090     } else {
4091       Diag(New->getLocation(), diag::err_static_non_static)
4092           << New->getDeclName();
4093       Diag(OldLocation, PrevDiag);
4094       return New->setInvalidDecl();
4095     }
4096   }
4097   // C99 6.2.2p4:
4098   //   For an identifier declared with the storage-class specifier
4099   //   extern in a scope in which a prior declaration of that
4100   //   identifier is visible,23) if the prior declaration specifies
4101   //   internal or external linkage, the linkage of the identifier at
4102   //   the later declaration is the same as the linkage specified at
4103   //   the prior declaration. If no prior declaration is visible, or
4104   //   if the prior declaration specifies no linkage, then the
4105   //   identifier has external linkage.
4106   if (New->hasExternalStorage() && Old->hasLinkage())
4107     /* Okay */;
4108   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4109            !New->isStaticDataMember() &&
4110            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4111     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4112     Diag(OldLocation, PrevDiag);
4113     return New->setInvalidDecl();
4114   }
4115
4116   // Check if extern is followed by non-extern and vice-versa.
4117   if (New->hasExternalStorage() &&
4118       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4119     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4120     Diag(OldLocation, PrevDiag);
4121     return New->setInvalidDecl();
4122   }
4123   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4124       !New->hasExternalStorage()) {
4125     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4126     Diag(OldLocation, PrevDiag);
4127     return New->setInvalidDecl();
4128   }
4129
4130   if (CheckRedeclarationModuleOwnership(New, Old))
4131     return;
4132
4133   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4134
4135   // FIXME: The test for external storage here seems wrong? We still
4136   // need to check for mismatches.
4137   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4138       // Don't complain about out-of-line definitions of static members.
4139       !(Old->getLexicalDeclContext()->isRecord() &&
4140         !New->getLexicalDeclContext()->isRecord())) {
4141     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4142     Diag(OldLocation, PrevDiag);
4143     return New->setInvalidDecl();
4144   }
4145
4146   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4147     if (VarDecl *Def = Old->getDefinition()) {
4148       // C++1z [dcl.fcn.spec]p4:
4149       //   If the definition of a variable appears in a translation unit before
4150       //   its first declaration as inline, the program is ill-formed.
4151       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4152       Diag(Def->getLocation(), diag::note_previous_definition);
4153     }
4154   }
4155
4156   // If this redeclaration makes the variable inline, we may need to add it to
4157   // UndefinedButUsed.
4158   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4159       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4160     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4161                                            SourceLocation()));
4162
4163   if (New->getTLSKind() != Old->getTLSKind()) {
4164     if (!Old->getTLSKind()) {
4165       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4166       Diag(OldLocation, PrevDiag);
4167     } else if (!New->getTLSKind()) {
4168       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4169       Diag(OldLocation, PrevDiag);
4170     } else {
4171       // Do not allow redeclaration to change the variable between requiring
4172       // static and dynamic initialization.
4173       // FIXME: GCC allows this, but uses the TLS keyword on the first
4174       // declaration to determine the kind. Do we need to be compatible here?
4175       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4176         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4177       Diag(OldLocation, PrevDiag);
4178     }
4179   }
4180
4181   // C++ doesn't have tentative definitions, so go right ahead and check here.
4182   if (getLangOpts().CPlusPlus &&
4183       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4184     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4185         Old->getCanonicalDecl()->isConstexpr()) {
4186       // This definition won't be a definition any more once it's been merged.
4187       Diag(New->getLocation(),
4188            diag::warn_deprecated_redundant_constexpr_static_def);
4189     } else if (VarDecl *Def = Old->getDefinition()) {
4190       if (checkVarDeclRedefinition(Def, New))
4191         return;
4192     }
4193   }
4194
4195   if (haveIncompatibleLanguageLinkages(Old, New)) {
4196     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4197     Diag(OldLocation, PrevDiag);
4198     New->setInvalidDecl();
4199     return;
4200   }
4201
4202   // Merge "used" flag.
4203   if (Old->getMostRecentDecl()->isUsed(false))
4204     New->setIsUsed();
4205
4206   // Keep a chain of previous declarations.
4207   New->setPreviousDecl(Old);
4208   if (NewTemplate)
4209     NewTemplate->setPreviousDecl(OldTemplate);
4210   adjustDeclContextForDeclaratorDecl(New, Old);
4211
4212   // Inherit access appropriately.
4213   New->setAccess(Old->getAccess());
4214   if (NewTemplate)
4215     NewTemplate->setAccess(New->getAccess());
4216
4217   if (Old->isInline())
4218     New->setImplicitlyInline();
4219 }
4220
4221 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4222   SourceManager &SrcMgr = getSourceManager();
4223   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4224   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4225   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4226   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4227   auto &HSI = PP.getHeaderSearchInfo();
4228   StringRef HdrFilename =
4229       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4230
4231   auto noteFromModuleOrInclude = [&](Module *Mod,
4232                                      SourceLocation IncLoc) -> bool {
4233     // Redefinition errors with modules are common with non modular mapped
4234     // headers, example: a non-modular header H in module A that also gets
4235     // included directly in a TU. Pointing twice to the same header/definition
4236     // is confusing, try to get better diagnostics when modules is on.
4237     if (IncLoc.isValid()) {
4238       if (Mod) {
4239         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4240             << HdrFilename.str() << Mod->getFullModuleName();
4241         if (!Mod->DefinitionLoc.isInvalid())
4242           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4243               << Mod->getFullModuleName();
4244       } else {
4245         Diag(IncLoc, diag::note_redefinition_include_same_file)
4246             << HdrFilename.str();
4247       }
4248       return true;
4249     }
4250
4251     return false;
4252   };
4253
4254   // Is it the same file and same offset? Provide more information on why
4255   // this leads to a redefinition error.
4256   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4257     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4258     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4259     bool EmittedDiag =
4260         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4261     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4262
4263     // If the header has no guards, emit a note suggesting one.
4264     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4265       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4266
4267     if (EmittedDiag)
4268       return;
4269   }
4270
4271   // Redefinition coming from different files or couldn't do better above.
4272   if (Old->getLocation().isValid())
4273     Diag(Old->getLocation(), diag::note_previous_definition);
4274 }
4275
4276 /// We've just determined that \p Old and \p New both appear to be definitions
4277 /// of the same variable. Either diagnose or fix the problem.
4278 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4279   if (!hasVisibleDefinition(Old) &&
4280       (New->getFormalLinkage() == InternalLinkage ||
4281        New->isInline() ||
4282        New->getDescribedVarTemplate() ||
4283        New->getNumTemplateParameterLists() ||
4284        New->getDeclContext()->isDependentContext())) {
4285     // The previous definition is hidden, and multiple definitions are
4286     // permitted (in separate TUs). Demote this to a declaration.
4287     New->demoteThisDefinitionToDeclaration();
4288
4289     // Make the canonical definition visible.
4290     if (auto *OldTD = Old->getDescribedVarTemplate())
4291       makeMergedDefinitionVisible(OldTD);
4292     makeMergedDefinitionVisible(Old);
4293     return false;
4294   } else {
4295     Diag(New->getLocation(), diag::err_redefinition) << New;
4296     notePreviousDefinition(Old, New->getLocation());
4297     New->setInvalidDecl();
4298     return true;
4299   }
4300 }
4301
4302 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4303 /// no declarator (e.g. "struct foo;") is parsed.
4304 Decl *
4305 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4306                                  RecordDecl *&AnonRecord) {
4307   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4308                                     AnonRecord);
4309 }
4310
4311 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4312 // disambiguate entities defined in different scopes.
4313 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4314 // compatibility.
4315 // We will pick our mangling number depending on which version of MSVC is being
4316 // targeted.
4317 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4318   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4319              ? S->getMSCurManglingNumber()
4320              : S->getMSLastManglingNumber();
4321 }
4322
4323 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4324   if (!Context.getLangOpts().CPlusPlus)
4325     return;
4326
4327   if (isa<CXXRecordDecl>(Tag->getParent())) {
4328     // If this tag is the direct child of a class, number it if
4329     // it is anonymous.
4330     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4331       return;
4332     MangleNumberingContext &MCtx =
4333         Context.getManglingNumberContext(Tag->getParent());
4334     Context.setManglingNumber(
4335         Tag, MCtx.getManglingNumber(
4336                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4337     return;
4338   }
4339
4340   // If this tag isn't a direct child of a class, number it if it is local.
4341   MangleNumberingContext *MCtx;
4342   Decl *ManglingContextDecl;
4343   std::tie(MCtx, ManglingContextDecl) =
4344       getCurrentMangleNumberContext(Tag->getDeclContext());
4345   if (MCtx) {
4346     Context.setManglingNumber(
4347         Tag, MCtx->getManglingNumber(
4348                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4349   }
4350 }
4351
4352 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4353                                         TypedefNameDecl *NewTD) {
4354   if (TagFromDeclSpec->isInvalidDecl())
4355     return;
4356
4357   // Do nothing if the tag already has a name for linkage purposes.
4358   if (TagFromDeclSpec->hasNameForLinkage())
4359     return;
4360
4361   // A well-formed anonymous tag must always be a TUK_Definition.
4362   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4363
4364   // The type must match the tag exactly;  no qualifiers allowed.
4365   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4366                            Context.getTagDeclType(TagFromDeclSpec))) {
4367     if (getLangOpts().CPlusPlus)
4368       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4369     return;
4370   }
4371
4372   // If we've already computed linkage for the anonymous tag, then
4373   // adding a typedef name for the anonymous decl can change that
4374   // linkage, which might be a serious problem.  Diagnose this as
4375   // unsupported and ignore the typedef name.  TODO: we should
4376   // pursue this as a language defect and establish a formal rule
4377   // for how to handle it.
4378   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4379     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4380
4381     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4382     tagLoc = getLocForEndOfToken(tagLoc);
4383
4384     llvm::SmallString<40> textToInsert;
4385     textToInsert += ' ';
4386     textToInsert += NewTD->getIdentifier()->getName();
4387     Diag(tagLoc, diag::note_typedef_changes_linkage)
4388         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4389     return;
4390   }
4391
4392   // Otherwise, set this is the anon-decl typedef for the tag.
4393   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4394 }
4395
4396 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4397   switch (T) {
4398   case DeclSpec::TST_class:
4399     return 0;
4400   case DeclSpec::TST_struct:
4401     return 1;
4402   case DeclSpec::TST_interface:
4403     return 2;
4404   case DeclSpec::TST_union:
4405     return 3;
4406   case DeclSpec::TST_enum:
4407     return 4;
4408   default:
4409     llvm_unreachable("unexpected type specifier");
4410   }
4411 }
4412
4413 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4414 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4415 /// parameters to cope with template friend declarations.
4416 Decl *
4417 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4418                                  MultiTemplateParamsArg TemplateParams,
4419                                  bool IsExplicitInstantiation,
4420                                  RecordDecl *&AnonRecord) {
4421   Decl *TagD = nullptr;
4422   TagDecl *Tag = nullptr;
4423   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4424       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4425       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4426       DS.getTypeSpecType() == DeclSpec::TST_union ||
4427       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4428     TagD = DS.getRepAsDecl();
4429
4430     if (!TagD) // We probably had an error
4431       return nullptr;
4432
4433     // Note that the above type specs guarantee that the
4434     // type rep is a Decl, whereas in many of the others
4435     // it's a Type.
4436     if (isa<TagDecl>(TagD))
4437       Tag = cast<TagDecl>(TagD);
4438     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4439       Tag = CTD->getTemplatedDecl();
4440   }
4441
4442   if (Tag) {
4443     handleTagNumbering(Tag, S);
4444     Tag->setFreeStanding();
4445     if (Tag->isInvalidDecl())
4446       return Tag;
4447   }
4448
4449   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4450     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4451     // or incomplete types shall not be restrict-qualified."
4452     if (TypeQuals & DeclSpec::TQ_restrict)
4453       Diag(DS.getRestrictSpecLoc(),
4454            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4455            << DS.getSourceRange();
4456   }
4457
4458   if (DS.isInlineSpecified())
4459     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4460         << getLangOpts().CPlusPlus17;
4461
4462   if (DS.hasConstexprSpecifier()) {
4463     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4464     // and definitions of functions and variables.
4465     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4466     // the declaration of a function or function template
4467     if (Tag)
4468       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4469           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4470           << DS.getConstexprSpecifier();
4471     else
4472       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4473           << DS.getConstexprSpecifier();
4474     // Don't emit warnings after this error.
4475     return TagD;
4476   }
4477
4478   DiagnoseFunctionSpecifiers(DS);
4479
4480   if (DS.isFriendSpecified()) {
4481     // If we're dealing with a decl but not a TagDecl, assume that
4482     // whatever routines created it handled the friendship aspect.
4483     if (TagD && !Tag)
4484       return nullptr;
4485     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4486   }
4487
4488   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4489   bool IsExplicitSpecialization =
4490     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4491   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4492       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4493       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4494     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4495     // nested-name-specifier unless it is an explicit instantiation
4496     // or an explicit specialization.
4497     //
4498     // FIXME: We allow class template partial specializations here too, per the
4499     // obvious intent of DR1819.
4500     //
4501     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4502     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4503         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4504     return nullptr;
4505   }
4506
4507   // Track whether this decl-specifier declares anything.
4508   bool DeclaresAnything = true;
4509
4510   // Handle anonymous struct definitions.
4511   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4512     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4513         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4514       if (getLangOpts().CPlusPlus ||
4515           Record->getDeclContext()->isRecord()) {
4516         // If CurContext is a DeclContext that can contain statements,
4517         // RecursiveASTVisitor won't visit the decls that
4518         // BuildAnonymousStructOrUnion() will put into CurContext.
4519         // Also store them here so that they can be part of the
4520         // DeclStmt that gets created in this case.
4521         // FIXME: Also return the IndirectFieldDecls created by
4522         // BuildAnonymousStructOr union, for the same reason?
4523         if (CurContext->isFunctionOrMethod())
4524           AnonRecord = Record;
4525         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4526                                            Context.getPrintingPolicy());
4527       }
4528
4529       DeclaresAnything = false;
4530     }
4531   }
4532
4533   // C11 6.7.2.1p2:
4534   //   A struct-declaration that does not declare an anonymous structure or
4535   //   anonymous union shall contain a struct-declarator-list.
4536   //
4537   // This rule also existed in C89 and C99; the grammar for struct-declaration
4538   // did not permit a struct-declaration without a struct-declarator-list.
4539   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4540       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4541     // Check for Microsoft C extension: anonymous struct/union member.
4542     // Handle 2 kinds of anonymous struct/union:
4543     //   struct STRUCT;
4544     //   union UNION;
4545     // and
4546     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4547     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4548     if ((Tag && Tag->getDeclName()) ||
4549         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4550       RecordDecl *Record = nullptr;
4551       if (Tag)
4552         Record = dyn_cast<RecordDecl>(Tag);
4553       else if (const RecordType *RT =
4554                    DS.getRepAsType().get()->getAsStructureType())
4555         Record = RT->getDecl();
4556       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4557         Record = UT->getDecl();
4558
4559       if (Record && getLangOpts().MicrosoftExt) {
4560         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4561             << Record->isUnion() << DS.getSourceRange();
4562         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4563       }
4564
4565       DeclaresAnything = false;
4566     }
4567   }
4568
4569   // Skip all the checks below if we have a type error.
4570   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4571       (TagD && TagD->isInvalidDecl()))
4572     return TagD;
4573
4574   if (getLangOpts().CPlusPlus &&
4575       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4576     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4577       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4578           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4579         DeclaresAnything = false;
4580
4581   if (!DS.isMissingDeclaratorOk()) {
4582     // Customize diagnostic for a typedef missing a name.
4583     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4584       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4585           << DS.getSourceRange();
4586     else
4587       DeclaresAnything = false;
4588   }
4589
4590   if (DS.isModulePrivateSpecified() &&
4591       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4592     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4593       << Tag->getTagKind()
4594       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4595
4596   ActOnDocumentableDecl(TagD);
4597
4598   // C 6.7/2:
4599   //   A declaration [...] shall declare at least a declarator [...], a tag,
4600   //   or the members of an enumeration.
4601   // C++ [dcl.dcl]p3:
4602   //   [If there are no declarators], and except for the declaration of an
4603   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4604   //   names into the program, or shall redeclare a name introduced by a
4605   //   previous declaration.
4606   if (!DeclaresAnything) {
4607     // In C, we allow this as a (popular) extension / bug. Don't bother
4608     // producing further diagnostics for redundant qualifiers after this.
4609     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4610     return TagD;
4611   }
4612
4613   // C++ [dcl.stc]p1:
4614   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4615   //   init-declarator-list of the declaration shall not be empty.
4616   // C++ [dcl.fct.spec]p1:
4617   //   If a cv-qualifier appears in a decl-specifier-seq, the
4618   //   init-declarator-list of the declaration shall not be empty.
4619   //
4620   // Spurious qualifiers here appear to be valid in C.
4621   unsigned DiagID = diag::warn_standalone_specifier;
4622   if (getLangOpts().CPlusPlus)
4623     DiagID = diag::ext_standalone_specifier;
4624
4625   // Note that a linkage-specification sets a storage class, but
4626   // 'extern "C" struct foo;' is actually valid and not theoretically
4627   // useless.
4628   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4629     if (SCS == DeclSpec::SCS_mutable)
4630       // Since mutable is not a viable storage class specifier in C, there is
4631       // no reason to treat it as an extension. Instead, diagnose as an error.
4632       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4633     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4634       Diag(DS.getStorageClassSpecLoc(), DiagID)
4635         << DeclSpec::getSpecifierName(SCS);
4636   }
4637
4638   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4639     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4640       << DeclSpec::getSpecifierName(TSCS);
4641   if (DS.getTypeQualifiers()) {
4642     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4643       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4644     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4645       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4646     // Restrict is covered above.
4647     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4648       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4649     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4650       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4651   }
4652
4653   // Warn about ignored type attributes, for example:
4654   // __attribute__((aligned)) struct A;
4655   // Attributes should be placed after tag to apply to type declaration.
4656   if (!DS.getAttributes().empty()) {
4657     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4658     if (TypeSpecType == DeclSpec::TST_class ||
4659         TypeSpecType == DeclSpec::TST_struct ||
4660         TypeSpecType == DeclSpec::TST_interface ||
4661         TypeSpecType == DeclSpec::TST_union ||
4662         TypeSpecType == DeclSpec::TST_enum) {
4663       for (const ParsedAttr &AL : DS.getAttributes())
4664         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4665             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4666     }
4667   }
4668
4669   return TagD;
4670 }
4671
4672 /// We are trying to inject an anonymous member into the given scope;
4673 /// check if there's an existing declaration that can't be overloaded.
4674 ///
4675 /// \return true if this is a forbidden redeclaration
4676 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4677                                          Scope *S,
4678                                          DeclContext *Owner,
4679                                          DeclarationName Name,
4680                                          SourceLocation NameLoc,
4681                                          bool IsUnion) {
4682   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4683                  Sema::ForVisibleRedeclaration);
4684   if (!SemaRef.LookupName(R, S)) return false;
4685
4686   // Pick a representative declaration.
4687   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4688   assert(PrevDecl && "Expected a non-null Decl");
4689
4690   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4691     return false;
4692
4693   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4694     << IsUnion << Name;
4695   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4696
4697   return true;
4698 }
4699
4700 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4701 /// anonymous struct or union AnonRecord into the owning context Owner
4702 /// and scope S. This routine will be invoked just after we realize
4703 /// that an unnamed union or struct is actually an anonymous union or
4704 /// struct, e.g.,
4705 ///
4706 /// @code
4707 /// union {
4708 ///   int i;
4709 ///   float f;
4710 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4711 ///    // f into the surrounding scope.x
4712 /// @endcode
4713 ///
4714 /// This routine is recursive, injecting the names of nested anonymous
4715 /// structs/unions into the owning context and scope as well.
4716 static bool
4717 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4718                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4719                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4720   bool Invalid = false;
4721
4722   // Look every FieldDecl and IndirectFieldDecl with a name.
4723   for (auto *D : AnonRecord->decls()) {
4724     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4725         cast<NamedDecl>(D)->getDeclName()) {
4726       ValueDecl *VD = cast<ValueDecl>(D);
4727       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4728                                        VD->getLocation(),
4729                                        AnonRecord->isUnion())) {
4730         // C++ [class.union]p2:
4731         //   The names of the members of an anonymous union shall be
4732         //   distinct from the names of any other entity in the
4733         //   scope in which the anonymous union is declared.
4734         Invalid = true;
4735       } else {
4736         // C++ [class.union]p2:
4737         //   For the purpose of name lookup, after the anonymous union
4738         //   definition, the members of the anonymous union are
4739         //   considered to have been defined in the scope in which the
4740         //   anonymous union is declared.
4741         unsigned OldChainingSize = Chaining.size();
4742         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4743           Chaining.append(IF->chain_begin(), IF->chain_end());
4744         else
4745           Chaining.push_back(VD);
4746
4747         assert(Chaining.size() >= 2);
4748         NamedDecl **NamedChain =
4749           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4750         for (unsigned i = 0; i < Chaining.size(); i++)
4751           NamedChain[i] = Chaining[i];
4752
4753         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4754             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4755             VD->getType(), {NamedChain, Chaining.size()});
4756
4757         for (const auto *Attr : VD->attrs())
4758           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4759
4760         IndirectField->setAccess(AS);
4761         IndirectField->setImplicit();
4762         SemaRef.PushOnScopeChains(IndirectField, S);
4763
4764         // That includes picking up the appropriate access specifier.
4765         if (AS != AS_none) IndirectField->setAccess(AS);
4766
4767         Chaining.resize(OldChainingSize);
4768       }
4769     }
4770   }
4771
4772   return Invalid;
4773 }
4774
4775 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4776 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4777 /// illegal input values are mapped to SC_None.
4778 static StorageClass
4779 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4780   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4781   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4782          "Parser allowed 'typedef' as storage class VarDecl.");
4783   switch (StorageClassSpec) {
4784   case DeclSpec::SCS_unspecified:    return SC_None;
4785   case DeclSpec::SCS_extern:
4786     if (DS.isExternInLinkageSpec())
4787       return SC_None;
4788     return SC_Extern;
4789   case DeclSpec::SCS_static:         return SC_Static;
4790   case DeclSpec::SCS_auto:           return SC_Auto;
4791   case DeclSpec::SCS_register:       return SC_Register;
4792   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4793     // Illegal SCSs map to None: error reporting is up to the caller.
4794   case DeclSpec::SCS_mutable:        // Fall through.
4795   case DeclSpec::SCS_typedef:        return SC_None;
4796   }
4797   llvm_unreachable("unknown storage class specifier");
4798 }
4799
4800 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4801   assert(Record->hasInClassInitializer());
4802
4803   for (const auto *I : Record->decls()) {
4804     const auto *FD = dyn_cast<FieldDecl>(I);
4805     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4806       FD = IFD->getAnonField();
4807     if (FD && FD->hasInClassInitializer())
4808       return FD->getLocation();
4809   }
4810
4811   llvm_unreachable("couldn't find in-class initializer");
4812 }
4813
4814 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4815                                       SourceLocation DefaultInitLoc) {
4816   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4817     return;
4818
4819   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4820   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4821 }
4822
4823 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4824                                       CXXRecordDecl *AnonUnion) {
4825   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4826     return;
4827
4828   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4829 }
4830
4831 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4832 /// anonymous structure or union. Anonymous unions are a C++ feature
4833 /// (C++ [class.union]) and a C11 feature; anonymous structures
4834 /// are a C11 feature and GNU C++ extension.
4835 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4836                                         AccessSpecifier AS,
4837                                         RecordDecl *Record,
4838                                         const PrintingPolicy &Policy) {
4839   DeclContext *Owner = Record->getDeclContext();
4840
4841   // Diagnose whether this anonymous struct/union is an extension.
4842   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4843     Diag(Record->getLocation(), diag::ext_anonymous_union);
4844   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4845     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4846   else if (!Record->isUnion() && !getLangOpts().C11)
4847     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4848
4849   // C and C++ require different kinds of checks for anonymous
4850   // structs/unions.
4851   bool Invalid = false;
4852   if (getLangOpts().CPlusPlus) {
4853     const char *PrevSpec = nullptr;
4854     if (Record->isUnion()) {
4855       // C++ [class.union]p6:
4856       // C++17 [class.union.anon]p2:
4857       //   Anonymous unions declared in a named namespace or in the
4858       //   global namespace shall be declared static.
4859       unsigned DiagID;
4860       DeclContext *OwnerScope = Owner->getRedeclContext();
4861       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4862           (OwnerScope->isTranslationUnit() ||
4863            (OwnerScope->isNamespace() &&
4864             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4865         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4866           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4867
4868         // Recover by adding 'static'.
4869         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4870                                PrevSpec, DiagID, Policy);
4871       }
4872       // C++ [class.union]p6:
4873       //   A storage class is not allowed in a declaration of an
4874       //   anonymous union in a class scope.
4875       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4876                isa<RecordDecl>(Owner)) {
4877         Diag(DS.getStorageClassSpecLoc(),
4878              diag::err_anonymous_union_with_storage_spec)
4879           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4880
4881         // Recover by removing the storage specifier.
4882         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4883                                SourceLocation(),
4884                                PrevSpec, DiagID, Context.getPrintingPolicy());
4885       }
4886     }
4887
4888     // Ignore const/volatile/restrict qualifiers.
4889     if (DS.getTypeQualifiers()) {
4890       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4891         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4892           << Record->isUnion() << "const"
4893           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4894       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4895         Diag(DS.getVolatileSpecLoc(),
4896              diag::ext_anonymous_struct_union_qualified)
4897           << Record->isUnion() << "volatile"
4898           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4899       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4900         Diag(DS.getRestrictSpecLoc(),
4901              diag::ext_anonymous_struct_union_qualified)
4902           << Record->isUnion() << "restrict"
4903           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4904       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4905         Diag(DS.getAtomicSpecLoc(),
4906              diag::ext_anonymous_struct_union_qualified)
4907           << Record->isUnion() << "_Atomic"
4908           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4909       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4910         Diag(DS.getUnalignedSpecLoc(),
4911              diag::ext_anonymous_struct_union_qualified)
4912           << Record->isUnion() << "__unaligned"
4913           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4914
4915       DS.ClearTypeQualifiers();
4916     }
4917
4918     // C++ [class.union]p2:
4919     //   The member-specification of an anonymous union shall only
4920     //   define non-static data members. [Note: nested types and
4921     //   functions cannot be declared within an anonymous union. ]
4922     for (auto *Mem : Record->decls()) {
4923       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4924         // C++ [class.union]p3:
4925         //   An anonymous union shall not have private or protected
4926         //   members (clause 11).
4927         assert(FD->getAccess() != AS_none);
4928         if (FD->getAccess() != AS_public) {
4929           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4930             << Record->isUnion() << (FD->getAccess() == AS_protected);
4931           Invalid = true;
4932         }
4933
4934         // C++ [class.union]p1
4935         //   An object of a class with a non-trivial constructor, a non-trivial
4936         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4937         //   assignment operator cannot be a member of a union, nor can an
4938         //   array of such objects.
4939         if (CheckNontrivialField(FD))
4940           Invalid = true;
4941       } else if (Mem->isImplicit()) {
4942         // Any implicit members are fine.
4943       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4944         // This is a type that showed up in an
4945         // elaborated-type-specifier inside the anonymous struct or
4946         // union, but which actually declares a type outside of the
4947         // anonymous struct or union. It's okay.
4948       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4949         if (!MemRecord->isAnonymousStructOrUnion() &&
4950             MemRecord->getDeclName()) {
4951           // Visual C++ allows type definition in anonymous struct or union.
4952           if (getLangOpts().MicrosoftExt)
4953             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4954               << Record->isUnion();
4955           else {
4956             // This is a nested type declaration.
4957             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4958               << Record->isUnion();
4959             Invalid = true;
4960           }
4961         } else {
4962           // This is an anonymous type definition within another anonymous type.
4963           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4964           // not part of standard C++.
4965           Diag(MemRecord->getLocation(),
4966                diag::ext_anonymous_record_with_anonymous_type)
4967             << Record->isUnion();
4968         }
4969       } else if (isa<AccessSpecDecl>(Mem)) {
4970         // Any access specifier is fine.
4971       } else if (isa<StaticAssertDecl>(Mem)) {
4972         // In C++1z, static_assert declarations are also fine.
4973       } else {
4974         // We have something that isn't a non-static data
4975         // member. Complain about it.
4976         unsigned DK = diag::err_anonymous_record_bad_member;
4977         if (isa<TypeDecl>(Mem))
4978           DK = diag::err_anonymous_record_with_type;
4979         else if (isa<FunctionDecl>(Mem))
4980           DK = diag::err_anonymous_record_with_function;
4981         else if (isa<VarDecl>(Mem))
4982           DK = diag::err_anonymous_record_with_static;
4983
4984         // Visual C++ allows type definition in anonymous struct or union.
4985         if (getLangOpts().MicrosoftExt &&
4986             DK == diag::err_anonymous_record_with_type)
4987           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4988             << Record->isUnion();
4989         else {
4990           Diag(Mem->getLocation(), DK) << Record->isUnion();
4991           Invalid = true;
4992         }
4993       }
4994     }
4995
4996     // C++11 [class.union]p8 (DR1460):
4997     //   At most one variant member of a union may have a
4998     //   brace-or-equal-initializer.
4999     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5000         Owner->isRecord())
5001       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5002                                 cast<CXXRecordDecl>(Record));
5003   }
5004
5005   if (!Record->isUnion() && !Owner->isRecord()) {
5006     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5007       << getLangOpts().CPlusPlus;
5008     Invalid = true;
5009   }
5010
5011   // C++ [dcl.dcl]p3:
5012   //   [If there are no declarators], and except for the declaration of an
5013   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5014   //   names into the program
5015   // C++ [class.mem]p2:
5016   //   each such member-declaration shall either declare at least one member
5017   //   name of the class or declare at least one unnamed bit-field
5018   //
5019   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5020   if (getLangOpts().CPlusPlus && Record->field_empty())
5021     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5022
5023   // Mock up a declarator.
5024   Declarator Dc(DS, DeclaratorContext::MemberContext);
5025   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5026   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5027
5028   // Create a declaration for this anonymous struct/union.
5029   NamedDecl *Anon = nullptr;
5030   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5031     Anon = FieldDecl::Create(
5032         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5033         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5034         /*BitWidth=*/nullptr, /*Mutable=*/false,
5035         /*InitStyle=*/ICIS_NoInit);
5036     Anon->setAccess(AS);
5037     ProcessDeclAttributes(S, Anon, Dc);
5038
5039     if (getLangOpts().CPlusPlus)
5040       FieldCollector->Add(cast<FieldDecl>(Anon));
5041   } else {
5042     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5043     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5044     if (SCSpec == DeclSpec::SCS_mutable) {
5045       // mutable can only appear on non-static class members, so it's always
5046       // an error here
5047       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5048       Invalid = true;
5049       SC = SC_None;
5050     }
5051
5052     assert(DS.getAttributes().empty() && "No attribute expected");
5053     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5054                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5055                            Context.getTypeDeclType(Record), TInfo, SC);
5056
5057     // Default-initialize the implicit variable. This initialization will be
5058     // trivial in almost all cases, except if a union member has an in-class
5059     // initializer:
5060     //   union { int n = 0; };
5061     ActOnUninitializedDecl(Anon);
5062   }
5063   Anon->setImplicit();
5064
5065   // Mark this as an anonymous struct/union type.
5066   Record->setAnonymousStructOrUnion(true);
5067
5068   // Add the anonymous struct/union object to the current
5069   // context. We'll be referencing this object when we refer to one of
5070   // its members.
5071   Owner->addDecl(Anon);
5072
5073   // Inject the members of the anonymous struct/union into the owning
5074   // context and into the identifier resolver chain for name lookup
5075   // purposes.
5076   SmallVector<NamedDecl*, 2> Chain;
5077   Chain.push_back(Anon);
5078
5079   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5080     Invalid = true;
5081
5082   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5083     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5084       MangleNumberingContext *MCtx;
5085       Decl *ManglingContextDecl;
5086       std::tie(MCtx, ManglingContextDecl) =
5087           getCurrentMangleNumberContext(NewVD->getDeclContext());
5088       if (MCtx) {
5089         Context.setManglingNumber(
5090             NewVD, MCtx->getManglingNumber(
5091                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5092         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5093       }
5094     }
5095   }
5096
5097   if (Invalid)
5098     Anon->setInvalidDecl();
5099
5100   return Anon;
5101 }
5102
5103 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5104 /// Microsoft C anonymous structure.
5105 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5106 /// Example:
5107 ///
5108 /// struct A { int a; };
5109 /// struct B { struct A; int b; };
5110 ///
5111 /// void foo() {
5112 ///   B var;
5113 ///   var.a = 3;
5114 /// }
5115 ///
5116 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5117                                            RecordDecl *Record) {
5118   assert(Record && "expected a record!");
5119
5120   // Mock up a declarator.
5121   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5122   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5123   assert(TInfo && "couldn't build declarator info for anonymous struct");
5124
5125   auto *ParentDecl = cast<RecordDecl>(CurContext);
5126   QualType RecTy = Context.getTypeDeclType(Record);
5127
5128   // Create a declaration for this anonymous struct.
5129   NamedDecl *Anon =
5130       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5131                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5132                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5133                         /*InitStyle=*/ICIS_NoInit);
5134   Anon->setImplicit();
5135
5136   // Add the anonymous struct object to the current context.
5137   CurContext->addDecl(Anon);
5138
5139   // Inject the members of the anonymous struct into the current
5140   // context and into the identifier resolver chain for name lookup
5141   // purposes.
5142   SmallVector<NamedDecl*, 2> Chain;
5143   Chain.push_back(Anon);
5144
5145   RecordDecl *RecordDef = Record->getDefinition();
5146   if (RequireCompleteType(Anon->getLocation(), RecTy,
5147                           diag::err_field_incomplete) ||
5148       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5149                                           AS_none, Chain)) {
5150     Anon->setInvalidDecl();
5151     ParentDecl->setInvalidDecl();
5152   }
5153
5154   return Anon;
5155 }
5156
5157 /// GetNameForDeclarator - Determine the full declaration name for the
5158 /// given Declarator.
5159 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5160   return GetNameFromUnqualifiedId(D.getName());
5161 }
5162
5163 /// Retrieves the declaration name from a parsed unqualified-id.
5164 DeclarationNameInfo
5165 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5166   DeclarationNameInfo NameInfo;
5167   NameInfo.setLoc(Name.StartLocation);
5168
5169   switch (Name.getKind()) {
5170
5171   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5172   case UnqualifiedIdKind::IK_Identifier:
5173     NameInfo.setName(Name.Identifier);
5174     return NameInfo;
5175
5176   case UnqualifiedIdKind::IK_DeductionGuideName: {
5177     // C++ [temp.deduct.guide]p3:
5178     //   The simple-template-id shall name a class template specialization.
5179     //   The template-name shall be the same identifier as the template-name
5180     //   of the simple-template-id.
5181     // These together intend to imply that the template-name shall name a
5182     // class template.
5183     // FIXME: template<typename T> struct X {};
5184     //        template<typename T> using Y = X<T>;
5185     //        Y(int) -> Y<int>;
5186     //   satisfies these rules but does not name a class template.
5187     TemplateName TN = Name.TemplateName.get().get();
5188     auto *Template = TN.getAsTemplateDecl();
5189     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5190       Diag(Name.StartLocation,
5191            diag::err_deduction_guide_name_not_class_template)
5192         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5193       if (Template)
5194         Diag(Template->getLocation(), diag::note_template_decl_here);
5195       return DeclarationNameInfo();
5196     }
5197
5198     NameInfo.setName(
5199         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5200     return NameInfo;
5201   }
5202
5203   case UnqualifiedIdKind::IK_OperatorFunctionId:
5204     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5205                                            Name.OperatorFunctionId.Operator));
5206     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5207       = Name.OperatorFunctionId.SymbolLocations[0];
5208     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5209       = Name.EndLocation.getRawEncoding();
5210     return NameInfo;
5211
5212   case UnqualifiedIdKind::IK_LiteralOperatorId:
5213     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5214                                                            Name.Identifier));
5215     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5216     return NameInfo;
5217
5218   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5219     TypeSourceInfo *TInfo;
5220     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5221     if (Ty.isNull())
5222       return DeclarationNameInfo();
5223     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5224                                                Context.getCanonicalType(Ty)));
5225     NameInfo.setNamedTypeInfo(TInfo);
5226     return NameInfo;
5227   }
5228
5229   case UnqualifiedIdKind::IK_ConstructorName: {
5230     TypeSourceInfo *TInfo;
5231     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5232     if (Ty.isNull())
5233       return DeclarationNameInfo();
5234     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5235                                               Context.getCanonicalType(Ty)));
5236     NameInfo.setNamedTypeInfo(TInfo);
5237     return NameInfo;
5238   }
5239
5240   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5241     // In well-formed code, we can only have a constructor
5242     // template-id that refers to the current context, so go there
5243     // to find the actual type being constructed.
5244     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5245     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5246       return DeclarationNameInfo();
5247
5248     // Determine the type of the class being constructed.
5249     QualType CurClassType = Context.getTypeDeclType(CurClass);
5250
5251     // FIXME: Check two things: that the template-id names the same type as
5252     // CurClassType, and that the template-id does not occur when the name
5253     // was qualified.
5254
5255     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5256                                     Context.getCanonicalType(CurClassType)));
5257     // FIXME: should we retrieve TypeSourceInfo?
5258     NameInfo.setNamedTypeInfo(nullptr);
5259     return NameInfo;
5260   }
5261
5262   case UnqualifiedIdKind::IK_DestructorName: {
5263     TypeSourceInfo *TInfo;
5264     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5265     if (Ty.isNull())
5266       return DeclarationNameInfo();
5267     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5268                                               Context.getCanonicalType(Ty)));
5269     NameInfo.setNamedTypeInfo(TInfo);
5270     return NameInfo;
5271   }
5272
5273   case UnqualifiedIdKind::IK_TemplateId: {
5274     TemplateName TName = Name.TemplateId->Template.get();
5275     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5276     return Context.getNameForTemplate(TName, TNameLoc);
5277   }
5278
5279   } // switch (Name.getKind())
5280
5281   llvm_unreachable("Unknown name kind");
5282 }
5283
5284 static QualType getCoreType(QualType Ty) {
5285   do {
5286     if (Ty->isPointerType() || Ty->isReferenceType())
5287       Ty = Ty->getPointeeType();
5288     else if (Ty->isArrayType())
5289       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5290     else
5291       return Ty.withoutLocalFastQualifiers();
5292   } while (true);
5293 }
5294
5295 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5296 /// and Definition have "nearly" matching parameters. This heuristic is
5297 /// used to improve diagnostics in the case where an out-of-line function
5298 /// definition doesn't match any declaration within the class or namespace.
5299 /// Also sets Params to the list of indices to the parameters that differ
5300 /// between the declaration and the definition. If hasSimilarParameters
5301 /// returns true and Params is empty, then all of the parameters match.
5302 static bool hasSimilarParameters(ASTContext &Context,
5303                                      FunctionDecl *Declaration,
5304                                      FunctionDecl *Definition,
5305                                      SmallVectorImpl<unsigned> &Params) {
5306   Params.clear();
5307   if (Declaration->param_size() != Definition->param_size())
5308     return false;
5309   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5310     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5311     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5312
5313     // The parameter types are identical
5314     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5315       continue;
5316
5317     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5318     QualType DefParamBaseTy = getCoreType(DefParamTy);
5319     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5320     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5321
5322     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5323         (DeclTyName && DeclTyName == DefTyName))
5324       Params.push_back(Idx);
5325     else  // The two parameters aren't even close
5326       return false;
5327   }
5328
5329   return true;
5330 }
5331
5332 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5333 /// declarator needs to be rebuilt in the current instantiation.
5334 /// Any bits of declarator which appear before the name are valid for
5335 /// consideration here.  That's specifically the type in the decl spec
5336 /// and the base type in any member-pointer chunks.
5337 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5338                                                     DeclarationName Name) {
5339   // The types we specifically need to rebuild are:
5340   //   - typenames, typeofs, and decltypes
5341   //   - types which will become injected class names
5342   // Of course, we also need to rebuild any type referencing such a
5343   // type.  It's safest to just say "dependent", but we call out a
5344   // few cases here.
5345
5346   DeclSpec &DS = D.getMutableDeclSpec();
5347   switch (DS.getTypeSpecType()) {
5348   case DeclSpec::TST_typename:
5349   case DeclSpec::TST_typeofType:
5350   case DeclSpec::TST_underlyingType:
5351   case DeclSpec::TST_atomic: {
5352     // Grab the type from the parser.
5353     TypeSourceInfo *TSI = nullptr;
5354     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5355     if (T.isNull() || !T->isDependentType()) break;
5356
5357     // Make sure there's a type source info.  This isn't really much
5358     // of a waste; most dependent types should have type source info
5359     // attached already.
5360     if (!TSI)
5361       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5362
5363     // Rebuild the type in the current instantiation.
5364     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5365     if (!TSI) return true;
5366
5367     // Store the new type back in the decl spec.
5368     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5369     DS.UpdateTypeRep(LocType);
5370     break;
5371   }
5372
5373   case DeclSpec::TST_decltype:
5374   case DeclSpec::TST_typeofExpr: {
5375     Expr *E = DS.getRepAsExpr();
5376     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5377     if (Result.isInvalid()) return true;
5378     DS.UpdateExprRep(Result.get());
5379     break;
5380   }
5381
5382   default:
5383     // Nothing to do for these decl specs.
5384     break;
5385   }
5386
5387   // It doesn't matter what order we do this in.
5388   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5389     DeclaratorChunk &Chunk = D.getTypeObject(I);
5390
5391     // The only type information in the declarator which can come
5392     // before the declaration name is the base type of a member
5393     // pointer.
5394     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5395       continue;
5396
5397     // Rebuild the scope specifier in-place.
5398     CXXScopeSpec &SS = Chunk.Mem.Scope();
5399     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5400       return true;
5401   }
5402
5403   return false;
5404 }
5405
5406 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5407   D.setFunctionDefinitionKind(FDK_Declaration);
5408   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5409
5410   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5411       Dcl && Dcl->getDeclContext()->isFileContext())
5412     Dcl->setTopLevelDeclInObjCContainer();
5413
5414   if (getLangOpts().OpenCL)
5415     setCurrentOpenCLExtensionForDecl(Dcl);
5416
5417   return Dcl;
5418 }
5419
5420 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5421 ///   If T is the name of a class, then each of the following shall have a
5422 ///   name different from T:
5423 ///     - every static data member of class T;
5424 ///     - every member function of class T
5425 ///     - every member of class T that is itself a type;
5426 /// \returns true if the declaration name violates these rules.
5427 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5428                                    DeclarationNameInfo NameInfo) {
5429   DeclarationName Name = NameInfo.getName();
5430
5431   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5432   while (Record && Record->isAnonymousStructOrUnion())
5433     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5434   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5435     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5436     return true;
5437   }
5438
5439   return false;
5440 }
5441
5442 /// Diagnose a declaration whose declarator-id has the given
5443 /// nested-name-specifier.
5444 ///
5445 /// \param SS The nested-name-specifier of the declarator-id.
5446 ///
5447 /// \param DC The declaration context to which the nested-name-specifier
5448 /// resolves.
5449 ///
5450 /// \param Name The name of the entity being declared.
5451 ///
5452 /// \param Loc The location of the name of the entity being declared.
5453 ///
5454 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5455 /// we're declaring an explicit / partial specialization / instantiation.
5456 ///
5457 /// \returns true if we cannot safely recover from this error, false otherwise.
5458 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5459                                         DeclarationName Name,
5460                                         SourceLocation Loc, bool IsTemplateId) {
5461   DeclContext *Cur = CurContext;
5462   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5463     Cur = Cur->getParent();
5464
5465   // If the user provided a superfluous scope specifier that refers back to the
5466   // class in which the entity is already declared, diagnose and ignore it.
5467   //
5468   // class X {
5469   //   void X::f();
5470   // };
5471   //
5472   // Note, it was once ill-formed to give redundant qualification in all
5473   // contexts, but that rule was removed by DR482.
5474   if (Cur->Equals(DC)) {
5475     if (Cur->isRecord()) {
5476       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5477                                       : diag::err_member_extra_qualification)
5478         << Name << FixItHint::CreateRemoval(SS.getRange());
5479       SS.clear();
5480     } else {
5481       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5482     }
5483     return false;
5484   }
5485
5486   // Check whether the qualifying scope encloses the scope of the original
5487   // declaration. For a template-id, we perform the checks in
5488   // CheckTemplateSpecializationScope.
5489   if (!Cur->Encloses(DC) && !IsTemplateId) {
5490     if (Cur->isRecord())
5491       Diag(Loc, diag::err_member_qualification)
5492         << Name << SS.getRange();
5493     else if (isa<TranslationUnitDecl>(DC))
5494       Diag(Loc, diag::err_invalid_declarator_global_scope)
5495         << Name << SS.getRange();
5496     else if (isa<FunctionDecl>(Cur))
5497       Diag(Loc, diag::err_invalid_declarator_in_function)
5498         << Name << SS.getRange();
5499     else if (isa<BlockDecl>(Cur))
5500       Diag(Loc, diag::err_invalid_declarator_in_block)
5501         << Name << SS.getRange();
5502     else
5503       Diag(Loc, diag::err_invalid_declarator_scope)
5504       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5505
5506     return true;
5507   }
5508
5509   if (Cur->isRecord()) {
5510     // Cannot qualify members within a class.
5511     Diag(Loc, diag::err_member_qualification)
5512       << Name << SS.getRange();
5513     SS.clear();
5514
5515     // C++ constructors and destructors with incorrect scopes can break
5516     // our AST invariants by having the wrong underlying types. If
5517     // that's the case, then drop this declaration entirely.
5518     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5519          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5520         !Context.hasSameType(Name.getCXXNameType(),
5521                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5522       return true;
5523
5524     return false;
5525   }
5526
5527   // C++11 [dcl.meaning]p1:
5528   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5529   //   not begin with a decltype-specifer"
5530   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5531   while (SpecLoc.getPrefix())
5532     SpecLoc = SpecLoc.getPrefix();
5533   if (dyn_cast_or_null<DecltypeType>(
5534         SpecLoc.getNestedNameSpecifier()->getAsType()))
5535     Diag(Loc, diag::err_decltype_in_declarator)
5536       << SpecLoc.getTypeLoc().getSourceRange();
5537
5538   return false;
5539 }
5540
5541 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5542                                   MultiTemplateParamsArg TemplateParamLists) {
5543   // TODO: consider using NameInfo for diagnostic.
5544   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5545   DeclarationName Name = NameInfo.getName();
5546
5547   // All of these full declarators require an identifier.  If it doesn't have
5548   // one, the ParsedFreeStandingDeclSpec action should be used.
5549   if (D.isDecompositionDeclarator()) {
5550     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5551   } else if (!Name) {
5552     if (!D.isInvalidType())  // Reject this if we think it is valid.
5553       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5554           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5555     return nullptr;
5556   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5557     return nullptr;
5558
5559   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5560   // we find one that is.
5561   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5562          (S->getFlags() & Scope::TemplateParamScope) != 0)
5563     S = S->getParent();
5564
5565   DeclContext *DC = CurContext;
5566   if (D.getCXXScopeSpec().isInvalid())
5567     D.setInvalidType();
5568   else if (D.getCXXScopeSpec().isSet()) {
5569     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5570                                         UPPC_DeclarationQualifier))
5571       return nullptr;
5572
5573     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5574     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5575     if (!DC || isa<EnumDecl>(DC)) {
5576       // If we could not compute the declaration context, it's because the
5577       // declaration context is dependent but does not refer to a class,
5578       // class template, or class template partial specialization. Complain
5579       // and return early, to avoid the coming semantic disaster.
5580       Diag(D.getIdentifierLoc(),
5581            diag::err_template_qualified_declarator_no_match)
5582         << D.getCXXScopeSpec().getScopeRep()
5583         << D.getCXXScopeSpec().getRange();
5584       return nullptr;
5585     }
5586     bool IsDependentContext = DC->isDependentContext();
5587
5588     if (!IsDependentContext &&
5589         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5590       return nullptr;
5591
5592     // If a class is incomplete, do not parse entities inside it.
5593     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5594       Diag(D.getIdentifierLoc(),
5595            diag::err_member_def_undefined_record)
5596         << Name << DC << D.getCXXScopeSpec().getRange();
5597       return nullptr;
5598     }
5599     if (!D.getDeclSpec().isFriendSpecified()) {
5600       if (diagnoseQualifiedDeclaration(
5601               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5602               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5603         if (DC->isRecord())
5604           return nullptr;
5605
5606         D.setInvalidType();
5607       }
5608     }
5609
5610     // Check whether we need to rebuild the type of the given
5611     // declaration in the current instantiation.
5612     if (EnteringContext && IsDependentContext &&
5613         TemplateParamLists.size() != 0) {
5614       ContextRAII SavedContext(*this, DC);
5615       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5616         D.setInvalidType();
5617     }
5618   }
5619
5620   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5621   QualType R = TInfo->getType();
5622
5623   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5624                                       UPPC_DeclarationType))
5625     D.setInvalidType();
5626
5627   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5628                         forRedeclarationInCurContext());
5629
5630   // See if this is a redefinition of a variable in the same scope.
5631   if (!D.getCXXScopeSpec().isSet()) {
5632     bool IsLinkageLookup = false;
5633     bool CreateBuiltins = false;
5634
5635     // If the declaration we're planning to build will be a function
5636     // or object with linkage, then look for another declaration with
5637     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5638     //
5639     // If the declaration we're planning to build will be declared with
5640     // external linkage in the translation unit, create any builtin with
5641     // the same name.
5642     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5643       /* Do nothing*/;
5644     else if (CurContext->isFunctionOrMethod() &&
5645              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5646               R->isFunctionType())) {
5647       IsLinkageLookup = true;
5648       CreateBuiltins =
5649           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5650     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5651                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5652       CreateBuiltins = true;
5653
5654     if (IsLinkageLookup) {
5655       Previous.clear(LookupRedeclarationWithLinkage);
5656       Previous.setRedeclarationKind(ForExternalRedeclaration);
5657     }
5658
5659     LookupName(Previous, S, CreateBuiltins);
5660   } else { // Something like "int foo::x;"
5661     LookupQualifiedName(Previous, DC);
5662
5663     // C++ [dcl.meaning]p1:
5664     //   When the declarator-id is qualified, the declaration shall refer to a
5665     //  previously declared member of the class or namespace to which the
5666     //  qualifier refers (or, in the case of a namespace, of an element of the
5667     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5668     //  thereof; [...]
5669     //
5670     // Note that we already checked the context above, and that we do not have
5671     // enough information to make sure that Previous contains the declaration
5672     // we want to match. For example, given:
5673     //
5674     //   class X {
5675     //     void f();
5676     //     void f(float);
5677     //   };
5678     //
5679     //   void X::f(int) { } // ill-formed
5680     //
5681     // In this case, Previous will point to the overload set
5682     // containing the two f's declared in X, but neither of them
5683     // matches.
5684
5685     // C++ [dcl.meaning]p1:
5686     //   [...] the member shall not merely have been introduced by a
5687     //   using-declaration in the scope of the class or namespace nominated by
5688     //   the nested-name-specifier of the declarator-id.
5689     RemoveUsingDecls(Previous);
5690   }
5691
5692   if (Previous.isSingleResult() &&
5693       Previous.getFoundDecl()->isTemplateParameter()) {
5694     // Maybe we will complain about the shadowed template parameter.
5695     if (!D.isInvalidType())
5696       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5697                                       Previous.getFoundDecl());
5698
5699     // Just pretend that we didn't see the previous declaration.
5700     Previous.clear();
5701   }
5702
5703   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5704     // Forget that the previous declaration is the injected-class-name.
5705     Previous.clear();
5706
5707   // In C++, the previous declaration we find might be a tag type
5708   // (class or enum). In this case, the new declaration will hide the
5709   // tag type. Note that this applies to functions, function templates, and
5710   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5711   if (Previous.isSingleTagDecl() &&
5712       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5713       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5714     Previous.clear();
5715
5716   // Check that there are no default arguments other than in the parameters
5717   // of a function declaration (C++ only).
5718   if (getLangOpts().CPlusPlus)
5719     CheckExtraCXXDefaultArguments(D);
5720
5721   NamedDecl *New;
5722
5723   bool AddToScope = true;
5724   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5725     if (TemplateParamLists.size()) {
5726       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5727       return nullptr;
5728     }
5729
5730     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5731   } else if (R->isFunctionType()) {
5732     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5733                                   TemplateParamLists,
5734                                   AddToScope);
5735   } else {
5736     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5737                                   AddToScope);
5738   }
5739
5740   if (!New)
5741     return nullptr;
5742
5743   // If this has an identifier and is not a function template specialization,
5744   // add it to the scope stack.
5745   if (New->getDeclName() && AddToScope)
5746     PushOnScopeChains(New, S);
5747
5748   if (isInOpenMPDeclareTargetContext())
5749     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5750
5751   return New;
5752 }
5753
5754 /// Helper method to turn variable array types into constant array
5755 /// types in certain situations which would otherwise be errors (for
5756 /// GCC compatibility).
5757 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5758                                                     ASTContext &Context,
5759                                                     bool &SizeIsNegative,
5760                                                     llvm::APSInt &Oversized) {
5761   // This method tries to turn a variable array into a constant
5762   // array even when the size isn't an ICE.  This is necessary
5763   // for compatibility with code that depends on gcc's buggy
5764   // constant expression folding, like struct {char x[(int)(char*)2];}
5765   SizeIsNegative = false;
5766   Oversized = 0;
5767
5768   if (T->isDependentType())
5769     return QualType();
5770
5771   QualifierCollector Qs;
5772   const Type *Ty = Qs.strip(T);
5773
5774   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5775     QualType Pointee = PTy->getPointeeType();
5776     QualType FixedType =
5777         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5778                                             Oversized);
5779     if (FixedType.isNull()) return FixedType;
5780     FixedType = Context.getPointerType(FixedType);
5781     return Qs.apply(Context, FixedType);
5782   }
5783   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5784     QualType Inner = PTy->getInnerType();
5785     QualType FixedType =
5786         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5787                                             Oversized);
5788     if (FixedType.isNull()) return FixedType;
5789     FixedType = Context.getParenType(FixedType);
5790     return Qs.apply(Context, FixedType);
5791   }
5792
5793   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5794   if (!VLATy)
5795     return QualType();
5796   // FIXME: We should probably handle this case
5797   if (VLATy->getElementType()->isVariablyModifiedType())
5798     return QualType();
5799
5800   Expr::EvalResult Result;
5801   if (!VLATy->getSizeExpr() ||
5802       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5803     return QualType();
5804
5805   llvm::APSInt Res = Result.Val.getInt();
5806
5807   // Check whether the array size is negative.
5808   if (Res.isSigned() && Res.isNegative()) {
5809     SizeIsNegative = true;
5810     return QualType();
5811   }
5812
5813   // Check whether the array is too large to be addressed.
5814   unsigned ActiveSizeBits
5815     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5816                                               Res);
5817   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5818     Oversized = Res;
5819     return QualType();
5820   }
5821
5822   return Context.getConstantArrayType(
5823       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5824 }
5825
5826 static void
5827 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5828   SrcTL = SrcTL.getUnqualifiedLoc();
5829   DstTL = DstTL.getUnqualifiedLoc();
5830   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5831     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5832     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5833                                       DstPTL.getPointeeLoc());
5834     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5835     return;
5836   }
5837   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5838     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5839     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5840                                       DstPTL.getInnerLoc());
5841     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5842     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5843     return;
5844   }
5845   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5846   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5847   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5848   TypeLoc DstElemTL = DstATL.getElementLoc();
5849   DstElemTL.initializeFullCopy(SrcElemTL);
5850   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5851   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5852   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5853 }
5854
5855 /// Helper method to turn variable array types into constant array
5856 /// types in certain situations which would otherwise be errors (for
5857 /// GCC compatibility).
5858 static TypeSourceInfo*
5859 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5860                                               ASTContext &Context,
5861                                               bool &SizeIsNegative,
5862                                               llvm::APSInt &Oversized) {
5863   QualType FixedTy
5864     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5865                                           SizeIsNegative, Oversized);
5866   if (FixedTy.isNull())
5867     return nullptr;
5868   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5869   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5870                                     FixedTInfo->getTypeLoc());
5871   return FixedTInfo;
5872 }
5873
5874 /// Register the given locally-scoped extern "C" declaration so
5875 /// that it can be found later for redeclarations. We include any extern "C"
5876 /// declaration that is not visible in the translation unit here, not just
5877 /// function-scope declarations.
5878 void
5879 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5880   if (!getLangOpts().CPlusPlus &&
5881       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5882     // Don't need to track declarations in the TU in C.
5883     return;
5884
5885   // Note that we have a locally-scoped external with this name.
5886   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5887 }
5888
5889 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5890   // FIXME: We can have multiple results via __attribute__((overloadable)).
5891   auto Result = Context.getExternCContextDecl()->lookup(Name);
5892   return Result.empty() ? nullptr : *Result.begin();
5893 }
5894
5895 /// Diagnose function specifiers on a declaration of an identifier that
5896 /// does not identify a function.
5897 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5898   // FIXME: We should probably indicate the identifier in question to avoid
5899   // confusion for constructs like "virtual int a(), b;"
5900   if (DS.isVirtualSpecified())
5901     Diag(DS.getVirtualSpecLoc(),
5902          diag::err_virtual_non_function);
5903
5904   if (DS.hasExplicitSpecifier())
5905     Diag(DS.getExplicitSpecLoc(),
5906          diag::err_explicit_non_function);
5907
5908   if (DS.isNoreturnSpecified())
5909     Diag(DS.getNoreturnSpecLoc(),
5910          diag::err_noreturn_non_function);
5911 }
5912
5913 NamedDecl*
5914 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5915                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5916   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5917   if (D.getCXXScopeSpec().isSet()) {
5918     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5919       << D.getCXXScopeSpec().getRange();
5920     D.setInvalidType();
5921     // Pretend we didn't see the scope specifier.
5922     DC = CurContext;
5923     Previous.clear();
5924   }
5925
5926   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5927
5928   if (D.getDeclSpec().isInlineSpecified())
5929     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5930         << getLangOpts().CPlusPlus17;
5931   if (D.getDeclSpec().hasConstexprSpecifier())
5932     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5933         << 1 << D.getDeclSpec().getConstexprSpecifier();
5934
5935   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5936     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5937       Diag(D.getName().StartLocation,
5938            diag::err_deduction_guide_invalid_specifier)
5939           << "typedef";
5940     else
5941       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5942           << D.getName().getSourceRange();
5943     return nullptr;
5944   }
5945
5946   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5947   if (!NewTD) return nullptr;
5948
5949   // Handle attributes prior to checking for duplicates in MergeVarDecl
5950   ProcessDeclAttributes(S, NewTD, D);
5951
5952   CheckTypedefForVariablyModifiedType(S, NewTD);
5953
5954   bool Redeclaration = D.isRedeclaration();
5955   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5956   D.setRedeclaration(Redeclaration);
5957   return ND;
5958 }
5959
5960 void
5961 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5962   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5963   // then it shall have block scope.
5964   // Note that variably modified types must be fixed before merging the decl so
5965   // that redeclarations will match.
5966   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5967   QualType T = TInfo->getType();
5968   if (T->isVariablyModifiedType()) {
5969     setFunctionHasBranchProtectedScope();
5970
5971     if (S->getFnParent() == nullptr) {
5972       bool SizeIsNegative;
5973       llvm::APSInt Oversized;
5974       TypeSourceInfo *FixedTInfo =
5975         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5976                                                       SizeIsNegative,
5977                                                       Oversized);
5978       if (FixedTInfo) {
5979         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5980         NewTD->setTypeSourceInfo(FixedTInfo);
5981       } else {
5982         if (SizeIsNegative)
5983           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5984         else if (T->isVariableArrayType())
5985           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5986         else if (Oversized.getBoolValue())
5987           Diag(NewTD->getLocation(), diag::err_array_too_large)
5988             << Oversized.toString(10);
5989         else
5990           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5991         NewTD->setInvalidDecl();
5992       }
5993     }
5994   }
5995 }
5996
5997 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5998 /// declares a typedef-name, either using the 'typedef' type specifier or via
5999 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6000 NamedDecl*
6001 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6002                            LookupResult &Previous, bool &Redeclaration) {
6003
6004   // Find the shadowed declaration before filtering for scope.
6005   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6006
6007   // Merge the decl with the existing one if appropriate. If the decl is
6008   // in an outer scope, it isn't the same thing.
6009   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6010                        /*AllowInlineNamespace*/false);
6011   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6012   if (!Previous.empty()) {
6013     Redeclaration = true;
6014     MergeTypedefNameDecl(S, NewTD, Previous);
6015   } else {
6016     inferGslPointerAttribute(NewTD);
6017   }
6018
6019   if (ShadowedDecl && !Redeclaration)
6020     CheckShadow(NewTD, ShadowedDecl, Previous);
6021
6022   // If this is the C FILE type, notify the AST context.
6023   if (IdentifierInfo *II = NewTD->getIdentifier())
6024     if (!NewTD->isInvalidDecl() &&
6025         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6026       if (II->isStr("FILE"))
6027         Context.setFILEDecl(NewTD);
6028       else if (II->isStr("jmp_buf"))
6029         Context.setjmp_bufDecl(NewTD);
6030       else if (II->isStr("sigjmp_buf"))
6031         Context.setsigjmp_bufDecl(NewTD);
6032       else if (II->isStr("ucontext_t"))
6033         Context.setucontext_tDecl(NewTD);
6034     }
6035
6036   return NewTD;
6037 }
6038
6039 /// Determines whether the given declaration is an out-of-scope
6040 /// previous declaration.
6041 ///
6042 /// This routine should be invoked when name lookup has found a
6043 /// previous declaration (PrevDecl) that is not in the scope where a
6044 /// new declaration by the same name is being introduced. If the new
6045 /// declaration occurs in a local scope, previous declarations with
6046 /// linkage may still be considered previous declarations (C99
6047 /// 6.2.2p4-5, C++ [basic.link]p6).
6048 ///
6049 /// \param PrevDecl the previous declaration found by name
6050 /// lookup
6051 ///
6052 /// \param DC the context in which the new declaration is being
6053 /// declared.
6054 ///
6055 /// \returns true if PrevDecl is an out-of-scope previous declaration
6056 /// for a new delcaration with the same name.
6057 static bool
6058 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6059                                 ASTContext &Context) {
6060   if (!PrevDecl)
6061     return false;
6062
6063   if (!PrevDecl->hasLinkage())
6064     return false;
6065
6066   if (Context.getLangOpts().CPlusPlus) {
6067     // C++ [basic.link]p6:
6068     //   If there is a visible declaration of an entity with linkage
6069     //   having the same name and type, ignoring entities declared
6070     //   outside the innermost enclosing namespace scope, the block
6071     //   scope declaration declares that same entity and receives the
6072     //   linkage of the previous declaration.
6073     DeclContext *OuterContext = DC->getRedeclContext();
6074     if (!OuterContext->isFunctionOrMethod())
6075       // This rule only applies to block-scope declarations.
6076       return false;
6077
6078     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6079     if (PrevOuterContext->isRecord())
6080       // We found a member function: ignore it.
6081       return false;
6082
6083     // Find the innermost enclosing namespace for the new and
6084     // previous declarations.
6085     OuterContext = OuterContext->getEnclosingNamespaceContext();
6086     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6087
6088     // The previous declaration is in a different namespace, so it
6089     // isn't the same function.
6090     if (!OuterContext->Equals(PrevOuterContext))
6091       return false;
6092   }
6093
6094   return true;
6095 }
6096
6097 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6098   CXXScopeSpec &SS = D.getCXXScopeSpec();
6099   if (!SS.isSet()) return;
6100   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6101 }
6102
6103 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6104   QualType type = decl->getType();
6105   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6106   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6107     // Various kinds of declaration aren't allowed to be __autoreleasing.
6108     unsigned kind = -1U;
6109     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6110       if (var->hasAttr<BlocksAttr>())
6111         kind = 0; // __block
6112       else if (!var->hasLocalStorage())
6113         kind = 1; // global
6114     } else if (isa<ObjCIvarDecl>(decl)) {
6115       kind = 3; // ivar
6116     } else if (isa<FieldDecl>(decl)) {
6117       kind = 2; // field
6118     }
6119
6120     if (kind != -1U) {
6121       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6122         << kind;
6123     }
6124   } else if (lifetime == Qualifiers::OCL_None) {
6125     // Try to infer lifetime.
6126     if (!type->isObjCLifetimeType())
6127       return false;
6128
6129     lifetime = type->getObjCARCImplicitLifetime();
6130     type = Context.getLifetimeQualifiedType(type, lifetime);
6131     decl->setType(type);
6132   }
6133
6134   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6135     // Thread-local variables cannot have lifetime.
6136     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6137         var->getTLSKind()) {
6138       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6139         << var->getType();
6140       return true;
6141     }
6142   }
6143
6144   return false;
6145 }
6146
6147 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6148   if (Decl->getType().hasAddressSpace())
6149     return;
6150   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6151     QualType Type = Var->getType();
6152     if (Type->isSamplerT() || Type->isVoidType())
6153       return;
6154     LangAS ImplAS = LangAS::opencl_private;
6155     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6156         Var->hasGlobalStorage())
6157       ImplAS = LangAS::opencl_global;
6158     // If the original type from a decayed type is an array type and that array
6159     // type has no address space yet, deduce it now.
6160     if (auto DT = dyn_cast<DecayedType>(Type)) {
6161       auto OrigTy = DT->getOriginalType();
6162       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6163         // Add the address space to the original array type and then propagate
6164         // that to the element type through `getAsArrayType`.
6165         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6166         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6167         // Re-generate the decayed type.
6168         Type = Context.getDecayedType(OrigTy);
6169       }
6170     }
6171     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6172     // Apply any qualifiers (including address space) from the array type to
6173     // the element type. This implements C99 6.7.3p8: "If the specification of
6174     // an array type includes any type qualifiers, the element type is so
6175     // qualified, not the array type."
6176     if (Type->isArrayType())
6177       Type = QualType(Context.getAsArrayType(Type), 0);
6178     Decl->setType(Type);
6179   }
6180 }
6181
6182 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6183   // Ensure that an auto decl is deduced otherwise the checks below might cache
6184   // the wrong linkage.
6185   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6186
6187   // 'weak' only applies to declarations with external linkage.
6188   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6189     if (!ND.isExternallyVisible()) {
6190       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6191       ND.dropAttr<WeakAttr>();
6192     }
6193   }
6194   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6195     if (ND.isExternallyVisible()) {
6196       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6197       ND.dropAttr<WeakRefAttr>();
6198       ND.dropAttr<AliasAttr>();
6199     }
6200   }
6201
6202   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6203     if (VD->hasInit()) {
6204       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6205         assert(VD->isThisDeclarationADefinition() &&
6206                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6207         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6208         VD->dropAttr<AliasAttr>();
6209       }
6210     }
6211   }
6212
6213   // 'selectany' only applies to externally visible variable declarations.
6214   // It does not apply to functions.
6215   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6216     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6217       S.Diag(Attr->getLocation(),
6218              diag::err_attribute_selectany_non_extern_data);
6219       ND.dropAttr<SelectAnyAttr>();
6220     }
6221   }
6222
6223   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6224     auto *VD = dyn_cast<VarDecl>(&ND);
6225     bool IsAnonymousNS = false;
6226     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6227     if (VD) {
6228       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6229       while (NS && !IsAnonymousNS) {
6230         IsAnonymousNS = NS->isAnonymousNamespace();
6231         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6232       }
6233     }
6234     // dll attributes require external linkage. Static locals may have external
6235     // linkage but still cannot be explicitly imported or exported.
6236     // In Microsoft mode, a variable defined in anonymous namespace must have
6237     // external linkage in order to be exported.
6238     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6239     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6240         (!AnonNSInMicrosoftMode &&
6241          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6242       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6243         << &ND << Attr;
6244       ND.setInvalidDecl();
6245     }
6246   }
6247
6248   // Virtual functions cannot be marked as 'notail'.
6249   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6250     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6251       if (MD->isVirtual()) {
6252         S.Diag(ND.getLocation(),
6253                diag::err_invalid_attribute_on_virtual_function)
6254             << Attr;
6255         ND.dropAttr<NotTailCalledAttr>();
6256       }
6257
6258   // Check the attributes on the function type, if any.
6259   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6260     // Don't declare this variable in the second operand of the for-statement;
6261     // GCC miscompiles that by ending its lifetime before evaluating the
6262     // third operand. See gcc.gnu.org/PR86769.
6263     AttributedTypeLoc ATL;
6264     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6265          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6266          TL = ATL.getModifiedLoc()) {
6267       // The [[lifetimebound]] attribute can be applied to the implicit object
6268       // parameter of a non-static member function (other than a ctor or dtor)
6269       // by applying it to the function type.
6270       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6271         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6272         if (!MD || MD->isStatic()) {
6273           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6274               << !MD << A->getRange();
6275         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6276           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6277               << isa<CXXDestructorDecl>(MD) << A->getRange();
6278         }
6279       }
6280     }
6281   }
6282 }
6283
6284 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6285                                            NamedDecl *NewDecl,
6286                                            bool IsSpecialization,
6287                                            bool IsDefinition) {
6288   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6289     return;
6290
6291   bool IsTemplate = false;
6292   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6293     OldDecl = OldTD->getTemplatedDecl();
6294     IsTemplate = true;
6295     if (!IsSpecialization)
6296       IsDefinition = false;
6297   }
6298   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6299     NewDecl = NewTD->getTemplatedDecl();
6300     IsTemplate = true;
6301   }
6302
6303   if (!OldDecl || !NewDecl)
6304     return;
6305
6306   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6307   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6308   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6309   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6310
6311   // dllimport and dllexport are inheritable attributes so we have to exclude
6312   // inherited attribute instances.
6313   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6314                     (NewExportAttr && !NewExportAttr->isInherited());
6315
6316   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6317   // the only exception being explicit specializations.
6318   // Implicitly generated declarations are also excluded for now because there
6319   // is no other way to switch these to use dllimport or dllexport.
6320   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6321
6322   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6323     // Allow with a warning for free functions and global variables.
6324     bool JustWarn = false;
6325     if (!OldDecl->isCXXClassMember()) {
6326       auto *VD = dyn_cast<VarDecl>(OldDecl);
6327       if (VD && !VD->getDescribedVarTemplate())
6328         JustWarn = true;
6329       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6330       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6331         JustWarn = true;
6332     }
6333
6334     // We cannot change a declaration that's been used because IR has already
6335     // been emitted. Dllimported functions will still work though (modulo
6336     // address equality) as they can use the thunk.
6337     if (OldDecl->isUsed())
6338       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6339         JustWarn = false;
6340
6341     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6342                                : diag::err_attribute_dll_redeclaration;
6343     S.Diag(NewDecl->getLocation(), DiagID)
6344         << NewDecl
6345         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6346     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6347     if (!JustWarn) {
6348       NewDecl->setInvalidDecl();
6349       return;
6350     }
6351   }
6352
6353   // A redeclaration is not allowed to drop a dllimport attribute, the only
6354   // exceptions being inline function definitions (except for function
6355   // templates), local extern declarations, qualified friend declarations or
6356   // special MSVC extension: in the last case, the declaration is treated as if
6357   // it were marked dllexport.
6358   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6359   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6360   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6361     // Ignore static data because out-of-line definitions are diagnosed
6362     // separately.
6363     IsStaticDataMember = VD->isStaticDataMember();
6364     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6365                    VarDecl::DeclarationOnly;
6366   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6367     IsInline = FD->isInlined();
6368     IsQualifiedFriend = FD->getQualifier() &&
6369                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6370   }
6371
6372   if (OldImportAttr && !HasNewAttr &&
6373       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6374       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6375     if (IsMicrosoft && IsDefinition) {
6376       S.Diag(NewDecl->getLocation(),
6377              diag::warn_redeclaration_without_import_attribute)
6378           << NewDecl;
6379       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6380       NewDecl->dropAttr<DLLImportAttr>();
6381       NewDecl->addAttr(
6382           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6383     } else {
6384       S.Diag(NewDecl->getLocation(),
6385              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6386           << NewDecl << OldImportAttr;
6387       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6388       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6389       OldDecl->dropAttr<DLLImportAttr>();
6390       NewDecl->dropAttr<DLLImportAttr>();
6391     }
6392   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6393     // In MinGW, seeing a function declared inline drops the dllimport
6394     // attribute.
6395     OldDecl->dropAttr<DLLImportAttr>();
6396     NewDecl->dropAttr<DLLImportAttr>();
6397     S.Diag(NewDecl->getLocation(),
6398            diag::warn_dllimport_dropped_from_inline_function)
6399         << NewDecl << OldImportAttr;
6400   }
6401
6402   // A specialization of a class template member function is processed here
6403   // since it's a redeclaration. If the parent class is dllexport, the
6404   // specialization inherits that attribute. This doesn't happen automatically
6405   // since the parent class isn't instantiated until later.
6406   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6407     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6408         !NewImportAttr && !NewExportAttr) {
6409       if (const DLLExportAttr *ParentExportAttr =
6410               MD->getParent()->getAttr<DLLExportAttr>()) {
6411         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6412         NewAttr->setInherited(true);
6413         NewDecl->addAttr(NewAttr);
6414       }
6415     }
6416   }
6417 }
6418
6419 /// Given that we are within the definition of the given function,
6420 /// will that definition behave like C99's 'inline', where the
6421 /// definition is discarded except for optimization purposes?
6422 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6423   // Try to avoid calling GetGVALinkageForFunction.
6424
6425   // All cases of this require the 'inline' keyword.
6426   if (!FD->isInlined()) return false;
6427
6428   // This is only possible in C++ with the gnu_inline attribute.
6429   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6430     return false;
6431
6432   // Okay, go ahead and call the relatively-more-expensive function.
6433   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6434 }
6435
6436 /// Determine whether a variable is extern "C" prior to attaching
6437 /// an initializer. We can't just call isExternC() here, because that
6438 /// will also compute and cache whether the declaration is externally
6439 /// visible, which might change when we attach the initializer.
6440 ///
6441 /// This can only be used if the declaration is known to not be a
6442 /// redeclaration of an internal linkage declaration.
6443 ///
6444 /// For instance:
6445 ///
6446 ///   auto x = []{};
6447 ///
6448 /// Attaching the initializer here makes this declaration not externally
6449 /// visible, because its type has internal linkage.
6450 ///
6451 /// FIXME: This is a hack.
6452 template<typename T>
6453 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6454   if (S.getLangOpts().CPlusPlus) {
6455     // In C++, the overloadable attribute negates the effects of extern "C".
6456     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6457       return false;
6458
6459     // So do CUDA's host/device attributes.
6460     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6461                                  D->template hasAttr<CUDAHostAttr>()))
6462       return false;
6463   }
6464   return D->isExternC();
6465 }
6466
6467 static bool shouldConsiderLinkage(const VarDecl *VD) {
6468   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6469   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6470       isa<OMPDeclareMapperDecl>(DC))
6471     return VD->hasExternalStorage();
6472   if (DC->isFileContext())
6473     return true;
6474   if (DC->isRecord())
6475     return false;
6476   if (isa<RequiresExprBodyDecl>(DC))
6477     return false;
6478   llvm_unreachable("Unexpected context");
6479 }
6480
6481 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6482   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6483   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6484       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6485     return true;
6486   if (DC->isRecord())
6487     return false;
6488   llvm_unreachable("Unexpected context");
6489 }
6490
6491 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6492                           ParsedAttr::Kind Kind) {
6493   // Check decl attributes on the DeclSpec.
6494   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6495     return true;
6496
6497   // Walk the declarator structure, checking decl attributes that were in a type
6498   // position to the decl itself.
6499   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6500     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6501       return true;
6502   }
6503
6504   // Finally, check attributes on the decl itself.
6505   return PD.getAttributes().hasAttribute(Kind);
6506 }
6507
6508 /// Adjust the \c DeclContext for a function or variable that might be a
6509 /// function-local external declaration.
6510 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6511   if (!DC->isFunctionOrMethod())
6512     return false;
6513
6514   // If this is a local extern function or variable declared within a function
6515   // template, don't add it into the enclosing namespace scope until it is
6516   // instantiated; it might have a dependent type right now.
6517   if (DC->isDependentContext())
6518     return true;
6519
6520   // C++11 [basic.link]p7:
6521   //   When a block scope declaration of an entity with linkage is not found to
6522   //   refer to some other declaration, then that entity is a member of the
6523   //   innermost enclosing namespace.
6524   //
6525   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6526   // semantically-enclosing namespace, not a lexically-enclosing one.
6527   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6528     DC = DC->getParent();
6529   return true;
6530 }
6531
6532 /// Returns true if given declaration has external C language linkage.
6533 static bool isDeclExternC(const Decl *D) {
6534   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6535     return FD->isExternC();
6536   if (const auto *VD = dyn_cast<VarDecl>(D))
6537     return VD->isExternC();
6538
6539   llvm_unreachable("Unknown type of decl!");
6540 }
6541 /// Returns true if there hasn't been any invalid type diagnosed.
6542 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6543                                 DeclContext *DC, QualType R) {
6544   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6545   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6546   // argument.
6547   if (R->isImageType() || R->isPipeType()) {
6548     Se.Diag(D.getIdentifierLoc(),
6549             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6550         << R;
6551     D.setInvalidType();
6552     return false;
6553   }
6554
6555   // OpenCL v1.2 s6.9.r:
6556   // The event type cannot be used to declare a program scope variable.
6557   // OpenCL v2.0 s6.9.q:
6558   // The clk_event_t and reserve_id_t types cannot be declared in program
6559   // scope.
6560   if (NULL == S->getParent()) {
6561     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6562       Se.Diag(D.getIdentifierLoc(),
6563               diag::err_invalid_type_for_program_scope_var)
6564           << R;
6565       D.setInvalidType();
6566       return false;
6567     }
6568   }
6569
6570   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6571   QualType NR = R;
6572   while (NR->isPointerType()) {
6573     if (NR->isFunctionPointerType()) {
6574       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6575       D.setInvalidType();
6576       return false;
6577     }
6578     NR = NR->getPointeeType();
6579   }
6580
6581   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6582     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6583     // half array type (unless the cl_khr_fp16 extension is enabled).
6584     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6585       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6586       D.setInvalidType();
6587       return false;
6588     }
6589   }
6590
6591   // OpenCL v1.2 s6.9.r:
6592   // The event type cannot be used with the __local, __constant and __global
6593   // address space qualifiers.
6594   if (R->isEventT()) {
6595     if (R.getAddressSpace() != LangAS::opencl_private) {
6596       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6597       D.setInvalidType();
6598       return false;
6599     }
6600   }
6601
6602   // C++ for OpenCL does not allow the thread_local storage qualifier.
6603   // OpenCL C does not support thread_local either, and
6604   // also reject all other thread storage class specifiers.
6605   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6606   if (TSC != TSCS_unspecified) {
6607     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6608     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6609             diag::err_opencl_unknown_type_specifier)
6610         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6611         << DeclSpec::getSpecifierName(TSC) << 1;
6612     D.setInvalidType();
6613     return false;
6614   }
6615
6616   if (R->isSamplerT()) {
6617     // OpenCL v1.2 s6.9.b p4:
6618     // The sampler type cannot be used with the __local and __global address
6619     // space qualifiers.
6620     if (R.getAddressSpace() == LangAS::opencl_local ||
6621         R.getAddressSpace() == LangAS::opencl_global) {
6622       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6623       D.setInvalidType();
6624     }
6625
6626     // OpenCL v1.2 s6.12.14.1:
6627     // A global sampler must be declared with either the constant address
6628     // space qualifier or with the const qualifier.
6629     if (DC->isTranslationUnit() &&
6630         !(R.getAddressSpace() == LangAS::opencl_constant ||
6631           R.isConstQualified())) {
6632       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6633       D.setInvalidType();
6634     }
6635     if (D.isInvalidType())
6636       return false;
6637   }
6638   return true;
6639 }
6640
6641 NamedDecl *Sema::ActOnVariableDeclarator(
6642     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6643     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6644     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6645   QualType R = TInfo->getType();
6646   DeclarationName Name = GetNameForDeclarator(D).getName();
6647
6648   IdentifierInfo *II = Name.getAsIdentifierInfo();
6649
6650   if (D.isDecompositionDeclarator()) {
6651     // Take the name of the first declarator as our name for diagnostic
6652     // purposes.
6653     auto &Decomp = D.getDecompositionDeclarator();
6654     if (!Decomp.bindings().empty()) {
6655       II = Decomp.bindings()[0].Name;
6656       Name = II;
6657     }
6658   } else if (!II) {
6659     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6660     return nullptr;
6661   }
6662
6663
6664   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6665   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6666
6667   // dllimport globals without explicit storage class are treated as extern. We
6668   // have to change the storage class this early to get the right DeclContext.
6669   if (SC == SC_None && !DC->isRecord() &&
6670       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6671       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6672     SC = SC_Extern;
6673
6674   DeclContext *OriginalDC = DC;
6675   bool IsLocalExternDecl = SC == SC_Extern &&
6676                            adjustContextForLocalExternDecl(DC);
6677
6678   if (SCSpec == DeclSpec::SCS_mutable) {
6679     // mutable can only appear on non-static class members, so it's always
6680     // an error here
6681     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6682     D.setInvalidType();
6683     SC = SC_None;
6684   }
6685
6686   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6687       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6688                               D.getDeclSpec().getStorageClassSpecLoc())) {
6689     // In C++11, the 'register' storage class specifier is deprecated.
6690     // Suppress the warning in system macros, it's used in macros in some
6691     // popular C system headers, such as in glibc's htonl() macro.
6692     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6693          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6694                                    : diag::warn_deprecated_register)
6695       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6696   }
6697
6698   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6699
6700   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6701     // C99 6.9p2: The storage-class specifiers auto and register shall not
6702     // appear in the declaration specifiers in an external declaration.
6703     // Global Register+Asm is a GNU extension we support.
6704     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6705       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6706       D.setInvalidType();
6707     }
6708   }
6709
6710   bool IsMemberSpecialization = false;
6711   bool IsVariableTemplateSpecialization = false;
6712   bool IsPartialSpecialization = false;
6713   bool IsVariableTemplate = false;
6714   VarDecl *NewVD = nullptr;
6715   VarTemplateDecl *NewTemplate = nullptr;
6716   TemplateParameterList *TemplateParams = nullptr;
6717   if (!getLangOpts().CPlusPlus) {
6718     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6719                             II, R, TInfo, SC);
6720
6721     if (R->getContainedDeducedType())
6722       ParsingInitForAutoVars.insert(NewVD);
6723
6724     if (D.isInvalidType())
6725       NewVD->setInvalidDecl();
6726
6727     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6728         NewVD->hasLocalStorage())
6729       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6730                             NTCUC_AutoVar, NTCUK_Destruct);
6731   } else {
6732     bool Invalid = false;
6733
6734     if (DC->isRecord() && !CurContext->isRecord()) {
6735       // This is an out-of-line definition of a static data member.
6736       switch (SC) {
6737       case SC_None:
6738         break;
6739       case SC_Static:
6740         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6741              diag::err_static_out_of_line)
6742           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6743         break;
6744       case SC_Auto:
6745       case SC_Register:
6746       case SC_Extern:
6747         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6748         // to names of variables declared in a block or to function parameters.
6749         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6750         // of class members
6751
6752         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6753              diag::err_storage_class_for_static_member)
6754           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6755         break;
6756       case SC_PrivateExtern:
6757         llvm_unreachable("C storage class in c++!");
6758       }
6759     }
6760
6761     if (SC == SC_Static && CurContext->isRecord()) {
6762       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6763         if (RD->isLocalClass())
6764           Diag(D.getIdentifierLoc(),
6765                diag::err_static_data_member_not_allowed_in_local_class)
6766             << Name << RD->getDeclName();
6767
6768         // C++98 [class.union]p1: If a union contains a static data member,
6769         // the program is ill-formed. C++11 drops this restriction.
6770         if (RD->isUnion())
6771           Diag(D.getIdentifierLoc(),
6772                getLangOpts().CPlusPlus11
6773                  ? diag::warn_cxx98_compat_static_data_member_in_union
6774                  : diag::ext_static_data_member_in_union) << Name;
6775         // We conservatively disallow static data members in anonymous structs.
6776         else if (!RD->getDeclName())
6777           Diag(D.getIdentifierLoc(),
6778                diag::err_static_data_member_not_allowed_in_anon_struct)
6779             << Name << RD->isUnion();
6780       }
6781     }
6782
6783     // Match up the template parameter lists with the scope specifier, then
6784     // determine whether we have a template or a template specialization.
6785     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6786         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6787         D.getCXXScopeSpec(),
6788         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6789             ? D.getName().TemplateId
6790             : nullptr,
6791         TemplateParamLists,
6792         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6793
6794     if (TemplateParams) {
6795       if (!TemplateParams->size() &&
6796           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6797         // There is an extraneous 'template<>' for this variable. Complain
6798         // about it, but allow the declaration of the variable.
6799         Diag(TemplateParams->getTemplateLoc(),
6800              diag::err_template_variable_noparams)
6801           << II
6802           << SourceRange(TemplateParams->getTemplateLoc(),
6803                          TemplateParams->getRAngleLoc());
6804         TemplateParams = nullptr;
6805       } else {
6806         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6807           // This is an explicit specialization or a partial specialization.
6808           // FIXME: Check that we can declare a specialization here.
6809           IsVariableTemplateSpecialization = true;
6810           IsPartialSpecialization = TemplateParams->size() > 0;
6811         } else { // if (TemplateParams->size() > 0)
6812           // This is a template declaration.
6813           IsVariableTemplate = true;
6814
6815           // Check that we can declare a template here.
6816           if (CheckTemplateDeclScope(S, TemplateParams))
6817             return nullptr;
6818
6819           // Only C++1y supports variable templates (N3651).
6820           Diag(D.getIdentifierLoc(),
6821                getLangOpts().CPlusPlus14
6822                    ? diag::warn_cxx11_compat_variable_template
6823                    : diag::ext_variable_template);
6824         }
6825       }
6826     } else {
6827       assert((Invalid ||
6828               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6829              "should have a 'template<>' for this decl");
6830     }
6831
6832     if (IsVariableTemplateSpecialization) {
6833       SourceLocation TemplateKWLoc =
6834           TemplateParamLists.size() > 0
6835               ? TemplateParamLists[0]->getTemplateLoc()
6836               : SourceLocation();
6837       DeclResult Res = ActOnVarTemplateSpecialization(
6838           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6839           IsPartialSpecialization);
6840       if (Res.isInvalid())
6841         return nullptr;
6842       NewVD = cast<VarDecl>(Res.get());
6843       AddToScope = false;
6844     } else if (D.isDecompositionDeclarator()) {
6845       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6846                                         D.getIdentifierLoc(), R, TInfo, SC,
6847                                         Bindings);
6848     } else
6849       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6850                               D.getIdentifierLoc(), II, R, TInfo, SC);
6851
6852     // If this is supposed to be a variable template, create it as such.
6853     if (IsVariableTemplate) {
6854       NewTemplate =
6855           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6856                                   TemplateParams, NewVD);
6857       NewVD->setDescribedVarTemplate(NewTemplate);
6858     }
6859
6860     // If this decl has an auto type in need of deduction, make a note of the
6861     // Decl so we can diagnose uses of it in its own initializer.
6862     if (R->getContainedDeducedType())
6863       ParsingInitForAutoVars.insert(NewVD);
6864
6865     if (D.isInvalidType() || Invalid) {
6866       NewVD->setInvalidDecl();
6867       if (NewTemplate)
6868         NewTemplate->setInvalidDecl();
6869     }
6870
6871     SetNestedNameSpecifier(*this, NewVD, D);
6872
6873     // If we have any template parameter lists that don't directly belong to
6874     // the variable (matching the scope specifier), store them.
6875     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6876     if (TemplateParamLists.size() > VDTemplateParamLists)
6877       NewVD->setTemplateParameterListsInfo(
6878           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6879   }
6880
6881   if (D.getDeclSpec().isInlineSpecified()) {
6882     if (!getLangOpts().CPlusPlus) {
6883       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6884           << 0;
6885     } else if (CurContext->isFunctionOrMethod()) {
6886       // 'inline' is not allowed on block scope variable declaration.
6887       Diag(D.getDeclSpec().getInlineSpecLoc(),
6888            diag::err_inline_declaration_block_scope) << Name
6889         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6890     } else {
6891       Diag(D.getDeclSpec().getInlineSpecLoc(),
6892            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6893                                      : diag::ext_inline_variable);
6894       NewVD->setInlineSpecified();
6895     }
6896   }
6897
6898   // Set the lexical context. If the declarator has a C++ scope specifier, the
6899   // lexical context will be different from the semantic context.
6900   NewVD->setLexicalDeclContext(CurContext);
6901   if (NewTemplate)
6902     NewTemplate->setLexicalDeclContext(CurContext);
6903
6904   if (IsLocalExternDecl) {
6905     if (D.isDecompositionDeclarator())
6906       for (auto *B : Bindings)
6907         B->setLocalExternDecl();
6908     else
6909       NewVD->setLocalExternDecl();
6910   }
6911
6912   bool EmitTLSUnsupportedError = false;
6913   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6914     // C++11 [dcl.stc]p4:
6915     //   When thread_local is applied to a variable of block scope the
6916     //   storage-class-specifier static is implied if it does not appear
6917     //   explicitly.
6918     // Core issue: 'static' is not implied if the variable is declared
6919     //   'extern'.
6920     if (NewVD->hasLocalStorage() &&
6921         (SCSpec != DeclSpec::SCS_unspecified ||
6922          TSCS != DeclSpec::TSCS_thread_local ||
6923          !DC->isFunctionOrMethod()))
6924       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6925            diag::err_thread_non_global)
6926         << DeclSpec::getSpecifierName(TSCS);
6927     else if (!Context.getTargetInfo().isTLSSupported()) {
6928       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6929         // Postpone error emission until we've collected attributes required to
6930         // figure out whether it's a host or device variable and whether the
6931         // error should be ignored.
6932         EmitTLSUnsupportedError = true;
6933         // We still need to mark the variable as TLS so it shows up in AST with
6934         // proper storage class for other tools to use even if we're not going
6935         // to emit any code for it.
6936         NewVD->setTSCSpec(TSCS);
6937       } else
6938         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6939              diag::err_thread_unsupported);
6940     } else
6941       NewVD->setTSCSpec(TSCS);
6942   }
6943
6944   switch (D.getDeclSpec().getConstexprSpecifier()) {
6945   case CSK_unspecified:
6946     break;
6947
6948   case CSK_consteval:
6949     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6950         diag::err_constexpr_wrong_decl_kind)
6951       << D.getDeclSpec().getConstexprSpecifier();
6952     LLVM_FALLTHROUGH;
6953
6954   case CSK_constexpr:
6955     NewVD->setConstexpr(true);
6956     // C++1z [dcl.spec.constexpr]p1:
6957     //   A static data member declared with the constexpr specifier is
6958     //   implicitly an inline variable.
6959     if (NewVD->isStaticDataMember() &&
6960         (getLangOpts().CPlusPlus17 ||
6961          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6962       NewVD->setImplicitlyInline();
6963     break;
6964
6965   case CSK_constinit:
6966     if (!NewVD->hasGlobalStorage())
6967       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6968            diag::err_constinit_local_variable);
6969     else
6970       NewVD->addAttr(ConstInitAttr::Create(
6971           Context, D.getDeclSpec().getConstexprSpecLoc(),
6972           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6973     break;
6974   }
6975
6976   // C99 6.7.4p3
6977   //   An inline definition of a function with external linkage shall
6978   //   not contain a definition of a modifiable object with static or
6979   //   thread storage duration...
6980   // We only apply this when the function is required to be defined
6981   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6982   // that a local variable with thread storage duration still has to
6983   // be marked 'static'.  Also note that it's possible to get these
6984   // semantics in C++ using __attribute__((gnu_inline)).
6985   if (SC == SC_Static && S->getFnParent() != nullptr &&
6986       !NewVD->getType().isConstQualified()) {
6987     FunctionDecl *CurFD = getCurFunctionDecl();
6988     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6989       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6990            diag::warn_static_local_in_extern_inline);
6991       MaybeSuggestAddingStaticToDecl(CurFD);
6992     }
6993   }
6994
6995   if (D.getDeclSpec().isModulePrivateSpecified()) {
6996     if (IsVariableTemplateSpecialization)
6997       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6998           << (IsPartialSpecialization ? 1 : 0)
6999           << FixItHint::CreateRemoval(
7000                  D.getDeclSpec().getModulePrivateSpecLoc());
7001     else if (IsMemberSpecialization)
7002       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7003         << 2
7004         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7005     else if (NewVD->hasLocalStorage())
7006       Diag(NewVD->getLocation(), diag::err_module_private_local)
7007         << 0 << NewVD->getDeclName()
7008         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7009         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7010     else {
7011       NewVD->setModulePrivate();
7012       if (NewTemplate)
7013         NewTemplate->setModulePrivate();
7014       for (auto *B : Bindings)
7015         B->setModulePrivate();
7016     }
7017   }
7018
7019   if (getLangOpts().OpenCL) {
7020
7021     deduceOpenCLAddressSpace(NewVD);
7022
7023     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7024   }
7025
7026   // Handle attributes prior to checking for duplicates in MergeVarDecl
7027   ProcessDeclAttributes(S, NewVD, D);
7028
7029   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7030     if (EmitTLSUnsupportedError &&
7031         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7032          (getLangOpts().OpenMPIsDevice &&
7033           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7034       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7035            diag::err_thread_unsupported);
7036     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7037     // storage [duration]."
7038     if (SC == SC_None && S->getFnParent() != nullptr &&
7039         (NewVD->hasAttr<CUDASharedAttr>() ||
7040          NewVD->hasAttr<CUDAConstantAttr>())) {
7041       NewVD->setStorageClass(SC_Static);
7042     }
7043   }
7044
7045   // Ensure that dllimport globals without explicit storage class are treated as
7046   // extern. The storage class is set above using parsed attributes. Now we can
7047   // check the VarDecl itself.
7048   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7049          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7050          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7051
7052   // In auto-retain/release, infer strong retension for variables of
7053   // retainable type.
7054   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7055     NewVD->setInvalidDecl();
7056
7057   // Handle GNU asm-label extension (encoded as an attribute).
7058   if (Expr *E = (Expr*)D.getAsmLabel()) {
7059     // The parser guarantees this is a string.
7060     StringLiteral *SE = cast<StringLiteral>(E);
7061     StringRef Label = SE->getString();
7062     if (S->getFnParent() != nullptr) {
7063       switch (SC) {
7064       case SC_None:
7065       case SC_Auto:
7066         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7067         break;
7068       case SC_Register:
7069         // Local Named register
7070         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7071             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7072           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7073         break;
7074       case SC_Static:
7075       case SC_Extern:
7076       case SC_PrivateExtern:
7077         break;
7078       }
7079     } else if (SC == SC_Register) {
7080       // Global Named register
7081       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7082         const auto &TI = Context.getTargetInfo();
7083         bool HasSizeMismatch;
7084
7085         if (!TI.isValidGCCRegisterName(Label))
7086           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7087         else if (!TI.validateGlobalRegisterVariable(Label,
7088                                                     Context.getTypeSize(R),
7089                                                     HasSizeMismatch))
7090           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7091         else if (HasSizeMismatch)
7092           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7093       }
7094
7095       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7096         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7097         NewVD->setInvalidDecl(true);
7098       }
7099     }
7100
7101     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7102                                         /*IsLiteralLabel=*/true,
7103                                         SE->getStrTokenLoc(0)));
7104   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7105     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7106       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7107     if (I != ExtnameUndeclaredIdentifiers.end()) {
7108       if (isDeclExternC(NewVD)) {
7109         NewVD->addAttr(I->second);
7110         ExtnameUndeclaredIdentifiers.erase(I);
7111       } else
7112         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7113             << /*Variable*/1 << NewVD;
7114     }
7115   }
7116
7117   // Find the shadowed declaration before filtering for scope.
7118   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7119                                 ? getShadowedDeclaration(NewVD, Previous)
7120                                 : nullptr;
7121
7122   // Don't consider existing declarations that are in a different
7123   // scope and are out-of-semantic-context declarations (if the new
7124   // declaration has linkage).
7125   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7126                        D.getCXXScopeSpec().isNotEmpty() ||
7127                        IsMemberSpecialization ||
7128                        IsVariableTemplateSpecialization);
7129
7130   // Check whether the previous declaration is in the same block scope. This
7131   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7132   if (getLangOpts().CPlusPlus &&
7133       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7134     NewVD->setPreviousDeclInSameBlockScope(
7135         Previous.isSingleResult() && !Previous.isShadowed() &&
7136         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7137
7138   if (!getLangOpts().CPlusPlus) {
7139     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7140   } else {
7141     // If this is an explicit specialization of a static data member, check it.
7142     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7143         CheckMemberSpecialization(NewVD, Previous))
7144       NewVD->setInvalidDecl();
7145
7146     // Merge the decl with the existing one if appropriate.
7147     if (!Previous.empty()) {
7148       if (Previous.isSingleResult() &&
7149           isa<FieldDecl>(Previous.getFoundDecl()) &&
7150           D.getCXXScopeSpec().isSet()) {
7151         // The user tried to define a non-static data member
7152         // out-of-line (C++ [dcl.meaning]p1).
7153         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7154           << D.getCXXScopeSpec().getRange();
7155         Previous.clear();
7156         NewVD->setInvalidDecl();
7157       }
7158     } else if (D.getCXXScopeSpec().isSet()) {
7159       // No previous declaration in the qualifying scope.
7160       Diag(D.getIdentifierLoc(), diag::err_no_member)
7161         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7162         << D.getCXXScopeSpec().getRange();
7163       NewVD->setInvalidDecl();
7164     }
7165
7166     if (!IsVariableTemplateSpecialization)
7167       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7168
7169     if (NewTemplate) {
7170       VarTemplateDecl *PrevVarTemplate =
7171           NewVD->getPreviousDecl()
7172               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7173               : nullptr;
7174
7175       // Check the template parameter list of this declaration, possibly
7176       // merging in the template parameter list from the previous variable
7177       // template declaration.
7178       if (CheckTemplateParameterList(
7179               TemplateParams,
7180               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7181                               : nullptr,
7182               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7183                DC->isDependentContext())
7184                   ? TPC_ClassTemplateMember
7185                   : TPC_VarTemplate))
7186         NewVD->setInvalidDecl();
7187
7188       // If we are providing an explicit specialization of a static variable
7189       // template, make a note of that.
7190       if (PrevVarTemplate &&
7191           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7192         PrevVarTemplate->setMemberSpecialization();
7193     }
7194   }
7195
7196   // Diagnose shadowed variables iff this isn't a redeclaration.
7197   if (ShadowedDecl && !D.isRedeclaration())
7198     CheckShadow(NewVD, ShadowedDecl, Previous);
7199
7200   ProcessPragmaWeak(S, NewVD);
7201
7202   // If this is the first declaration of an extern C variable, update
7203   // the map of such variables.
7204   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7205       isIncompleteDeclExternC(*this, NewVD))
7206     RegisterLocallyScopedExternCDecl(NewVD, S);
7207
7208   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7209     MangleNumberingContext *MCtx;
7210     Decl *ManglingContextDecl;
7211     std::tie(MCtx, ManglingContextDecl) =
7212         getCurrentMangleNumberContext(NewVD->getDeclContext());
7213     if (MCtx) {
7214       Context.setManglingNumber(
7215           NewVD, MCtx->getManglingNumber(
7216                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7217       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7218     }
7219   }
7220
7221   // Special handling of variable named 'main'.
7222   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7223       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7224       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7225
7226     // C++ [basic.start.main]p3
7227     // A program that declares a variable main at global scope is ill-formed.
7228     if (getLangOpts().CPlusPlus)
7229       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7230
7231     // In C, and external-linkage variable named main results in undefined
7232     // behavior.
7233     else if (NewVD->hasExternalFormalLinkage())
7234       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7235   }
7236
7237   if (D.isRedeclaration() && !Previous.empty()) {
7238     NamedDecl *Prev = Previous.getRepresentativeDecl();
7239     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7240                                    D.isFunctionDefinition());
7241   }
7242
7243   if (NewTemplate) {
7244     if (NewVD->isInvalidDecl())
7245       NewTemplate->setInvalidDecl();
7246     ActOnDocumentableDecl(NewTemplate);
7247     return NewTemplate;
7248   }
7249
7250   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7251     CompleteMemberSpecialization(NewVD, Previous);
7252
7253   return NewVD;
7254 }
7255
7256 /// Enum describing the %select options in diag::warn_decl_shadow.
7257 enum ShadowedDeclKind {
7258   SDK_Local,
7259   SDK_Global,
7260   SDK_StaticMember,
7261   SDK_Field,
7262   SDK_Typedef,
7263   SDK_Using
7264 };
7265
7266 /// Determine what kind of declaration we're shadowing.
7267 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7268                                                 const DeclContext *OldDC) {
7269   if (isa<TypeAliasDecl>(ShadowedDecl))
7270     return SDK_Using;
7271   else if (isa<TypedefDecl>(ShadowedDecl))
7272     return SDK_Typedef;
7273   else if (isa<RecordDecl>(OldDC))
7274     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7275
7276   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7277 }
7278
7279 /// Return the location of the capture if the given lambda captures the given
7280 /// variable \p VD, or an invalid source location otherwise.
7281 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7282                                          const VarDecl *VD) {
7283   for (const Capture &Capture : LSI->Captures) {
7284     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7285       return Capture.getLocation();
7286   }
7287   return SourceLocation();
7288 }
7289
7290 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7291                                      const LookupResult &R) {
7292   // Only diagnose if we're shadowing an unambiguous field or variable.
7293   if (R.getResultKind() != LookupResult::Found)
7294     return false;
7295
7296   // Return false if warning is ignored.
7297   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7298 }
7299
7300 /// Return the declaration shadowed by the given variable \p D, or null
7301 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7302 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7303                                         const LookupResult &R) {
7304   if (!shouldWarnIfShadowedDecl(Diags, R))
7305     return nullptr;
7306
7307   // Don't diagnose declarations at file scope.
7308   if (D->hasGlobalStorage())
7309     return nullptr;
7310
7311   NamedDecl *ShadowedDecl = R.getFoundDecl();
7312   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7313              ? ShadowedDecl
7314              : nullptr;
7315 }
7316
7317 /// Return the declaration shadowed by the given typedef \p D, or null
7318 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7319 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7320                                         const LookupResult &R) {
7321   // Don't warn if typedef declaration is part of a class
7322   if (D->getDeclContext()->isRecord())
7323     return nullptr;
7324
7325   if (!shouldWarnIfShadowedDecl(Diags, R))
7326     return nullptr;
7327
7328   NamedDecl *ShadowedDecl = R.getFoundDecl();
7329   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7330 }
7331
7332 /// Diagnose variable or built-in function shadowing.  Implements
7333 /// -Wshadow.
7334 ///
7335 /// This method is called whenever a VarDecl is added to a "useful"
7336 /// scope.
7337 ///
7338 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7339 /// \param R the lookup of the name
7340 ///
7341 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7342                        const LookupResult &R) {
7343   DeclContext *NewDC = D->getDeclContext();
7344
7345   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7346     // Fields are not shadowed by variables in C++ static methods.
7347     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7348       if (MD->isStatic())
7349         return;
7350
7351     // Fields shadowed by constructor parameters are a special case. Usually
7352     // the constructor initializes the field with the parameter.
7353     if (isa<CXXConstructorDecl>(NewDC))
7354       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7355         // Remember that this was shadowed so we can either warn about its
7356         // modification or its existence depending on warning settings.
7357         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7358         return;
7359       }
7360   }
7361
7362   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7363     if (shadowedVar->isExternC()) {
7364       // For shadowing external vars, make sure that we point to the global
7365       // declaration, not a locally scoped extern declaration.
7366       for (auto I : shadowedVar->redecls())
7367         if (I->isFileVarDecl()) {
7368           ShadowedDecl = I;
7369           break;
7370         }
7371     }
7372
7373   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7374
7375   unsigned WarningDiag = diag::warn_decl_shadow;
7376   SourceLocation CaptureLoc;
7377   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7378       isa<CXXMethodDecl>(NewDC)) {
7379     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7380       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7381         if (RD->getLambdaCaptureDefault() == LCD_None) {
7382           // Try to avoid warnings for lambdas with an explicit capture list.
7383           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7384           // Warn only when the lambda captures the shadowed decl explicitly.
7385           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7386           if (CaptureLoc.isInvalid())
7387             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7388         } else {
7389           // Remember that this was shadowed so we can avoid the warning if the
7390           // shadowed decl isn't captured and the warning settings allow it.
7391           cast<LambdaScopeInfo>(getCurFunction())
7392               ->ShadowingDecls.push_back(
7393                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7394           return;
7395         }
7396       }
7397
7398       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7399         // A variable can't shadow a local variable in an enclosing scope, if
7400         // they are separated by a non-capturing declaration context.
7401         for (DeclContext *ParentDC = NewDC;
7402              ParentDC && !ParentDC->Equals(OldDC);
7403              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7404           // Only block literals, captured statements, and lambda expressions
7405           // can capture; other scopes don't.
7406           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7407               !isLambdaCallOperator(ParentDC)) {
7408             return;
7409           }
7410         }
7411       }
7412     }
7413   }
7414
7415   // Only warn about certain kinds of shadowing for class members.
7416   if (NewDC && NewDC->isRecord()) {
7417     // In particular, don't warn about shadowing non-class members.
7418     if (!OldDC->isRecord())
7419       return;
7420
7421     // TODO: should we warn about static data members shadowing
7422     // static data members from base classes?
7423
7424     // TODO: don't diagnose for inaccessible shadowed members.
7425     // This is hard to do perfectly because we might friend the
7426     // shadowing context, but that's just a false negative.
7427   }
7428
7429
7430   DeclarationName Name = R.getLookupName();
7431
7432   // Emit warning and note.
7433   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7434     return;
7435   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7436   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7437   if (!CaptureLoc.isInvalid())
7438     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7439         << Name << /*explicitly*/ 1;
7440   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7441 }
7442
7443 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7444 /// when these variables are captured by the lambda.
7445 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7446   for (const auto &Shadow : LSI->ShadowingDecls) {
7447     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7448     // Try to avoid the warning when the shadowed decl isn't captured.
7449     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7450     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7451     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7452                                        ? diag::warn_decl_shadow_uncaptured_local
7453                                        : diag::warn_decl_shadow)
7454         << Shadow.VD->getDeclName()
7455         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7456     if (!CaptureLoc.isInvalid())
7457       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7458           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7459     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7460   }
7461 }
7462
7463 /// Check -Wshadow without the advantage of a previous lookup.
7464 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7465   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7466     return;
7467
7468   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7469                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7470   LookupName(R, S);
7471   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7472     CheckShadow(D, ShadowedDecl, R);
7473 }
7474
7475 /// Check if 'E', which is an expression that is about to be modified, refers
7476 /// to a constructor parameter that shadows a field.
7477 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7478   // Quickly ignore expressions that can't be shadowing ctor parameters.
7479   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7480     return;
7481   E = E->IgnoreParenImpCasts();
7482   auto *DRE = dyn_cast<DeclRefExpr>(E);
7483   if (!DRE)
7484     return;
7485   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7486   auto I = ShadowingDecls.find(D);
7487   if (I == ShadowingDecls.end())
7488     return;
7489   const NamedDecl *ShadowedDecl = I->second;
7490   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7491   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7492   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7493   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7494
7495   // Avoid issuing multiple warnings about the same decl.
7496   ShadowingDecls.erase(I);
7497 }
7498
7499 /// Check for conflict between this global or extern "C" declaration and
7500 /// previous global or extern "C" declarations. This is only used in C++.
7501 template<typename T>
7502 static bool checkGlobalOrExternCConflict(
7503     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7504   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7505   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7506
7507   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7508     // The common case: this global doesn't conflict with any extern "C"
7509     // declaration.
7510     return false;
7511   }
7512
7513   if (Prev) {
7514     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7515       // Both the old and new declarations have C language linkage. This is a
7516       // redeclaration.
7517       Previous.clear();
7518       Previous.addDecl(Prev);
7519       return true;
7520     }
7521
7522     // This is a global, non-extern "C" declaration, and there is a previous
7523     // non-global extern "C" declaration. Diagnose if this is a variable
7524     // declaration.
7525     if (!isa<VarDecl>(ND))
7526       return false;
7527   } else {
7528     // The declaration is extern "C". Check for any declaration in the
7529     // translation unit which might conflict.
7530     if (IsGlobal) {
7531       // We have already performed the lookup into the translation unit.
7532       IsGlobal = false;
7533       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7534            I != E; ++I) {
7535         if (isa<VarDecl>(*I)) {
7536           Prev = *I;
7537           break;
7538         }
7539       }
7540     } else {
7541       DeclContext::lookup_result R =
7542           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7543       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7544            I != E; ++I) {
7545         if (isa<VarDecl>(*I)) {
7546           Prev = *I;
7547           break;
7548         }
7549         // FIXME: If we have any other entity with this name in global scope,
7550         // the declaration is ill-formed, but that is a defect: it breaks the
7551         // 'stat' hack, for instance. Only variables can have mangled name
7552         // clashes with extern "C" declarations, so only they deserve a
7553         // diagnostic.
7554       }
7555     }
7556
7557     if (!Prev)
7558       return false;
7559   }
7560
7561   // Use the first declaration's location to ensure we point at something which
7562   // is lexically inside an extern "C" linkage-spec.
7563   assert(Prev && "should have found a previous declaration to diagnose");
7564   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7565     Prev = FD->getFirstDecl();
7566   else
7567     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7568
7569   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7570     << IsGlobal << ND;
7571   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7572     << IsGlobal;
7573   return false;
7574 }
7575
7576 /// Apply special rules for handling extern "C" declarations. Returns \c true
7577 /// if we have found that this is a redeclaration of some prior entity.
7578 ///
7579 /// Per C++ [dcl.link]p6:
7580 ///   Two declarations [for a function or variable] with C language linkage
7581 ///   with the same name that appear in different scopes refer to the same
7582 ///   [entity]. An entity with C language linkage shall not be declared with
7583 ///   the same name as an entity in global scope.
7584 template<typename T>
7585 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7586                                                   LookupResult &Previous) {
7587   if (!S.getLangOpts().CPlusPlus) {
7588     // In C, when declaring a global variable, look for a corresponding 'extern'
7589     // variable declared in function scope. We don't need this in C++, because
7590     // we find local extern decls in the surrounding file-scope DeclContext.
7591     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7592       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7593         Previous.clear();
7594         Previous.addDecl(Prev);
7595         return true;
7596       }
7597     }
7598     return false;
7599   }
7600
7601   // A declaration in the translation unit can conflict with an extern "C"
7602   // declaration.
7603   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7604     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7605
7606   // An extern "C" declaration can conflict with a declaration in the
7607   // translation unit or can be a redeclaration of an extern "C" declaration
7608   // in another scope.
7609   if (isIncompleteDeclExternC(S,ND))
7610     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7611
7612   // Neither global nor extern "C": nothing to do.
7613   return false;
7614 }
7615
7616 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7617   // If the decl is already known invalid, don't check it.
7618   if (NewVD->isInvalidDecl())
7619     return;
7620
7621   QualType T = NewVD->getType();
7622
7623   // Defer checking an 'auto' type until its initializer is attached.
7624   if (T->isUndeducedType())
7625     return;
7626
7627   if (NewVD->hasAttrs())
7628     CheckAlignasUnderalignment(NewVD);
7629
7630   if (T->isObjCObjectType()) {
7631     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7632       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7633     T = Context.getObjCObjectPointerType(T);
7634     NewVD->setType(T);
7635   }
7636
7637   // Emit an error if an address space was applied to decl with local storage.
7638   // This includes arrays of objects with address space qualifiers, but not
7639   // automatic variables that point to other address spaces.
7640   // ISO/IEC TR 18037 S5.1.2
7641   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7642       T.getAddressSpace() != LangAS::Default) {
7643     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7644     NewVD->setInvalidDecl();
7645     return;
7646   }
7647
7648   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7649   // scope.
7650   if (getLangOpts().OpenCLVersion == 120 &&
7651       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7652       NewVD->isStaticLocal()) {
7653     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7654     NewVD->setInvalidDecl();
7655     return;
7656   }
7657
7658   if (getLangOpts().OpenCL) {
7659     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7660     if (NewVD->hasAttr<BlocksAttr>()) {
7661       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7662       return;
7663     }
7664
7665     if (T->isBlockPointerType()) {
7666       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7667       // can't use 'extern' storage class.
7668       if (!T.isConstQualified()) {
7669         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7670             << 0 /*const*/;
7671         NewVD->setInvalidDecl();
7672         return;
7673       }
7674       if (NewVD->hasExternalStorage()) {
7675         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7676         NewVD->setInvalidDecl();
7677         return;
7678       }
7679     }
7680     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7681     // __constant address space.
7682     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7683     // variables inside a function can also be declared in the global
7684     // address space.
7685     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7686     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7687     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7688         NewVD->hasExternalStorage()) {
7689       if (!T->isSamplerT() &&
7690           !(T.getAddressSpace() == LangAS::opencl_constant ||
7691             (T.getAddressSpace() == LangAS::opencl_global &&
7692              (getLangOpts().OpenCLVersion == 200 ||
7693               getLangOpts().OpenCLCPlusPlus)))) {
7694         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7695         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7696           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7697               << Scope << "global or constant";
7698         else
7699           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7700               << Scope << "constant";
7701         NewVD->setInvalidDecl();
7702         return;
7703       }
7704     } else {
7705       if (T.getAddressSpace() == LangAS::opencl_global) {
7706         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7707             << 1 /*is any function*/ << "global";
7708         NewVD->setInvalidDecl();
7709         return;
7710       }
7711       if (T.getAddressSpace() == LangAS::opencl_constant ||
7712           T.getAddressSpace() == LangAS::opencl_local) {
7713         FunctionDecl *FD = getCurFunctionDecl();
7714         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7715         // in functions.
7716         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7717           if (T.getAddressSpace() == LangAS::opencl_constant)
7718             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7719                 << 0 /*non-kernel only*/ << "constant";
7720           else
7721             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7722                 << 0 /*non-kernel only*/ << "local";
7723           NewVD->setInvalidDecl();
7724           return;
7725         }
7726         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7727         // in the outermost scope of a kernel function.
7728         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7729           if (!getCurScope()->isFunctionScope()) {
7730             if (T.getAddressSpace() == LangAS::opencl_constant)
7731               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7732                   << "constant";
7733             else
7734               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7735                   << "local";
7736             NewVD->setInvalidDecl();
7737             return;
7738           }
7739         }
7740       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7741                  // If we are parsing a template we didn't deduce an addr
7742                  // space yet.
7743                  T.getAddressSpace() != LangAS::Default) {
7744         // Do not allow other address spaces on automatic variable.
7745         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7746         NewVD->setInvalidDecl();
7747         return;
7748       }
7749     }
7750   }
7751
7752   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7753       && !NewVD->hasAttr<BlocksAttr>()) {
7754     if (getLangOpts().getGC() != LangOptions::NonGC)
7755       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7756     else {
7757       assert(!getLangOpts().ObjCAutoRefCount);
7758       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7759     }
7760   }
7761
7762   bool isVM = T->isVariablyModifiedType();
7763   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7764       NewVD->hasAttr<BlocksAttr>())
7765     setFunctionHasBranchProtectedScope();
7766
7767   if ((isVM && NewVD->hasLinkage()) ||
7768       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7769     bool SizeIsNegative;
7770     llvm::APSInt Oversized;
7771     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7772         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7773     QualType FixedT;
7774     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7775       FixedT = FixedTInfo->getType();
7776     else if (FixedTInfo) {
7777       // Type and type-as-written are canonically different. We need to fix up
7778       // both types separately.
7779       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7780                                                    Oversized);
7781     }
7782     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7783       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7784       // FIXME: This won't give the correct result for
7785       // int a[10][n];
7786       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7787
7788       if (NewVD->isFileVarDecl())
7789         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7790         << SizeRange;
7791       else if (NewVD->isStaticLocal())
7792         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7793         << SizeRange;
7794       else
7795         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7796         << SizeRange;
7797       NewVD->setInvalidDecl();
7798       return;
7799     }
7800
7801     if (!FixedTInfo) {
7802       if (NewVD->isFileVarDecl())
7803         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7804       else
7805         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7806       NewVD->setInvalidDecl();
7807       return;
7808     }
7809
7810     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7811     NewVD->setType(FixedT);
7812     NewVD->setTypeSourceInfo(FixedTInfo);
7813   }
7814
7815   if (T->isVoidType()) {
7816     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7817     //                    of objects and functions.
7818     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7819       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7820         << T;
7821       NewVD->setInvalidDecl();
7822       return;
7823     }
7824   }
7825
7826   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7827     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7828     NewVD->setInvalidDecl();
7829     return;
7830   }
7831
7832   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7833     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7834     NewVD->setInvalidDecl();
7835     return;
7836   }
7837
7838   if (NewVD->isConstexpr() && !T->isDependentType() &&
7839       RequireLiteralType(NewVD->getLocation(), T,
7840                          diag::err_constexpr_var_non_literal)) {
7841     NewVD->setInvalidDecl();
7842     return;
7843   }
7844 }
7845
7846 /// Perform semantic checking on a newly-created variable
7847 /// declaration.
7848 ///
7849 /// This routine performs all of the type-checking required for a
7850 /// variable declaration once it has been built. It is used both to
7851 /// check variables after they have been parsed and their declarators
7852 /// have been translated into a declaration, and to check variables
7853 /// that have been instantiated from a template.
7854 ///
7855 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7856 ///
7857 /// Returns true if the variable declaration is a redeclaration.
7858 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7859   CheckVariableDeclarationType(NewVD);
7860
7861   // If the decl is already known invalid, don't check it.
7862   if (NewVD->isInvalidDecl())
7863     return false;
7864
7865   // If we did not find anything by this name, look for a non-visible
7866   // extern "C" declaration with the same name.
7867   if (Previous.empty() &&
7868       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7869     Previous.setShadowed();
7870
7871   if (!Previous.empty()) {
7872     MergeVarDecl(NewVD, Previous);
7873     return true;
7874   }
7875   return false;
7876 }
7877
7878 namespace {
7879 struct FindOverriddenMethod {
7880   Sema *S;
7881   CXXMethodDecl *Method;
7882
7883   /// Member lookup function that determines whether a given C++
7884   /// method overrides a method in a base class, to be used with
7885   /// CXXRecordDecl::lookupInBases().
7886   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7887     RecordDecl *BaseRecord =
7888         Specifier->getType()->castAs<RecordType>()->getDecl();
7889
7890     DeclarationName Name = Method->getDeclName();
7891
7892     // FIXME: Do we care about other names here too?
7893     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7894       // We really want to find the base class destructor here.
7895       QualType T = S->Context.getTypeDeclType(BaseRecord);
7896       CanQualType CT = S->Context.getCanonicalType(T);
7897
7898       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7899     }
7900
7901     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7902          Path.Decls = Path.Decls.slice(1)) {
7903       NamedDecl *D = Path.Decls.front();
7904       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7905         if (MD->isVirtual() &&
7906             !S->IsOverload(
7907                 Method, MD, /*UseMemberUsingDeclRules=*/false,
7908                 /*ConsiderCudaAttrs=*/true,
7909                 // C++2a [class.virtual]p2 does not consider requires clauses
7910                 // when overriding.
7911                 /*ConsiderRequiresClauses=*/false))
7912           return true;
7913       }
7914     }
7915
7916     return false;
7917   }
7918 };
7919
7920 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7921 } // end anonymous namespace
7922
7923 /// Report an error regarding overriding, along with any relevant
7924 /// overridden methods.
7925 ///
7926 /// \param DiagID the primary error to report.
7927 /// \param MD the overriding method.
7928 /// \param OEK which overrides to include as notes.
7929 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7930                             OverrideErrorKind OEK = OEK_All) {
7931   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7932   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7933     // This check (& the OEK parameter) could be replaced by a predicate, but
7934     // without lambdas that would be overkill. This is still nicer than writing
7935     // out the diag loop 3 times.
7936     if ((OEK == OEK_All) ||
7937         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7938         (OEK == OEK_Deleted && O->isDeleted()))
7939       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7940   }
7941 }
7942
7943 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7944 /// and if so, check that it's a valid override and remember it.
7945 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7946   // Look for methods in base classes that this method might override.
7947   CXXBasePaths Paths;
7948   FindOverriddenMethod FOM;
7949   FOM.Method = MD;
7950   FOM.S = this;
7951   bool hasDeletedOverridenMethods = false;
7952   bool hasNonDeletedOverridenMethods = false;
7953   bool AddedAny = false;
7954   if (DC->lookupInBases(FOM, Paths)) {
7955     for (auto *I : Paths.found_decls()) {
7956       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7957         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7958         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7959             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7960             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7961             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7962           hasDeletedOverridenMethods |= OldMD->isDeleted();
7963           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7964           AddedAny = true;
7965         }
7966       }
7967     }
7968   }
7969
7970   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7971     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7972   }
7973   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7974     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7975   }
7976
7977   return AddedAny;
7978 }
7979
7980 namespace {
7981   // Struct for holding all of the extra arguments needed by
7982   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7983   struct ActOnFDArgs {
7984     Scope *S;
7985     Declarator &D;
7986     MultiTemplateParamsArg TemplateParamLists;
7987     bool AddToScope;
7988   };
7989 } // end anonymous namespace
7990
7991 namespace {
7992
7993 // Callback to only accept typo corrections that have a non-zero edit distance.
7994 // Also only accept corrections that have the same parent decl.
7995 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7996  public:
7997   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7998                             CXXRecordDecl *Parent)
7999       : Context(Context), OriginalFD(TypoFD),
8000         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8001
8002   bool ValidateCandidate(const TypoCorrection &candidate) override {
8003     if (candidate.getEditDistance() == 0)
8004       return false;
8005
8006     SmallVector<unsigned, 1> MismatchedParams;
8007     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8008                                           CDeclEnd = candidate.end();
8009          CDecl != CDeclEnd; ++CDecl) {
8010       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8011
8012       if (FD && !FD->hasBody() &&
8013           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8014         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8015           CXXRecordDecl *Parent = MD->getParent();
8016           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8017             return true;
8018         } else if (!ExpectedParent) {
8019           return true;
8020         }
8021       }
8022     }
8023
8024     return false;
8025   }
8026
8027   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8028     return std::make_unique<DifferentNameValidatorCCC>(*this);
8029   }
8030
8031  private:
8032   ASTContext &Context;
8033   FunctionDecl *OriginalFD;
8034   CXXRecordDecl *ExpectedParent;
8035 };
8036
8037 } // end anonymous namespace
8038
8039 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8040   TypoCorrectedFunctionDefinitions.insert(F);
8041 }
8042
8043 /// Generate diagnostics for an invalid function redeclaration.
8044 ///
8045 /// This routine handles generating the diagnostic messages for an invalid
8046 /// function redeclaration, including finding possible similar declarations
8047 /// or performing typo correction if there are no previous declarations with
8048 /// the same name.
8049 ///
8050 /// Returns a NamedDecl iff typo correction was performed and substituting in
8051 /// the new declaration name does not cause new errors.
8052 static NamedDecl *DiagnoseInvalidRedeclaration(
8053     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8054     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8055   DeclarationName Name = NewFD->getDeclName();
8056   DeclContext *NewDC = NewFD->getDeclContext();
8057   SmallVector<unsigned, 1> MismatchedParams;
8058   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8059   TypoCorrection Correction;
8060   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8061   unsigned DiagMsg =
8062     IsLocalFriend ? diag::err_no_matching_local_friend :
8063     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8064     diag::err_member_decl_does_not_match;
8065   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8066                     IsLocalFriend ? Sema::LookupLocalFriendName
8067                                   : Sema::LookupOrdinaryName,
8068                     Sema::ForVisibleRedeclaration);
8069
8070   NewFD->setInvalidDecl();
8071   if (IsLocalFriend)
8072     SemaRef.LookupName(Prev, S);
8073   else
8074     SemaRef.LookupQualifiedName(Prev, NewDC);
8075   assert(!Prev.isAmbiguous() &&
8076          "Cannot have an ambiguity in previous-declaration lookup");
8077   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8078   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8079                                 MD ? MD->getParent() : nullptr);
8080   if (!Prev.empty()) {
8081     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8082          Func != FuncEnd; ++Func) {
8083       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8084       if (FD &&
8085           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8086         // Add 1 to the index so that 0 can mean the mismatch didn't
8087         // involve a parameter
8088         unsigned ParamNum =
8089             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8090         NearMatches.push_back(std::make_pair(FD, ParamNum));
8091       }
8092     }
8093   // If the qualified name lookup yielded nothing, try typo correction
8094   } else if ((Correction = SemaRef.CorrectTypo(
8095                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8096                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8097                   IsLocalFriend ? nullptr : NewDC))) {
8098     // Set up everything for the call to ActOnFunctionDeclarator
8099     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8100                               ExtraArgs.D.getIdentifierLoc());
8101     Previous.clear();
8102     Previous.setLookupName(Correction.getCorrection());
8103     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8104                                     CDeclEnd = Correction.end();
8105          CDecl != CDeclEnd; ++CDecl) {
8106       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8107       if (FD && !FD->hasBody() &&
8108           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8109         Previous.addDecl(FD);
8110       }
8111     }
8112     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8113
8114     NamedDecl *Result;
8115     // Retry building the function declaration with the new previous
8116     // declarations, and with errors suppressed.
8117     {
8118       // Trap errors.
8119       Sema::SFINAETrap Trap(SemaRef);
8120
8121       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8122       // pieces need to verify the typo-corrected C++ declaration and hopefully
8123       // eliminate the need for the parameter pack ExtraArgs.
8124       Result = SemaRef.ActOnFunctionDeclarator(
8125           ExtraArgs.S, ExtraArgs.D,
8126           Correction.getCorrectionDecl()->getDeclContext(),
8127           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8128           ExtraArgs.AddToScope);
8129
8130       if (Trap.hasErrorOccurred())
8131         Result = nullptr;
8132     }
8133
8134     if (Result) {
8135       // Determine which correction we picked.
8136       Decl *Canonical = Result->getCanonicalDecl();
8137       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8138            I != E; ++I)
8139         if ((*I)->getCanonicalDecl() == Canonical)
8140           Correction.setCorrectionDecl(*I);
8141
8142       // Let Sema know about the correction.
8143       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8144       SemaRef.diagnoseTypo(
8145           Correction,
8146           SemaRef.PDiag(IsLocalFriend
8147                           ? diag::err_no_matching_local_friend_suggest
8148                           : diag::err_member_decl_does_not_match_suggest)
8149             << Name << NewDC << IsDefinition);
8150       return Result;
8151     }
8152
8153     // Pretend the typo correction never occurred
8154     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8155                               ExtraArgs.D.getIdentifierLoc());
8156     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8157     Previous.clear();
8158     Previous.setLookupName(Name);
8159   }
8160
8161   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8162       << Name << NewDC << IsDefinition << NewFD->getLocation();
8163
8164   bool NewFDisConst = false;
8165   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8166     NewFDisConst = NewMD->isConst();
8167
8168   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8169        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8170        NearMatch != NearMatchEnd; ++NearMatch) {
8171     FunctionDecl *FD = NearMatch->first;
8172     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8173     bool FDisConst = MD && MD->isConst();
8174     bool IsMember = MD || !IsLocalFriend;
8175
8176     // FIXME: These notes are poorly worded for the local friend case.
8177     if (unsigned Idx = NearMatch->second) {
8178       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8179       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8180       if (Loc.isInvalid()) Loc = FD->getLocation();
8181       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8182                                  : diag::note_local_decl_close_param_match)
8183         << Idx << FDParam->getType()
8184         << NewFD->getParamDecl(Idx - 1)->getType();
8185     } else if (FDisConst != NewFDisConst) {
8186       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8187           << NewFDisConst << FD->getSourceRange().getEnd();
8188     } else
8189       SemaRef.Diag(FD->getLocation(),
8190                    IsMember ? diag::note_member_def_close_match
8191                             : diag::note_local_decl_close_match);
8192   }
8193   return nullptr;
8194 }
8195
8196 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8197   switch (D.getDeclSpec().getStorageClassSpec()) {
8198   default: llvm_unreachable("Unknown storage class!");
8199   case DeclSpec::SCS_auto:
8200   case DeclSpec::SCS_register:
8201   case DeclSpec::SCS_mutable:
8202     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8203                  diag::err_typecheck_sclass_func);
8204     D.getMutableDeclSpec().ClearStorageClassSpecs();
8205     D.setInvalidType();
8206     break;
8207   case DeclSpec::SCS_unspecified: break;
8208   case DeclSpec::SCS_extern:
8209     if (D.getDeclSpec().isExternInLinkageSpec())
8210       return SC_None;
8211     return SC_Extern;
8212   case DeclSpec::SCS_static: {
8213     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8214       // C99 6.7.1p5:
8215       //   The declaration of an identifier for a function that has
8216       //   block scope shall have no explicit storage-class specifier
8217       //   other than extern
8218       // See also (C++ [dcl.stc]p4).
8219       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8220                    diag::err_static_block_func);
8221       break;
8222     } else
8223       return SC_Static;
8224   }
8225   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8226   }
8227
8228   // No explicit storage class has already been returned
8229   return SC_None;
8230 }
8231
8232 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8233                                            DeclContext *DC, QualType &R,
8234                                            TypeSourceInfo *TInfo,
8235                                            StorageClass SC,
8236                                            bool &IsVirtualOkay) {
8237   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8238   DeclarationName Name = NameInfo.getName();
8239
8240   FunctionDecl *NewFD = nullptr;
8241   bool isInline = D.getDeclSpec().isInlineSpecified();
8242
8243   if (!SemaRef.getLangOpts().CPlusPlus) {
8244     // Determine whether the function was written with a
8245     // prototype. This true when:
8246     //   - there is a prototype in the declarator, or
8247     //   - the type R of the function is some kind of typedef or other non-
8248     //     attributed reference to a type name (which eventually refers to a
8249     //     function type).
8250     bool HasPrototype =
8251       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8252       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8253
8254     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8255                                  R, TInfo, SC, isInline, HasPrototype,
8256                                  CSK_unspecified,
8257                                  /*TrailingRequiresClause=*/nullptr);
8258     if (D.isInvalidType())
8259       NewFD->setInvalidDecl();
8260
8261     return NewFD;
8262   }
8263
8264   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8265
8266   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8267   if (ConstexprKind == CSK_constinit) {
8268     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8269                  diag::err_constexpr_wrong_decl_kind)
8270         << ConstexprKind;
8271     ConstexprKind = CSK_unspecified;
8272     D.getMutableDeclSpec().ClearConstexprSpec();
8273   }
8274   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8275
8276   // Check that the return type is not an abstract class type.
8277   // For record types, this is done by the AbstractClassUsageDiagnoser once
8278   // the class has been completely parsed.
8279   if (!DC->isRecord() &&
8280       SemaRef.RequireNonAbstractType(
8281           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8282           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8283     D.setInvalidType();
8284
8285   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8286     // This is a C++ constructor declaration.
8287     assert(DC->isRecord() &&
8288            "Constructors can only be declared in a member context");
8289
8290     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8291     return CXXConstructorDecl::Create(
8292         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8293         TInfo, ExplicitSpecifier, isInline,
8294         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8295         TrailingRequiresClause);
8296
8297   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8298     // This is a C++ destructor declaration.
8299     if (DC->isRecord()) {
8300       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8301       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8302       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8303           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8304           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8305           TrailingRequiresClause);
8306
8307       // If the destructor needs an implicit exception specification, set it
8308       // now. FIXME: It'd be nice to be able to create the right type to start
8309       // with, but the type needs to reference the destructor declaration.
8310       if (SemaRef.getLangOpts().CPlusPlus11)
8311         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8312
8313       IsVirtualOkay = true;
8314       return NewDD;
8315
8316     } else {
8317       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8318       D.setInvalidType();
8319
8320       // Create a FunctionDecl to satisfy the function definition parsing
8321       // code path.
8322       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8323                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8324                                   isInline,
8325                                   /*hasPrototype=*/true, ConstexprKind,
8326                                   TrailingRequiresClause);
8327     }
8328
8329   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8330     if (!DC->isRecord()) {
8331       SemaRef.Diag(D.getIdentifierLoc(),
8332            diag::err_conv_function_not_member);
8333       return nullptr;
8334     }
8335
8336     SemaRef.CheckConversionDeclarator(D, R, SC);
8337     if (D.isInvalidType())
8338       return nullptr;
8339
8340     IsVirtualOkay = true;
8341     return CXXConversionDecl::Create(
8342         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8343         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8344         TrailingRequiresClause);
8345
8346   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8347     if (TrailingRequiresClause)
8348       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8349                    diag::err_trailing_requires_clause_on_deduction_guide)
8350           << TrailingRequiresClause->getSourceRange();
8351     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8352
8353     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8354                                          ExplicitSpecifier, NameInfo, R, TInfo,
8355                                          D.getEndLoc());
8356   } else if (DC->isRecord()) {
8357     // If the name of the function is the same as the name of the record,
8358     // then this must be an invalid constructor that has a return type.
8359     // (The parser checks for a return type and makes the declarator a
8360     // constructor if it has no return type).
8361     if (Name.getAsIdentifierInfo() &&
8362         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8363       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8364         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8365         << SourceRange(D.getIdentifierLoc());
8366       return nullptr;
8367     }
8368
8369     // This is a C++ method declaration.
8370     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8371         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8372         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8373         TrailingRequiresClause);
8374     IsVirtualOkay = !Ret->isStatic();
8375     return Ret;
8376   } else {
8377     bool isFriend =
8378         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8379     if (!isFriend && SemaRef.CurContext->isRecord())
8380       return nullptr;
8381
8382     // Determine whether the function was written with a
8383     // prototype. This true when:
8384     //   - we're in C++ (where every function has a prototype),
8385     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8386                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8387                                 ConstexprKind, TrailingRequiresClause);
8388   }
8389 }
8390
8391 enum OpenCLParamType {
8392   ValidKernelParam,
8393   PtrPtrKernelParam,
8394   PtrKernelParam,
8395   InvalidAddrSpacePtrKernelParam,
8396   InvalidKernelParam,
8397   RecordKernelParam
8398 };
8399
8400 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8401   // Size dependent types are just typedefs to normal integer types
8402   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8403   // integers other than by their names.
8404   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8405
8406   // Remove typedefs one by one until we reach a typedef
8407   // for a size dependent type.
8408   QualType DesugaredTy = Ty;
8409   do {
8410     ArrayRef<StringRef> Names(SizeTypeNames);
8411     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8412     if (Names.end() != Match)
8413       return true;
8414
8415     Ty = DesugaredTy;
8416     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8417   } while (DesugaredTy != Ty);
8418
8419   return false;
8420 }
8421
8422 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8423   if (PT->isPointerType()) {
8424     QualType PointeeType = PT->getPointeeType();
8425     if (PointeeType->isPointerType())
8426       return PtrPtrKernelParam;
8427     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8428         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8429         PointeeType.getAddressSpace() == LangAS::Default)
8430       return InvalidAddrSpacePtrKernelParam;
8431     return PtrKernelParam;
8432   }
8433
8434   // OpenCL v1.2 s6.9.k:
8435   // Arguments to kernel functions in a program cannot be declared with the
8436   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8437   // uintptr_t or a struct and/or union that contain fields declared to be one
8438   // of these built-in scalar types.
8439   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8440     return InvalidKernelParam;
8441
8442   if (PT->isImageType())
8443     return PtrKernelParam;
8444
8445   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8446     return InvalidKernelParam;
8447
8448   // OpenCL extension spec v1.2 s9.5:
8449   // This extension adds support for half scalar and vector types as built-in
8450   // types that can be used for arithmetic operations, conversions etc.
8451   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8452     return InvalidKernelParam;
8453
8454   if (PT->isRecordType())
8455     return RecordKernelParam;
8456
8457   // Look into an array argument to check if it has a forbidden type.
8458   if (PT->isArrayType()) {
8459     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8460     // Call ourself to check an underlying type of an array. Since the
8461     // getPointeeOrArrayElementType returns an innermost type which is not an
8462     // array, this recursive call only happens once.
8463     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8464   }
8465
8466   return ValidKernelParam;
8467 }
8468
8469 static void checkIsValidOpenCLKernelParameter(
8470   Sema &S,
8471   Declarator &D,
8472   ParmVarDecl *Param,
8473   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8474   QualType PT = Param->getType();
8475
8476   // Cache the valid types we encounter to avoid rechecking structs that are
8477   // used again
8478   if (ValidTypes.count(PT.getTypePtr()))
8479     return;
8480
8481   switch (getOpenCLKernelParameterType(S, PT)) {
8482   case PtrPtrKernelParam:
8483     // OpenCL v1.2 s6.9.a:
8484     // A kernel function argument cannot be declared as a
8485     // pointer to a pointer type.
8486     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8487     D.setInvalidType();
8488     return;
8489
8490   case InvalidAddrSpacePtrKernelParam:
8491     // OpenCL v1.0 s6.5:
8492     // __kernel function arguments declared to be a pointer of a type can point
8493     // to one of the following address spaces only : __global, __local or
8494     // __constant.
8495     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8496     D.setInvalidType();
8497     return;
8498
8499     // OpenCL v1.2 s6.9.k:
8500     // Arguments to kernel functions in a program cannot be declared with the
8501     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8502     // uintptr_t or a struct and/or union that contain fields declared to be
8503     // one of these built-in scalar types.
8504
8505   case InvalidKernelParam:
8506     // OpenCL v1.2 s6.8 n:
8507     // A kernel function argument cannot be declared
8508     // of event_t type.
8509     // Do not diagnose half type since it is diagnosed as invalid argument
8510     // type for any function elsewhere.
8511     if (!PT->isHalfType()) {
8512       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8513
8514       // Explain what typedefs are involved.
8515       const TypedefType *Typedef = nullptr;
8516       while ((Typedef = PT->getAs<TypedefType>())) {
8517         SourceLocation Loc = Typedef->getDecl()->getLocation();
8518         // SourceLocation may be invalid for a built-in type.
8519         if (Loc.isValid())
8520           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8521         PT = Typedef->desugar();
8522       }
8523     }
8524
8525     D.setInvalidType();
8526     return;
8527
8528   case PtrKernelParam:
8529   case ValidKernelParam:
8530     ValidTypes.insert(PT.getTypePtr());
8531     return;
8532
8533   case RecordKernelParam:
8534     break;
8535   }
8536
8537   // Track nested structs we will inspect
8538   SmallVector<const Decl *, 4> VisitStack;
8539
8540   // Track where we are in the nested structs. Items will migrate from
8541   // VisitStack to HistoryStack as we do the DFS for bad field.
8542   SmallVector<const FieldDecl *, 4> HistoryStack;
8543   HistoryStack.push_back(nullptr);
8544
8545   // At this point we already handled everything except of a RecordType or
8546   // an ArrayType of a RecordType.
8547   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8548   const RecordType *RecTy =
8549       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8550   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8551
8552   VisitStack.push_back(RecTy->getDecl());
8553   assert(VisitStack.back() && "First decl null?");
8554
8555   do {
8556     const Decl *Next = VisitStack.pop_back_val();
8557     if (!Next) {
8558       assert(!HistoryStack.empty());
8559       // Found a marker, we have gone up a level
8560       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8561         ValidTypes.insert(Hist->getType().getTypePtr());
8562
8563       continue;
8564     }
8565
8566     // Adds everything except the original parameter declaration (which is not a
8567     // field itself) to the history stack.
8568     const RecordDecl *RD;
8569     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8570       HistoryStack.push_back(Field);
8571
8572       QualType FieldTy = Field->getType();
8573       // Other field types (known to be valid or invalid) are handled while we
8574       // walk around RecordDecl::fields().
8575       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8576              "Unexpected type.");
8577       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8578
8579       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8580     } else {
8581       RD = cast<RecordDecl>(Next);
8582     }
8583
8584     // Add a null marker so we know when we've gone back up a level
8585     VisitStack.push_back(nullptr);
8586
8587     for (const auto *FD : RD->fields()) {
8588       QualType QT = FD->getType();
8589
8590       if (ValidTypes.count(QT.getTypePtr()))
8591         continue;
8592
8593       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8594       if (ParamType == ValidKernelParam)
8595         continue;
8596
8597       if (ParamType == RecordKernelParam) {
8598         VisitStack.push_back(FD);
8599         continue;
8600       }
8601
8602       // OpenCL v1.2 s6.9.p:
8603       // Arguments to kernel functions that are declared to be a struct or union
8604       // do not allow OpenCL objects to be passed as elements of the struct or
8605       // union.
8606       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8607           ParamType == InvalidAddrSpacePtrKernelParam) {
8608         S.Diag(Param->getLocation(),
8609                diag::err_record_with_pointers_kernel_param)
8610           << PT->isUnionType()
8611           << PT;
8612       } else {
8613         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8614       }
8615
8616       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8617           << OrigRecDecl->getDeclName();
8618
8619       // We have an error, now let's go back up through history and show where
8620       // the offending field came from
8621       for (ArrayRef<const FieldDecl *>::const_iterator
8622                I = HistoryStack.begin() + 1,
8623                E = HistoryStack.end();
8624            I != E; ++I) {
8625         const FieldDecl *OuterField = *I;
8626         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8627           << OuterField->getType();
8628       }
8629
8630       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8631         << QT->isPointerType()
8632         << QT;
8633       D.setInvalidType();
8634       return;
8635     }
8636   } while (!VisitStack.empty());
8637 }
8638
8639 /// Find the DeclContext in which a tag is implicitly declared if we see an
8640 /// elaborated type specifier in the specified context, and lookup finds
8641 /// nothing.
8642 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8643   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8644     DC = DC->getParent();
8645   return DC;
8646 }
8647
8648 /// Find the Scope in which a tag is implicitly declared if we see an
8649 /// elaborated type specifier in the specified context, and lookup finds
8650 /// nothing.
8651 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8652   while (S->isClassScope() ||
8653          (LangOpts.CPlusPlus &&
8654           S->isFunctionPrototypeScope()) ||
8655          ((S->getFlags() & Scope::DeclScope) == 0) ||
8656          (S->getEntity() && S->getEntity()->isTransparentContext()))
8657     S = S->getParent();
8658   return S;
8659 }
8660
8661 NamedDecl*
8662 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8663                               TypeSourceInfo *TInfo, LookupResult &Previous,
8664                               MultiTemplateParamsArg TemplateParamListsRef,
8665                               bool &AddToScope) {
8666   QualType R = TInfo->getType();
8667
8668   assert(R->isFunctionType());
8669   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8670   for (TemplateParameterList *TPL : TemplateParamListsRef)
8671     TemplateParamLists.push_back(TPL);
8672   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8673     if (!TemplateParamLists.empty() &&
8674         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8675       TemplateParamLists.back() = Invented;
8676     else
8677       TemplateParamLists.push_back(Invented);
8678   }
8679
8680   // TODO: consider using NameInfo for diagnostic.
8681   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8682   DeclarationName Name = NameInfo.getName();
8683   StorageClass SC = getFunctionStorageClass(*this, D);
8684
8685   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8686     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8687          diag::err_invalid_thread)
8688       << DeclSpec::getSpecifierName(TSCS);
8689
8690   if (D.isFirstDeclarationOfMember())
8691     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8692                            D.getIdentifierLoc());
8693
8694   bool isFriend = false;
8695   FunctionTemplateDecl *FunctionTemplate = nullptr;
8696   bool isMemberSpecialization = false;
8697   bool isFunctionTemplateSpecialization = false;
8698
8699   bool isDependentClassScopeExplicitSpecialization = false;
8700   bool HasExplicitTemplateArgs = false;
8701   TemplateArgumentListInfo TemplateArgs;
8702
8703   bool isVirtualOkay = false;
8704
8705   DeclContext *OriginalDC = DC;
8706   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8707
8708   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8709                                               isVirtualOkay);
8710   if (!NewFD) return nullptr;
8711
8712   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8713     NewFD->setTopLevelDeclInObjCContainer();
8714
8715   // Set the lexical context. If this is a function-scope declaration, or has a
8716   // C++ scope specifier, or is the object of a friend declaration, the lexical
8717   // context will be different from the semantic context.
8718   NewFD->setLexicalDeclContext(CurContext);
8719
8720   if (IsLocalExternDecl)
8721     NewFD->setLocalExternDecl();
8722
8723   if (getLangOpts().CPlusPlus) {
8724     bool isInline = D.getDeclSpec().isInlineSpecified();
8725     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8726     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8727     isFriend = D.getDeclSpec().isFriendSpecified();
8728     if (isFriend && !isInline && D.isFunctionDefinition()) {
8729       // C++ [class.friend]p5
8730       //   A function can be defined in a friend declaration of a
8731       //   class . . . . Such a function is implicitly inline.
8732       NewFD->setImplicitlyInline();
8733     }
8734
8735     // If this is a method defined in an __interface, and is not a constructor
8736     // or an overloaded operator, then set the pure flag (isVirtual will already
8737     // return true).
8738     if (const CXXRecordDecl *Parent =
8739           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8740       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8741         NewFD->setPure(true);
8742
8743       // C++ [class.union]p2
8744       //   A union can have member functions, but not virtual functions.
8745       if (isVirtual && Parent->isUnion())
8746         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8747     }
8748
8749     SetNestedNameSpecifier(*this, NewFD, D);
8750     isMemberSpecialization = false;
8751     isFunctionTemplateSpecialization = false;
8752     if (D.isInvalidType())
8753       NewFD->setInvalidDecl();
8754
8755     // Match up the template parameter lists with the scope specifier, then
8756     // determine whether we have a template or a template specialization.
8757     bool Invalid = false;
8758     TemplateParameterList *TemplateParams =
8759         MatchTemplateParametersToScopeSpecifier(
8760             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8761             D.getCXXScopeSpec(),
8762             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8763                 ? D.getName().TemplateId
8764                 : nullptr,
8765             TemplateParamLists, isFriend, isMemberSpecialization,
8766             Invalid);
8767     if (TemplateParams) {
8768       if (TemplateParams->size() > 0) {
8769         // This is a function template
8770
8771         // Check that we can declare a template here.
8772         if (CheckTemplateDeclScope(S, TemplateParams))
8773           NewFD->setInvalidDecl();
8774
8775         // A destructor cannot be a template.
8776         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8777           Diag(NewFD->getLocation(), diag::err_destructor_template);
8778           NewFD->setInvalidDecl();
8779         }
8780
8781         // If we're adding a template to a dependent context, we may need to
8782         // rebuilding some of the types used within the template parameter list,
8783         // now that we know what the current instantiation is.
8784         if (DC->isDependentContext()) {
8785           ContextRAII SavedContext(*this, DC);
8786           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8787             Invalid = true;
8788         }
8789
8790         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8791                                                         NewFD->getLocation(),
8792                                                         Name, TemplateParams,
8793                                                         NewFD);
8794         FunctionTemplate->setLexicalDeclContext(CurContext);
8795         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8796
8797         // For source fidelity, store the other template param lists.
8798         if (TemplateParamLists.size() > 1) {
8799           NewFD->setTemplateParameterListsInfo(Context,
8800               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8801                   .drop_back(1));
8802         }
8803       } else {
8804         // This is a function template specialization.
8805         isFunctionTemplateSpecialization = true;
8806         // For source fidelity, store all the template param lists.
8807         if (TemplateParamLists.size() > 0)
8808           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8809
8810         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8811         if (isFriend) {
8812           // We want to remove the "template<>", found here.
8813           SourceRange RemoveRange = TemplateParams->getSourceRange();
8814
8815           // If we remove the template<> and the name is not a
8816           // template-id, we're actually silently creating a problem:
8817           // the friend declaration will refer to an untemplated decl,
8818           // and clearly the user wants a template specialization.  So
8819           // we need to insert '<>' after the name.
8820           SourceLocation InsertLoc;
8821           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8822             InsertLoc = D.getName().getSourceRange().getEnd();
8823             InsertLoc = getLocForEndOfToken(InsertLoc);
8824           }
8825
8826           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8827             << Name << RemoveRange
8828             << FixItHint::CreateRemoval(RemoveRange)
8829             << FixItHint::CreateInsertion(InsertLoc, "<>");
8830         }
8831       }
8832     } else {
8833       // All template param lists were matched against the scope specifier:
8834       // this is NOT (an explicit specialization of) a template.
8835       if (TemplateParamLists.size() > 0)
8836         // For source fidelity, store all the template param lists.
8837         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8838     }
8839
8840     if (Invalid) {
8841       NewFD->setInvalidDecl();
8842       if (FunctionTemplate)
8843         FunctionTemplate->setInvalidDecl();
8844     }
8845
8846     // C++ [dcl.fct.spec]p5:
8847     //   The virtual specifier shall only be used in declarations of
8848     //   nonstatic class member functions that appear within a
8849     //   member-specification of a class declaration; see 10.3.
8850     //
8851     if (isVirtual && !NewFD->isInvalidDecl()) {
8852       if (!isVirtualOkay) {
8853         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8854              diag::err_virtual_non_function);
8855       } else if (!CurContext->isRecord()) {
8856         // 'virtual' was specified outside of the class.
8857         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8858              diag::err_virtual_out_of_class)
8859           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8860       } else if (NewFD->getDescribedFunctionTemplate()) {
8861         // C++ [temp.mem]p3:
8862         //  A member function template shall not be virtual.
8863         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8864              diag::err_virtual_member_function_template)
8865           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8866       } else {
8867         // Okay: Add virtual to the method.
8868         NewFD->setVirtualAsWritten(true);
8869       }
8870
8871       if (getLangOpts().CPlusPlus14 &&
8872           NewFD->getReturnType()->isUndeducedType())
8873         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8874     }
8875
8876     if (getLangOpts().CPlusPlus14 &&
8877         (NewFD->isDependentContext() ||
8878          (isFriend && CurContext->isDependentContext())) &&
8879         NewFD->getReturnType()->isUndeducedType()) {
8880       // If the function template is referenced directly (for instance, as a
8881       // member of the current instantiation), pretend it has a dependent type.
8882       // This is not really justified by the standard, but is the only sane
8883       // thing to do.
8884       // FIXME: For a friend function, we have not marked the function as being
8885       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8886       const FunctionProtoType *FPT =
8887           NewFD->getType()->castAs<FunctionProtoType>();
8888       QualType Result =
8889           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8890       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8891                                              FPT->getExtProtoInfo()));
8892     }
8893
8894     // C++ [dcl.fct.spec]p3:
8895     //  The inline specifier shall not appear on a block scope function
8896     //  declaration.
8897     if (isInline && !NewFD->isInvalidDecl()) {
8898       if (CurContext->isFunctionOrMethod()) {
8899         // 'inline' is not allowed on block scope function declaration.
8900         Diag(D.getDeclSpec().getInlineSpecLoc(),
8901              diag::err_inline_declaration_block_scope) << Name
8902           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8903       }
8904     }
8905
8906     // C++ [dcl.fct.spec]p6:
8907     //  The explicit specifier shall be used only in the declaration of a
8908     //  constructor or conversion function within its class definition;
8909     //  see 12.3.1 and 12.3.2.
8910     if (hasExplicit && !NewFD->isInvalidDecl() &&
8911         !isa<CXXDeductionGuideDecl>(NewFD)) {
8912       if (!CurContext->isRecord()) {
8913         // 'explicit' was specified outside of the class.
8914         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8915              diag::err_explicit_out_of_class)
8916             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8917       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8918                  !isa<CXXConversionDecl>(NewFD)) {
8919         // 'explicit' was specified on a function that wasn't a constructor
8920         // or conversion function.
8921         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8922              diag::err_explicit_non_ctor_or_conv_function)
8923             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8924       }
8925     }
8926
8927     if (ConstexprSpecKind ConstexprKind =
8928             D.getDeclSpec().getConstexprSpecifier()) {
8929       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8930       // are implicitly inline.
8931       NewFD->setImplicitlyInline();
8932
8933       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8934       // be either constructors or to return a literal type. Therefore,
8935       // destructors cannot be declared constexpr.
8936       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8937         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8938             << ConstexprKind;
8939       }
8940     }
8941
8942     // If __module_private__ was specified, mark the function accordingly.
8943     if (D.getDeclSpec().isModulePrivateSpecified()) {
8944       if (isFunctionTemplateSpecialization) {
8945         SourceLocation ModulePrivateLoc
8946           = D.getDeclSpec().getModulePrivateSpecLoc();
8947         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8948           << 0
8949           << FixItHint::CreateRemoval(ModulePrivateLoc);
8950       } else {
8951         NewFD->setModulePrivate();
8952         if (FunctionTemplate)
8953           FunctionTemplate->setModulePrivate();
8954       }
8955     }
8956
8957     if (isFriend) {
8958       if (FunctionTemplate) {
8959         FunctionTemplate->setObjectOfFriendDecl();
8960         FunctionTemplate->setAccess(AS_public);
8961       }
8962       NewFD->setObjectOfFriendDecl();
8963       NewFD->setAccess(AS_public);
8964     }
8965
8966     // If a function is defined as defaulted or deleted, mark it as such now.
8967     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8968     // definition kind to FDK_Definition.
8969     switch (D.getFunctionDefinitionKind()) {
8970       case FDK_Declaration:
8971       case FDK_Definition:
8972         break;
8973
8974       case FDK_Defaulted:
8975         NewFD->setDefaulted();
8976         break;
8977
8978       case FDK_Deleted:
8979         NewFD->setDeletedAsWritten();
8980         break;
8981     }
8982
8983     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8984         D.isFunctionDefinition()) {
8985       // C++ [class.mfct]p2:
8986       //   A member function may be defined (8.4) in its class definition, in
8987       //   which case it is an inline member function (7.1.2)
8988       NewFD->setImplicitlyInline();
8989     }
8990
8991     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8992         !CurContext->isRecord()) {
8993       // C++ [class.static]p1:
8994       //   A data or function member of a class may be declared static
8995       //   in a class definition, in which case it is a static member of
8996       //   the class.
8997
8998       // Complain about the 'static' specifier if it's on an out-of-line
8999       // member function definition.
9000
9001       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9002       // member function template declaration and class member template
9003       // declaration (MSVC versions before 2015), warn about this.
9004       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9005            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9006              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9007            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9008            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9009         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9010     }
9011
9012     // C++11 [except.spec]p15:
9013     //   A deallocation function with no exception-specification is treated
9014     //   as if it were specified with noexcept(true).
9015     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9016     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9017          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9018         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9019       NewFD->setType(Context.getFunctionType(
9020           FPT->getReturnType(), FPT->getParamTypes(),
9021           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9022   }
9023
9024   // Filter out previous declarations that don't match the scope.
9025   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9026                        D.getCXXScopeSpec().isNotEmpty() ||
9027                        isMemberSpecialization ||
9028                        isFunctionTemplateSpecialization);
9029
9030   // Handle GNU asm-label extension (encoded as an attribute).
9031   if (Expr *E = (Expr*) D.getAsmLabel()) {
9032     // The parser guarantees this is a string.
9033     StringLiteral *SE = cast<StringLiteral>(E);
9034     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9035                                         /*IsLiteralLabel=*/true,
9036                                         SE->getStrTokenLoc(0)));
9037   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9038     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9039       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9040     if (I != ExtnameUndeclaredIdentifiers.end()) {
9041       if (isDeclExternC(NewFD)) {
9042         NewFD->addAttr(I->second);
9043         ExtnameUndeclaredIdentifiers.erase(I);
9044       } else
9045         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9046             << /*Variable*/0 << NewFD;
9047     }
9048   }
9049
9050   // Copy the parameter declarations from the declarator D to the function
9051   // declaration NewFD, if they are available.  First scavenge them into Params.
9052   SmallVector<ParmVarDecl*, 16> Params;
9053   unsigned FTIIdx;
9054   if (D.isFunctionDeclarator(FTIIdx)) {
9055     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9056
9057     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9058     // function that takes no arguments, not a function that takes a
9059     // single void argument.
9060     // We let through "const void" here because Sema::GetTypeForDeclarator
9061     // already checks for that case.
9062     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9063       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9064         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9065         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9066         Param->setDeclContext(NewFD);
9067         Params.push_back(Param);
9068
9069         if (Param->isInvalidDecl())
9070           NewFD->setInvalidDecl();
9071       }
9072     }
9073
9074     if (!getLangOpts().CPlusPlus) {
9075       // In C, find all the tag declarations from the prototype and move them
9076       // into the function DeclContext. Remove them from the surrounding tag
9077       // injection context of the function, which is typically but not always
9078       // the TU.
9079       DeclContext *PrototypeTagContext =
9080           getTagInjectionContext(NewFD->getLexicalDeclContext());
9081       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9082         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9083
9084         // We don't want to reparent enumerators. Look at their parent enum
9085         // instead.
9086         if (!TD) {
9087           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9088             TD = cast<EnumDecl>(ECD->getDeclContext());
9089         }
9090         if (!TD)
9091           continue;
9092         DeclContext *TagDC = TD->getLexicalDeclContext();
9093         if (!TagDC->containsDecl(TD))
9094           continue;
9095         TagDC->removeDecl(TD);
9096         TD->setDeclContext(NewFD);
9097         NewFD->addDecl(TD);
9098
9099         // Preserve the lexical DeclContext if it is not the surrounding tag
9100         // injection context of the FD. In this example, the semantic context of
9101         // E will be f and the lexical context will be S, while both the
9102         // semantic and lexical contexts of S will be f:
9103         //   void f(struct S { enum E { a } f; } s);
9104         if (TagDC != PrototypeTagContext)
9105           TD->setLexicalDeclContext(TagDC);
9106       }
9107     }
9108   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9109     // When we're declaring a function with a typedef, typeof, etc as in the
9110     // following example, we'll need to synthesize (unnamed)
9111     // parameters for use in the declaration.
9112     //
9113     // @code
9114     // typedef void fn(int);
9115     // fn f;
9116     // @endcode
9117
9118     // Synthesize a parameter for each argument type.
9119     for (const auto &AI : FT->param_types()) {
9120       ParmVarDecl *Param =
9121           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9122       Param->setScopeInfo(0, Params.size());
9123       Params.push_back(Param);
9124     }
9125   } else {
9126     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9127            "Should not need args for typedef of non-prototype fn");
9128   }
9129
9130   // Finally, we know we have the right number of parameters, install them.
9131   NewFD->setParams(Params);
9132
9133   if (D.getDeclSpec().isNoreturnSpecified())
9134     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9135                                            D.getDeclSpec().getNoreturnSpecLoc(),
9136                                            AttributeCommonInfo::AS_Keyword));
9137
9138   // Functions returning a variably modified type violate C99 6.7.5.2p2
9139   // because all functions have linkage.
9140   if (!NewFD->isInvalidDecl() &&
9141       NewFD->getReturnType()->isVariablyModifiedType()) {
9142     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9143     NewFD->setInvalidDecl();
9144   }
9145
9146   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9147   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9148       !NewFD->hasAttr<SectionAttr>())
9149     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9150         Context, PragmaClangTextSection.SectionName,
9151         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9152
9153   // Apply an implicit SectionAttr if #pragma code_seg is active.
9154   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9155       !NewFD->hasAttr<SectionAttr>()) {
9156     NewFD->addAttr(SectionAttr::CreateImplicit(
9157         Context, CodeSegStack.CurrentValue->getString(),
9158         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9159         SectionAttr::Declspec_allocate));
9160     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9161                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9162                          ASTContext::PSF_Read,
9163                      NewFD))
9164       NewFD->dropAttr<SectionAttr>();
9165   }
9166
9167   // Apply an implicit CodeSegAttr from class declspec or
9168   // apply an implicit SectionAttr from #pragma code_seg if active.
9169   if (!NewFD->hasAttr<CodeSegAttr>()) {
9170     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9171                                                                  D.isFunctionDefinition())) {
9172       NewFD->addAttr(SAttr);
9173     }
9174   }
9175
9176   // Handle attributes.
9177   ProcessDeclAttributes(S, NewFD, D);
9178
9179   if (getLangOpts().OpenCL) {
9180     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9181     // type declaration will generate a compilation error.
9182     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9183     if (AddressSpace != LangAS::Default) {
9184       Diag(NewFD->getLocation(),
9185            diag::err_opencl_return_value_with_address_space);
9186       NewFD->setInvalidDecl();
9187     }
9188   }
9189
9190   if (!getLangOpts().CPlusPlus) {
9191     // Perform semantic checking on the function declaration.
9192     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9193       CheckMain(NewFD, D.getDeclSpec());
9194
9195     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9196       CheckMSVCRTEntryPoint(NewFD);
9197
9198     if (!NewFD->isInvalidDecl())
9199       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9200                                                   isMemberSpecialization));
9201     else if (!Previous.empty())
9202       // Recover gracefully from an invalid redeclaration.
9203       D.setRedeclaration(true);
9204     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9205             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9206            "previous declaration set still overloaded");
9207
9208     // Diagnose no-prototype function declarations with calling conventions that
9209     // don't support variadic calls. Only do this in C and do it after merging
9210     // possibly prototyped redeclarations.
9211     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9212     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9213       CallingConv CC = FT->getExtInfo().getCC();
9214       if (!supportsVariadicCall(CC)) {
9215         // Windows system headers sometimes accidentally use stdcall without
9216         // (void) parameters, so we relax this to a warning.
9217         int DiagID =
9218             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9219         Diag(NewFD->getLocation(), DiagID)
9220             << FunctionType::getNameForCallConv(CC);
9221       }
9222     }
9223
9224    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9225        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9226      checkNonTrivialCUnion(NewFD->getReturnType(),
9227                            NewFD->getReturnTypeSourceRange().getBegin(),
9228                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9229   } else {
9230     // C++11 [replacement.functions]p3:
9231     //  The program's definitions shall not be specified as inline.
9232     //
9233     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9234     //
9235     // Suppress the diagnostic if the function is __attribute__((used)), since
9236     // that forces an external definition to be emitted.
9237     if (D.getDeclSpec().isInlineSpecified() &&
9238         NewFD->isReplaceableGlobalAllocationFunction() &&
9239         !NewFD->hasAttr<UsedAttr>())
9240       Diag(D.getDeclSpec().getInlineSpecLoc(),
9241            diag::ext_operator_new_delete_declared_inline)
9242         << NewFD->getDeclName();
9243
9244     // If the declarator is a template-id, translate the parser's template
9245     // argument list into our AST format.
9246     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9247       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9248       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9249       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9250       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9251                                          TemplateId->NumArgs);
9252       translateTemplateArguments(TemplateArgsPtr,
9253                                  TemplateArgs);
9254
9255       HasExplicitTemplateArgs = true;
9256
9257       if (NewFD->isInvalidDecl()) {
9258         HasExplicitTemplateArgs = false;
9259       } else if (FunctionTemplate) {
9260         // Function template with explicit template arguments.
9261         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9262           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9263
9264         HasExplicitTemplateArgs = false;
9265       } else {
9266         assert((isFunctionTemplateSpecialization ||
9267                 D.getDeclSpec().isFriendSpecified()) &&
9268                "should have a 'template<>' for this decl");
9269         // "friend void foo<>(int);" is an implicit specialization decl.
9270         isFunctionTemplateSpecialization = true;
9271       }
9272     } else if (isFriend && isFunctionTemplateSpecialization) {
9273       // This combination is only possible in a recovery case;  the user
9274       // wrote something like:
9275       //   template <> friend void foo(int);
9276       // which we're recovering from as if the user had written:
9277       //   friend void foo<>(int);
9278       // Go ahead and fake up a template id.
9279       HasExplicitTemplateArgs = true;
9280       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9281       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9282     }
9283
9284     // We do not add HD attributes to specializations here because
9285     // they may have different constexpr-ness compared to their
9286     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9287     // may end up with different effective targets. Instead, a
9288     // specialization inherits its target attributes from its template
9289     // in the CheckFunctionTemplateSpecialization() call below.
9290     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9291       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9292
9293     // If it's a friend (and only if it's a friend), it's possible
9294     // that either the specialized function type or the specialized
9295     // template is dependent, and therefore matching will fail.  In
9296     // this case, don't check the specialization yet.
9297     bool InstantiationDependent = false;
9298     if (isFunctionTemplateSpecialization && isFriend &&
9299         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9300          TemplateSpecializationType::anyDependentTemplateArguments(
9301             TemplateArgs,
9302             InstantiationDependent))) {
9303       assert(HasExplicitTemplateArgs &&
9304              "friend function specialization without template args");
9305       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9306                                                        Previous))
9307         NewFD->setInvalidDecl();
9308     } else if (isFunctionTemplateSpecialization) {
9309       if (CurContext->isDependentContext() && CurContext->isRecord()
9310           && !isFriend) {
9311         isDependentClassScopeExplicitSpecialization = true;
9312       } else if (!NewFD->isInvalidDecl() &&
9313                  CheckFunctionTemplateSpecialization(
9314                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9315                      Previous))
9316         NewFD->setInvalidDecl();
9317
9318       // C++ [dcl.stc]p1:
9319       //   A storage-class-specifier shall not be specified in an explicit
9320       //   specialization (14.7.3)
9321       FunctionTemplateSpecializationInfo *Info =
9322           NewFD->getTemplateSpecializationInfo();
9323       if (Info && SC != SC_None) {
9324         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9325           Diag(NewFD->getLocation(),
9326                diag::err_explicit_specialization_inconsistent_storage_class)
9327             << SC
9328             << FixItHint::CreateRemoval(
9329                                       D.getDeclSpec().getStorageClassSpecLoc());
9330
9331         else
9332           Diag(NewFD->getLocation(),
9333                diag::ext_explicit_specialization_storage_class)
9334             << FixItHint::CreateRemoval(
9335                                       D.getDeclSpec().getStorageClassSpecLoc());
9336       }
9337     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9338       if (CheckMemberSpecialization(NewFD, Previous))
9339           NewFD->setInvalidDecl();
9340     }
9341
9342     // Perform semantic checking on the function declaration.
9343     if (!isDependentClassScopeExplicitSpecialization) {
9344       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9345         CheckMain(NewFD, D.getDeclSpec());
9346
9347       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9348         CheckMSVCRTEntryPoint(NewFD);
9349
9350       if (!NewFD->isInvalidDecl())
9351         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9352                                                     isMemberSpecialization));
9353       else if (!Previous.empty())
9354         // Recover gracefully from an invalid redeclaration.
9355         D.setRedeclaration(true);
9356     }
9357
9358     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9359             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9360            "previous declaration set still overloaded");
9361
9362     NamedDecl *PrincipalDecl = (FunctionTemplate
9363                                 ? cast<NamedDecl>(FunctionTemplate)
9364                                 : NewFD);
9365
9366     if (isFriend && NewFD->getPreviousDecl()) {
9367       AccessSpecifier Access = AS_public;
9368       if (!NewFD->isInvalidDecl())
9369         Access = NewFD->getPreviousDecl()->getAccess();
9370
9371       NewFD->setAccess(Access);
9372       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9373     }
9374
9375     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9376         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9377       PrincipalDecl->setNonMemberOperator();
9378
9379     // If we have a function template, check the template parameter
9380     // list. This will check and merge default template arguments.
9381     if (FunctionTemplate) {
9382       FunctionTemplateDecl *PrevTemplate =
9383                                      FunctionTemplate->getPreviousDecl();
9384       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9385                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9386                                     : nullptr,
9387                             D.getDeclSpec().isFriendSpecified()
9388                               ? (D.isFunctionDefinition()
9389                                    ? TPC_FriendFunctionTemplateDefinition
9390                                    : TPC_FriendFunctionTemplate)
9391                               : (D.getCXXScopeSpec().isSet() &&
9392                                  DC && DC->isRecord() &&
9393                                  DC->isDependentContext())
9394                                   ? TPC_ClassTemplateMember
9395                                   : TPC_FunctionTemplate);
9396     }
9397
9398     if (NewFD->isInvalidDecl()) {
9399       // Ignore all the rest of this.
9400     } else if (!D.isRedeclaration()) {
9401       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9402                                        AddToScope };
9403       // Fake up an access specifier if it's supposed to be a class member.
9404       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9405         NewFD->setAccess(AS_public);
9406
9407       // Qualified decls generally require a previous declaration.
9408       if (D.getCXXScopeSpec().isSet()) {
9409         // ...with the major exception of templated-scope or
9410         // dependent-scope friend declarations.
9411
9412         // TODO: we currently also suppress this check in dependent
9413         // contexts because (1) the parameter depth will be off when
9414         // matching friend templates and (2) we might actually be
9415         // selecting a friend based on a dependent factor.  But there
9416         // are situations where these conditions don't apply and we
9417         // can actually do this check immediately.
9418         //
9419         // Unless the scope is dependent, it's always an error if qualified
9420         // redeclaration lookup found nothing at all. Diagnose that now;
9421         // nothing will diagnose that error later.
9422         if (isFriend &&
9423             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9424              (!Previous.empty() && CurContext->isDependentContext()))) {
9425           // ignore these
9426         } else {
9427           // The user tried to provide an out-of-line definition for a
9428           // function that is a member of a class or namespace, but there
9429           // was no such member function declared (C++ [class.mfct]p2,
9430           // C++ [namespace.memdef]p2). For example:
9431           //
9432           // class X {
9433           //   void f() const;
9434           // };
9435           //
9436           // void X::f() { } // ill-formed
9437           //
9438           // Complain about this problem, and attempt to suggest close
9439           // matches (e.g., those that differ only in cv-qualifiers and
9440           // whether the parameter types are references).
9441
9442           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9443                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9444             AddToScope = ExtraArgs.AddToScope;
9445             return Result;
9446           }
9447         }
9448
9449         // Unqualified local friend declarations are required to resolve
9450         // to something.
9451       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9452         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9453                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9454           AddToScope = ExtraArgs.AddToScope;
9455           return Result;
9456         }
9457       }
9458     } else if (!D.isFunctionDefinition() &&
9459                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9460                !isFriend && !isFunctionTemplateSpecialization &&
9461                !isMemberSpecialization) {
9462       // An out-of-line member function declaration must also be a
9463       // definition (C++ [class.mfct]p2).
9464       // Note that this is not the case for explicit specializations of
9465       // function templates or member functions of class templates, per
9466       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9467       // extension for compatibility with old SWIG code which likes to
9468       // generate them.
9469       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9470         << D.getCXXScopeSpec().getRange();
9471     }
9472   }
9473
9474   ProcessPragmaWeak(S, NewFD);
9475   checkAttributesAfterMerging(*this, *NewFD);
9476
9477   AddKnownFunctionAttributes(NewFD);
9478
9479   if (NewFD->hasAttr<OverloadableAttr>() &&
9480       !NewFD->getType()->getAs<FunctionProtoType>()) {
9481     Diag(NewFD->getLocation(),
9482          diag::err_attribute_overloadable_no_prototype)
9483       << NewFD;
9484
9485     // Turn this into a variadic function with no parameters.
9486     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9487     FunctionProtoType::ExtProtoInfo EPI(
9488         Context.getDefaultCallingConvention(true, false));
9489     EPI.Variadic = true;
9490     EPI.ExtInfo = FT->getExtInfo();
9491
9492     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9493     NewFD->setType(R);
9494   }
9495
9496   // If there's a #pragma GCC visibility in scope, and this isn't a class
9497   // member, set the visibility of this function.
9498   if (!DC->isRecord() && NewFD->isExternallyVisible())
9499     AddPushedVisibilityAttribute(NewFD);
9500
9501   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9502   // marking the function.
9503   AddCFAuditedAttribute(NewFD);
9504
9505   // If this is a function definition, check if we have to apply optnone due to
9506   // a pragma.
9507   if(D.isFunctionDefinition())
9508     AddRangeBasedOptnone(NewFD);
9509
9510   // If this is the first declaration of an extern C variable, update
9511   // the map of such variables.
9512   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9513       isIncompleteDeclExternC(*this, NewFD))
9514     RegisterLocallyScopedExternCDecl(NewFD, S);
9515
9516   // Set this FunctionDecl's range up to the right paren.
9517   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9518
9519   if (D.isRedeclaration() && !Previous.empty()) {
9520     NamedDecl *Prev = Previous.getRepresentativeDecl();
9521     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9522                                    isMemberSpecialization ||
9523                                        isFunctionTemplateSpecialization,
9524                                    D.isFunctionDefinition());
9525   }
9526
9527   if (getLangOpts().CUDA) {
9528     IdentifierInfo *II = NewFD->getIdentifier();
9529     if (II && II->isStr(getCudaConfigureFuncName()) &&
9530         !NewFD->isInvalidDecl() &&
9531         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9532       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9533         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9534             << getCudaConfigureFuncName();
9535       Context.setcudaConfigureCallDecl(NewFD);
9536     }
9537
9538     // Variadic functions, other than a *declaration* of printf, are not allowed
9539     // in device-side CUDA code, unless someone passed
9540     // -fcuda-allow-variadic-functions.
9541     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9542         (NewFD->hasAttr<CUDADeviceAttr>() ||
9543          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9544         !(II && II->isStr("printf") && NewFD->isExternC() &&
9545           !D.isFunctionDefinition())) {
9546       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9547     }
9548   }
9549
9550   MarkUnusedFileScopedDecl(NewFD);
9551
9552
9553
9554   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9555     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9556     if ((getLangOpts().OpenCLVersion >= 120)
9557         && (SC == SC_Static)) {
9558       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9559       D.setInvalidType();
9560     }
9561
9562     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9563     if (!NewFD->getReturnType()->isVoidType()) {
9564       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9565       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9566           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9567                                 : FixItHint());
9568       D.setInvalidType();
9569     }
9570
9571     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9572     for (auto Param : NewFD->parameters())
9573       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9574
9575     if (getLangOpts().OpenCLCPlusPlus) {
9576       if (DC->isRecord()) {
9577         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9578         D.setInvalidType();
9579       }
9580       if (FunctionTemplate) {
9581         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9582         D.setInvalidType();
9583       }
9584     }
9585   }
9586
9587   if (getLangOpts().CPlusPlus) {
9588     if (FunctionTemplate) {
9589       if (NewFD->isInvalidDecl())
9590         FunctionTemplate->setInvalidDecl();
9591       return FunctionTemplate;
9592     }
9593
9594     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9595       CompleteMemberSpecialization(NewFD, Previous);
9596   }
9597
9598   for (const ParmVarDecl *Param : NewFD->parameters()) {
9599     QualType PT = Param->getType();
9600
9601     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9602     // types.
9603     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9604       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9605         QualType ElemTy = PipeTy->getElementType();
9606           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9607             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9608             D.setInvalidType();
9609           }
9610       }
9611     }
9612   }
9613
9614   // Here we have an function template explicit specialization at class scope.
9615   // The actual specialization will be postponed to template instatiation
9616   // time via the ClassScopeFunctionSpecializationDecl node.
9617   if (isDependentClassScopeExplicitSpecialization) {
9618     ClassScopeFunctionSpecializationDecl *NewSpec =
9619                          ClassScopeFunctionSpecializationDecl::Create(
9620                                 Context, CurContext, NewFD->getLocation(),
9621                                 cast<CXXMethodDecl>(NewFD),
9622                                 HasExplicitTemplateArgs, TemplateArgs);
9623     CurContext->addDecl(NewSpec);
9624     AddToScope = false;
9625   }
9626
9627   // Diagnose availability attributes. Availability cannot be used on functions
9628   // that are run during load/unload.
9629   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9630     if (NewFD->hasAttr<ConstructorAttr>()) {
9631       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9632           << 1;
9633       NewFD->dropAttr<AvailabilityAttr>();
9634     }
9635     if (NewFD->hasAttr<DestructorAttr>()) {
9636       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9637           << 2;
9638       NewFD->dropAttr<AvailabilityAttr>();
9639     }
9640   }
9641
9642   // Diagnose no_builtin attribute on function declaration that are not a
9643   // definition.
9644   // FIXME: We should really be doing this in
9645   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9646   // the FunctionDecl and at this point of the code
9647   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9648   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9649   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9650     switch (D.getFunctionDefinitionKind()) {
9651     case FDK_Defaulted:
9652     case FDK_Deleted:
9653       Diag(NBA->getLocation(),
9654            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9655           << NBA->getSpelling();
9656       break;
9657     case FDK_Declaration:
9658       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9659           << NBA->getSpelling();
9660       break;
9661     case FDK_Definition:
9662       break;
9663     }
9664
9665   return NewFD;
9666 }
9667
9668 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9669 /// when __declspec(code_seg) "is applied to a class, all member functions of
9670 /// the class and nested classes -- this includes compiler-generated special
9671 /// member functions -- are put in the specified segment."
9672 /// The actual behavior is a little more complicated. The Microsoft compiler
9673 /// won't check outer classes if there is an active value from #pragma code_seg.
9674 /// The CodeSeg is always applied from the direct parent but only from outer
9675 /// classes when the #pragma code_seg stack is empty. See:
9676 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9677 /// available since MS has removed the page.
9678 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9679   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9680   if (!Method)
9681     return nullptr;
9682   const CXXRecordDecl *Parent = Method->getParent();
9683   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9684     Attr *NewAttr = SAttr->clone(S.getASTContext());
9685     NewAttr->setImplicit(true);
9686     return NewAttr;
9687   }
9688
9689   // The Microsoft compiler won't check outer classes for the CodeSeg
9690   // when the #pragma code_seg stack is active.
9691   if (S.CodeSegStack.CurrentValue)
9692    return nullptr;
9693
9694   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9695     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9696       Attr *NewAttr = SAttr->clone(S.getASTContext());
9697       NewAttr->setImplicit(true);
9698       return NewAttr;
9699     }
9700   }
9701   return nullptr;
9702 }
9703
9704 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9705 /// containing class. Otherwise it will return implicit SectionAttr if the
9706 /// function is a definition and there is an active value on CodeSegStack
9707 /// (from the current #pragma code-seg value).
9708 ///
9709 /// \param FD Function being declared.
9710 /// \param IsDefinition Whether it is a definition or just a declarartion.
9711 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9712 ///          nullptr if no attribute should be added.
9713 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9714                                                        bool IsDefinition) {
9715   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9716     return A;
9717   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9718       CodeSegStack.CurrentValue)
9719     return SectionAttr::CreateImplicit(
9720         getASTContext(), CodeSegStack.CurrentValue->getString(),
9721         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9722         SectionAttr::Declspec_allocate);
9723   return nullptr;
9724 }
9725
9726 /// Determines if we can perform a correct type check for \p D as a
9727 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9728 /// best-effort check.
9729 ///
9730 /// \param NewD The new declaration.
9731 /// \param OldD The old declaration.
9732 /// \param NewT The portion of the type of the new declaration to check.
9733 /// \param OldT The portion of the type of the old declaration to check.
9734 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9735                                           QualType NewT, QualType OldT) {
9736   if (!NewD->getLexicalDeclContext()->isDependentContext())
9737     return true;
9738
9739   // For dependently-typed local extern declarations and friends, we can't
9740   // perform a correct type check in general until instantiation:
9741   //
9742   //   int f();
9743   //   template<typename T> void g() { T f(); }
9744   //
9745   // (valid if g() is only instantiated with T = int).
9746   if (NewT->isDependentType() &&
9747       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9748     return false;
9749
9750   // Similarly, if the previous declaration was a dependent local extern
9751   // declaration, we don't really know its type yet.
9752   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9753     return false;
9754
9755   return true;
9756 }
9757
9758 /// Checks if the new declaration declared in dependent context must be
9759 /// put in the same redeclaration chain as the specified declaration.
9760 ///
9761 /// \param D Declaration that is checked.
9762 /// \param PrevDecl Previous declaration found with proper lookup method for the
9763 ///                 same declaration name.
9764 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9765 ///          belongs to.
9766 ///
9767 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9768   if (!D->getLexicalDeclContext()->isDependentContext())
9769     return true;
9770
9771   // Don't chain dependent friend function definitions until instantiation, to
9772   // permit cases like
9773   //
9774   //   void func();
9775   //   template<typename T> class C1 { friend void func() {} };
9776   //   template<typename T> class C2 { friend void func() {} };
9777   //
9778   // ... which is valid if only one of C1 and C2 is ever instantiated.
9779   //
9780   // FIXME: This need only apply to function definitions. For now, we proxy
9781   // this by checking for a file-scope function. We do not want this to apply
9782   // to friend declarations nominating member functions, because that gets in
9783   // the way of access checks.
9784   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9785     return false;
9786
9787   auto *VD = dyn_cast<ValueDecl>(D);
9788   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9789   return !VD || !PrevVD ||
9790          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9791                                         PrevVD->getType());
9792 }
9793
9794 /// Check the target attribute of the function for MultiVersion
9795 /// validity.
9796 ///
9797 /// Returns true if there was an error, false otherwise.
9798 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9799   const auto *TA = FD->getAttr<TargetAttr>();
9800   assert(TA && "MultiVersion Candidate requires a target attribute");
9801   ParsedTargetAttr ParseInfo = TA->parse();
9802   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9803   enum ErrType { Feature = 0, Architecture = 1 };
9804
9805   if (!ParseInfo.Architecture.empty() &&
9806       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9807     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9808         << Architecture << ParseInfo.Architecture;
9809     return true;
9810   }
9811
9812   for (const auto &Feat : ParseInfo.Features) {
9813     auto BareFeat = StringRef{Feat}.substr(1);
9814     if (Feat[0] == '-') {
9815       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9816           << Feature << ("no-" + BareFeat).str();
9817       return true;
9818     }
9819
9820     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9821         !TargetInfo.isValidFeatureName(BareFeat)) {
9822       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9823           << Feature << BareFeat;
9824       return true;
9825     }
9826   }
9827   return false;
9828 }
9829
9830 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9831                                          MultiVersionKind MVType) {
9832   for (const Attr *A : FD->attrs()) {
9833     switch (A->getKind()) {
9834     case attr::CPUDispatch:
9835     case attr::CPUSpecific:
9836       if (MVType != MultiVersionKind::CPUDispatch &&
9837           MVType != MultiVersionKind::CPUSpecific)
9838         return true;
9839       break;
9840     case attr::Target:
9841       if (MVType != MultiVersionKind::Target)
9842         return true;
9843       break;
9844     default:
9845       return true;
9846     }
9847   }
9848   return false;
9849 }
9850
9851 bool Sema::areMultiversionVariantFunctionsCompatible(
9852     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9853     const PartialDiagnostic &NoProtoDiagID,
9854     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9855     const PartialDiagnosticAt &NoSupportDiagIDAt,
9856     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9857     bool ConstexprSupported, bool CLinkageMayDiffer) {
9858   enum DoesntSupport {
9859     FuncTemplates = 0,
9860     VirtFuncs = 1,
9861     DeducedReturn = 2,
9862     Constructors = 3,
9863     Destructors = 4,
9864     DeletedFuncs = 5,
9865     DefaultedFuncs = 6,
9866     ConstexprFuncs = 7,
9867     ConstevalFuncs = 8,
9868   };
9869   enum Different {
9870     CallingConv = 0,
9871     ReturnType = 1,
9872     ConstexprSpec = 2,
9873     InlineSpec = 3,
9874     StorageClass = 4,
9875     Linkage = 5,
9876   };
9877
9878   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9879       !OldFD->getType()->getAs<FunctionProtoType>()) {
9880     Diag(OldFD->getLocation(), NoProtoDiagID);
9881     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9882     return true;
9883   }
9884
9885   if (NoProtoDiagID.getDiagID() != 0 &&
9886       !NewFD->getType()->getAs<FunctionProtoType>())
9887     return Diag(NewFD->getLocation(), NoProtoDiagID);
9888
9889   if (!TemplatesSupported &&
9890       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9891     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9892            << FuncTemplates;
9893
9894   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9895     if (NewCXXFD->isVirtual())
9896       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9897              << VirtFuncs;
9898
9899     if (isa<CXXConstructorDecl>(NewCXXFD))
9900       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9901              << Constructors;
9902
9903     if (isa<CXXDestructorDecl>(NewCXXFD))
9904       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9905              << Destructors;
9906   }
9907
9908   if (NewFD->isDeleted())
9909     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9910            << DeletedFuncs;
9911
9912   if (NewFD->isDefaulted())
9913     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9914            << DefaultedFuncs;
9915
9916   if (!ConstexprSupported && NewFD->isConstexpr())
9917     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9918            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9919
9920   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9921   const auto *NewType = cast<FunctionType>(NewQType);
9922   QualType NewReturnType = NewType->getReturnType();
9923
9924   if (NewReturnType->isUndeducedType())
9925     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9926            << DeducedReturn;
9927
9928   // Ensure the return type is identical.
9929   if (OldFD) {
9930     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9931     const auto *OldType = cast<FunctionType>(OldQType);
9932     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9933     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9934
9935     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9936       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9937
9938     QualType OldReturnType = OldType->getReturnType();
9939
9940     if (OldReturnType != NewReturnType)
9941       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9942
9943     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9944       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9945
9946     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9947       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9948
9949     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9950       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9951
9952     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9953       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9954
9955     if (CheckEquivalentExceptionSpec(
9956             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9957             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9958       return true;
9959   }
9960   return false;
9961 }
9962
9963 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9964                                              const FunctionDecl *NewFD,
9965                                              bool CausesMV,
9966                                              MultiVersionKind MVType) {
9967   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9968     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9969     if (OldFD)
9970       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9971     return true;
9972   }
9973
9974   bool IsCPUSpecificCPUDispatchMVType =
9975       MVType == MultiVersionKind::CPUDispatch ||
9976       MVType == MultiVersionKind::CPUSpecific;
9977
9978   // For now, disallow all other attributes.  These should be opt-in, but
9979   // an analysis of all of them is a future FIXME.
9980   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9981     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9982         << IsCPUSpecificCPUDispatchMVType;
9983     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9984     return true;
9985   }
9986
9987   if (HasNonMultiVersionAttributes(NewFD, MVType))
9988     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9989            << IsCPUSpecificCPUDispatchMVType;
9990
9991   // Only allow transition to MultiVersion if it hasn't been used.
9992   if (OldFD && CausesMV && OldFD->isUsed(false))
9993     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9994
9995   return S.areMultiversionVariantFunctionsCompatible(
9996       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9997       PartialDiagnosticAt(NewFD->getLocation(),
9998                           S.PDiag(diag::note_multiversioning_caused_here)),
9999       PartialDiagnosticAt(NewFD->getLocation(),
10000                           S.PDiag(diag::err_multiversion_doesnt_support)
10001                               << IsCPUSpecificCPUDispatchMVType),
10002       PartialDiagnosticAt(NewFD->getLocation(),
10003                           S.PDiag(diag::err_multiversion_diff)),
10004       /*TemplatesSupported=*/false,
10005       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10006       /*CLinkageMayDiffer=*/false);
10007 }
10008
10009 /// Check the validity of a multiversion function declaration that is the
10010 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10011 ///
10012 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10013 ///
10014 /// Returns true if there was an error, false otherwise.
10015 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10016                                            MultiVersionKind MVType,
10017                                            const TargetAttr *TA) {
10018   assert(MVType != MultiVersionKind::None &&
10019          "Function lacks multiversion attribute");
10020
10021   // Target only causes MV if it is default, otherwise this is a normal
10022   // function.
10023   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10024     return false;
10025
10026   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10027     FD->setInvalidDecl();
10028     return true;
10029   }
10030
10031   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10032     FD->setInvalidDecl();
10033     return true;
10034   }
10035
10036   FD->setIsMultiVersion();
10037   return false;
10038 }
10039
10040 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10041   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10042     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10043       return true;
10044   }
10045
10046   return false;
10047 }
10048
10049 static bool CheckTargetCausesMultiVersioning(
10050     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10051     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10052     LookupResult &Previous) {
10053   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10054   ParsedTargetAttr NewParsed = NewTA->parse();
10055   // Sort order doesn't matter, it just needs to be consistent.
10056   llvm::sort(NewParsed.Features);
10057
10058   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10059   // to change, this is a simple redeclaration.
10060   if (!NewTA->isDefaultVersion() &&
10061       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10062     return false;
10063
10064   // Otherwise, this decl causes MultiVersioning.
10065   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10066     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10067     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10068     NewFD->setInvalidDecl();
10069     return true;
10070   }
10071
10072   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10073                                        MultiVersionKind::Target)) {
10074     NewFD->setInvalidDecl();
10075     return true;
10076   }
10077
10078   if (CheckMultiVersionValue(S, NewFD)) {
10079     NewFD->setInvalidDecl();
10080     return true;
10081   }
10082
10083   // If this is 'default', permit the forward declaration.
10084   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10085     Redeclaration = true;
10086     OldDecl = OldFD;
10087     OldFD->setIsMultiVersion();
10088     NewFD->setIsMultiVersion();
10089     return false;
10090   }
10091
10092   if (CheckMultiVersionValue(S, OldFD)) {
10093     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10094     NewFD->setInvalidDecl();
10095     return true;
10096   }
10097
10098   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10099
10100   if (OldParsed == NewParsed) {
10101     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10102     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10103     NewFD->setInvalidDecl();
10104     return true;
10105   }
10106
10107   for (const auto *FD : OldFD->redecls()) {
10108     const auto *CurTA = FD->getAttr<TargetAttr>();
10109     // We allow forward declarations before ANY multiversioning attributes, but
10110     // nothing after the fact.
10111     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10112         (!CurTA || CurTA->isInherited())) {
10113       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10114           << 0;
10115       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10116       NewFD->setInvalidDecl();
10117       return true;
10118     }
10119   }
10120
10121   OldFD->setIsMultiVersion();
10122   NewFD->setIsMultiVersion();
10123   Redeclaration = false;
10124   MergeTypeWithPrevious = false;
10125   OldDecl = nullptr;
10126   Previous.clear();
10127   return false;
10128 }
10129
10130 /// Check the validity of a new function declaration being added to an existing
10131 /// multiversioned declaration collection.
10132 static bool CheckMultiVersionAdditionalDecl(
10133     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10134     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10135     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10136     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10137     LookupResult &Previous) {
10138
10139   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10140   // Disallow mixing of multiversioning types.
10141   if ((OldMVType == MultiVersionKind::Target &&
10142        NewMVType != MultiVersionKind::Target) ||
10143       (NewMVType == MultiVersionKind::Target &&
10144        OldMVType != MultiVersionKind::Target)) {
10145     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10146     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10147     NewFD->setInvalidDecl();
10148     return true;
10149   }
10150
10151   ParsedTargetAttr NewParsed;
10152   if (NewTA) {
10153     NewParsed = NewTA->parse();
10154     llvm::sort(NewParsed.Features);
10155   }
10156
10157   bool UseMemberUsingDeclRules =
10158       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10159
10160   // Next, check ALL non-overloads to see if this is a redeclaration of a
10161   // previous member of the MultiVersion set.
10162   for (NamedDecl *ND : Previous) {
10163     FunctionDecl *CurFD = ND->getAsFunction();
10164     if (!CurFD)
10165       continue;
10166     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10167       continue;
10168
10169     if (NewMVType == MultiVersionKind::Target) {
10170       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10171       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10172         NewFD->setIsMultiVersion();
10173         Redeclaration = true;
10174         OldDecl = ND;
10175         return false;
10176       }
10177
10178       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10179       if (CurParsed == NewParsed) {
10180         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10181         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10182         NewFD->setInvalidDecl();
10183         return true;
10184       }
10185     } else {
10186       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10187       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10188       // Handle CPUDispatch/CPUSpecific versions.
10189       // Only 1 CPUDispatch function is allowed, this will make it go through
10190       // the redeclaration errors.
10191       if (NewMVType == MultiVersionKind::CPUDispatch &&
10192           CurFD->hasAttr<CPUDispatchAttr>()) {
10193         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10194             std::equal(
10195                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10196                 NewCPUDisp->cpus_begin(),
10197                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10198                   return Cur->getName() == New->getName();
10199                 })) {
10200           NewFD->setIsMultiVersion();
10201           Redeclaration = true;
10202           OldDecl = ND;
10203           return false;
10204         }
10205
10206         // If the declarations don't match, this is an error condition.
10207         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10208         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10209         NewFD->setInvalidDecl();
10210         return true;
10211       }
10212       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10213
10214         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10215             std::equal(
10216                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10217                 NewCPUSpec->cpus_begin(),
10218                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10219                   return Cur->getName() == New->getName();
10220                 })) {
10221           NewFD->setIsMultiVersion();
10222           Redeclaration = true;
10223           OldDecl = ND;
10224           return false;
10225         }
10226
10227         // Only 1 version of CPUSpecific is allowed for each CPU.
10228         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10229           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10230             if (CurII == NewII) {
10231               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10232                   << NewII;
10233               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10234               NewFD->setInvalidDecl();
10235               return true;
10236             }
10237           }
10238         }
10239       }
10240       // If the two decls aren't the same MVType, there is no possible error
10241       // condition.
10242     }
10243   }
10244
10245   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10246   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10247   // handled in the attribute adding step.
10248   if (NewMVType == MultiVersionKind::Target &&
10249       CheckMultiVersionValue(S, NewFD)) {
10250     NewFD->setInvalidDecl();
10251     return true;
10252   }
10253
10254   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10255                                        !OldFD->isMultiVersion(), NewMVType)) {
10256     NewFD->setInvalidDecl();
10257     return true;
10258   }
10259
10260   // Permit forward declarations in the case where these two are compatible.
10261   if (!OldFD->isMultiVersion()) {
10262     OldFD->setIsMultiVersion();
10263     NewFD->setIsMultiVersion();
10264     Redeclaration = true;
10265     OldDecl = OldFD;
10266     return false;
10267   }
10268
10269   NewFD->setIsMultiVersion();
10270   Redeclaration = false;
10271   MergeTypeWithPrevious = false;
10272   OldDecl = nullptr;
10273   Previous.clear();
10274   return false;
10275 }
10276
10277
10278 /// Check the validity of a mulitversion function declaration.
10279 /// Also sets the multiversion'ness' of the function itself.
10280 ///
10281 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10282 ///
10283 /// Returns true if there was an error, false otherwise.
10284 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10285                                       bool &Redeclaration, NamedDecl *&OldDecl,
10286                                       bool &MergeTypeWithPrevious,
10287                                       LookupResult &Previous) {
10288   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10289   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10290   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10291
10292   // Mixing Multiversioning types is prohibited.
10293   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10294       (NewCPUDisp && NewCPUSpec)) {
10295     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10296     NewFD->setInvalidDecl();
10297     return true;
10298   }
10299
10300   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10301
10302   // Main isn't allowed to become a multiversion function, however it IS
10303   // permitted to have 'main' be marked with the 'target' optimization hint.
10304   if (NewFD->isMain()) {
10305     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10306         MVType == MultiVersionKind::CPUDispatch ||
10307         MVType == MultiVersionKind::CPUSpecific) {
10308       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10309       NewFD->setInvalidDecl();
10310       return true;
10311     }
10312     return false;
10313   }
10314
10315   if (!OldDecl || !OldDecl->getAsFunction() ||
10316       OldDecl->getDeclContext()->getRedeclContext() !=
10317           NewFD->getDeclContext()->getRedeclContext()) {
10318     // If there's no previous declaration, AND this isn't attempting to cause
10319     // multiversioning, this isn't an error condition.
10320     if (MVType == MultiVersionKind::None)
10321       return false;
10322     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10323   }
10324
10325   FunctionDecl *OldFD = OldDecl->getAsFunction();
10326
10327   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10328     return false;
10329
10330   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10331     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10332         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10333     NewFD->setInvalidDecl();
10334     return true;
10335   }
10336
10337   // Handle the target potentially causes multiversioning case.
10338   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10339     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10340                                             Redeclaration, OldDecl,
10341                                             MergeTypeWithPrevious, Previous);
10342
10343   // At this point, we have a multiversion function decl (in OldFD) AND an
10344   // appropriate attribute in the current function decl.  Resolve that these are
10345   // still compatible with previous declarations.
10346   return CheckMultiVersionAdditionalDecl(
10347       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10348       OldDecl, MergeTypeWithPrevious, Previous);
10349 }
10350
10351 /// Perform semantic checking of a new function declaration.
10352 ///
10353 /// Performs semantic analysis of the new function declaration
10354 /// NewFD. This routine performs all semantic checking that does not
10355 /// require the actual declarator involved in the declaration, and is
10356 /// used both for the declaration of functions as they are parsed
10357 /// (called via ActOnDeclarator) and for the declaration of functions
10358 /// that have been instantiated via C++ template instantiation (called
10359 /// via InstantiateDecl).
10360 ///
10361 /// \param IsMemberSpecialization whether this new function declaration is
10362 /// a member specialization (that replaces any definition provided by the
10363 /// previous declaration).
10364 ///
10365 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10366 ///
10367 /// \returns true if the function declaration is a redeclaration.
10368 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10369                                     LookupResult &Previous,
10370                                     bool IsMemberSpecialization) {
10371   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10372          "Variably modified return types are not handled here");
10373
10374   // Determine whether the type of this function should be merged with
10375   // a previous visible declaration. This never happens for functions in C++,
10376   // and always happens in C if the previous declaration was visible.
10377   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10378                                !Previous.isShadowed();
10379
10380   bool Redeclaration = false;
10381   NamedDecl *OldDecl = nullptr;
10382   bool MayNeedOverloadableChecks = false;
10383
10384   // Merge or overload the declaration with an existing declaration of
10385   // the same name, if appropriate.
10386   if (!Previous.empty()) {
10387     // Determine whether NewFD is an overload of PrevDecl or
10388     // a declaration that requires merging. If it's an overload,
10389     // there's no more work to do here; we'll just add the new
10390     // function to the scope.
10391     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10392       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10393       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10394         Redeclaration = true;
10395         OldDecl = Candidate;
10396       }
10397     } else {
10398       MayNeedOverloadableChecks = true;
10399       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10400                             /*NewIsUsingDecl*/ false)) {
10401       case Ovl_Match:
10402         Redeclaration = true;
10403         break;
10404
10405       case Ovl_NonFunction:
10406         Redeclaration = true;
10407         break;
10408
10409       case Ovl_Overload:
10410         Redeclaration = false;
10411         break;
10412       }
10413     }
10414   }
10415
10416   // Check for a previous extern "C" declaration with this name.
10417   if (!Redeclaration &&
10418       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10419     if (!Previous.empty()) {
10420       // This is an extern "C" declaration with the same name as a previous
10421       // declaration, and thus redeclares that entity...
10422       Redeclaration = true;
10423       OldDecl = Previous.getFoundDecl();
10424       MergeTypeWithPrevious = false;
10425
10426       // ... except in the presence of __attribute__((overloadable)).
10427       if (OldDecl->hasAttr<OverloadableAttr>() ||
10428           NewFD->hasAttr<OverloadableAttr>()) {
10429         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10430           MayNeedOverloadableChecks = true;
10431           Redeclaration = false;
10432           OldDecl = nullptr;
10433         }
10434       }
10435     }
10436   }
10437
10438   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10439                                 MergeTypeWithPrevious, Previous))
10440     return Redeclaration;
10441
10442   // C++11 [dcl.constexpr]p8:
10443   //   A constexpr specifier for a non-static member function that is not
10444   //   a constructor declares that member function to be const.
10445   //
10446   // This needs to be delayed until we know whether this is an out-of-line
10447   // definition of a static member function.
10448   //
10449   // This rule is not present in C++1y, so we produce a backwards
10450   // compatibility warning whenever it happens in C++11.
10451   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10452   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10453       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10454       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10455     CXXMethodDecl *OldMD = nullptr;
10456     if (OldDecl)
10457       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10458     if (!OldMD || !OldMD->isStatic()) {
10459       const FunctionProtoType *FPT =
10460         MD->getType()->castAs<FunctionProtoType>();
10461       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10462       EPI.TypeQuals.addConst();
10463       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10464                                           FPT->getParamTypes(), EPI));
10465
10466       // Warn that we did this, if we're not performing template instantiation.
10467       // In that case, we'll have warned already when the template was defined.
10468       if (!inTemplateInstantiation()) {
10469         SourceLocation AddConstLoc;
10470         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10471                 .IgnoreParens().getAs<FunctionTypeLoc>())
10472           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10473
10474         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10475           << FixItHint::CreateInsertion(AddConstLoc, " const");
10476       }
10477     }
10478   }
10479
10480   if (Redeclaration) {
10481     // NewFD and OldDecl represent declarations that need to be
10482     // merged.
10483     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10484       NewFD->setInvalidDecl();
10485       return Redeclaration;
10486     }
10487
10488     Previous.clear();
10489     Previous.addDecl(OldDecl);
10490
10491     if (FunctionTemplateDecl *OldTemplateDecl =
10492             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10493       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10494       FunctionTemplateDecl *NewTemplateDecl
10495         = NewFD->getDescribedFunctionTemplate();
10496       assert(NewTemplateDecl && "Template/non-template mismatch");
10497
10498       // The call to MergeFunctionDecl above may have created some state in
10499       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10500       // can add it as a redeclaration.
10501       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10502
10503       NewFD->setPreviousDeclaration(OldFD);
10504       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10505       if (NewFD->isCXXClassMember()) {
10506         NewFD->setAccess(OldTemplateDecl->getAccess());
10507         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10508       }
10509
10510       // If this is an explicit specialization of a member that is a function
10511       // template, mark it as a member specialization.
10512       if (IsMemberSpecialization &&
10513           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10514         NewTemplateDecl->setMemberSpecialization();
10515         assert(OldTemplateDecl->isMemberSpecialization());
10516         // Explicit specializations of a member template do not inherit deleted
10517         // status from the parent member template that they are specializing.
10518         if (OldFD->isDeleted()) {
10519           // FIXME: This assert will not hold in the presence of modules.
10520           assert(OldFD->getCanonicalDecl() == OldFD);
10521           // FIXME: We need an update record for this AST mutation.
10522           OldFD->setDeletedAsWritten(false);
10523         }
10524       }
10525
10526     } else {
10527       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10528         auto *OldFD = cast<FunctionDecl>(OldDecl);
10529         // This needs to happen first so that 'inline' propagates.
10530         NewFD->setPreviousDeclaration(OldFD);
10531         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10532         if (NewFD->isCXXClassMember())
10533           NewFD->setAccess(OldFD->getAccess());
10534       }
10535     }
10536   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10537              !NewFD->getAttr<OverloadableAttr>()) {
10538     assert((Previous.empty() ||
10539             llvm::any_of(Previous,
10540                          [](const NamedDecl *ND) {
10541                            return ND->hasAttr<OverloadableAttr>();
10542                          })) &&
10543            "Non-redecls shouldn't happen without overloadable present");
10544
10545     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10546       const auto *FD = dyn_cast<FunctionDecl>(ND);
10547       return FD && !FD->hasAttr<OverloadableAttr>();
10548     });
10549
10550     if (OtherUnmarkedIter != Previous.end()) {
10551       Diag(NewFD->getLocation(),
10552            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10553       Diag((*OtherUnmarkedIter)->getLocation(),
10554            diag::note_attribute_overloadable_prev_overload)
10555           << false;
10556
10557       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10558     }
10559   }
10560
10561   // Semantic checking for this function declaration (in isolation).
10562
10563   if (getLangOpts().CPlusPlus) {
10564     // C++-specific checks.
10565     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10566       CheckConstructor(Constructor);
10567     } else if (CXXDestructorDecl *Destructor =
10568                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10569       CXXRecordDecl *Record = Destructor->getParent();
10570       QualType ClassType = Context.getTypeDeclType(Record);
10571
10572       // FIXME: Shouldn't we be able to perform this check even when the class
10573       // type is dependent? Both gcc and edg can handle that.
10574       if (!ClassType->isDependentType()) {
10575         DeclarationName Name
10576           = Context.DeclarationNames.getCXXDestructorName(
10577                                         Context.getCanonicalType(ClassType));
10578         if (NewFD->getDeclName() != Name) {
10579           Diag(NewFD->getLocation(), diag::err_destructor_name);
10580           NewFD->setInvalidDecl();
10581           return Redeclaration;
10582         }
10583       }
10584     } else if (CXXConversionDecl *Conversion
10585                = dyn_cast<CXXConversionDecl>(NewFD)) {
10586       ActOnConversionDeclarator(Conversion);
10587     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10588       if (auto *TD = Guide->getDescribedFunctionTemplate())
10589         CheckDeductionGuideTemplate(TD);
10590
10591       // A deduction guide is not on the list of entities that can be
10592       // explicitly specialized.
10593       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10594         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10595             << /*explicit specialization*/ 1;
10596     }
10597
10598     // Find any virtual functions that this function overrides.
10599     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10600       if (!Method->isFunctionTemplateSpecialization() &&
10601           !Method->getDescribedFunctionTemplate() &&
10602           Method->isCanonicalDecl()) {
10603         if (AddOverriddenMethods(Method->getParent(), Method)) {
10604           // If the function was marked as "static", we have a problem.
10605           if (NewFD->getStorageClass() == SC_Static) {
10606             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10607           }
10608         }
10609       }
10610       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10611         // C++2a [class.virtual]p6
10612         // A virtual method shall not have a requires-clause.
10613         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10614              diag::err_constrained_virtual_method);
10615
10616       if (Method->isStatic())
10617         checkThisInStaticMemberFunctionType(Method);
10618     }
10619
10620     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10621     if (NewFD->isOverloadedOperator() &&
10622         CheckOverloadedOperatorDeclaration(NewFD)) {
10623       NewFD->setInvalidDecl();
10624       return Redeclaration;
10625     }
10626
10627     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10628     if (NewFD->getLiteralIdentifier() &&
10629         CheckLiteralOperatorDeclaration(NewFD)) {
10630       NewFD->setInvalidDecl();
10631       return Redeclaration;
10632     }
10633
10634     // In C++, check default arguments now that we have merged decls. Unless
10635     // the lexical context is the class, because in this case this is done
10636     // during delayed parsing anyway.
10637     if (!CurContext->isRecord())
10638       CheckCXXDefaultArguments(NewFD);
10639
10640     // If this function declares a builtin function, check the type of this
10641     // declaration against the expected type for the builtin.
10642     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10643       ASTContext::GetBuiltinTypeError Error;
10644       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10645       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10646       // If the type of the builtin differs only in its exception
10647       // specification, that's OK.
10648       // FIXME: If the types do differ in this way, it would be better to
10649       // retain the 'noexcept' form of the type.
10650       if (!T.isNull() &&
10651           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10652                                                             NewFD->getType()))
10653         // The type of this function differs from the type of the builtin,
10654         // so forget about the builtin entirely.
10655         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10656     }
10657
10658     // If this function is declared as being extern "C", then check to see if
10659     // the function returns a UDT (class, struct, or union type) that is not C
10660     // compatible, and if it does, warn the user.
10661     // But, issue any diagnostic on the first declaration only.
10662     if (Previous.empty() && NewFD->isExternC()) {
10663       QualType R = NewFD->getReturnType();
10664       if (R->isIncompleteType() && !R->isVoidType())
10665         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10666             << NewFD << R;
10667       else if (!R.isPODType(Context) && !R->isVoidType() &&
10668                !R->isObjCObjectPointerType())
10669         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10670     }
10671
10672     // C++1z [dcl.fct]p6:
10673     //   [...] whether the function has a non-throwing exception-specification
10674     //   [is] part of the function type
10675     //
10676     // This results in an ABI break between C++14 and C++17 for functions whose
10677     // declared type includes an exception-specification in a parameter or
10678     // return type. (Exception specifications on the function itself are OK in
10679     // most cases, and exception specifications are not permitted in most other
10680     // contexts where they could make it into a mangling.)
10681     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10682       auto HasNoexcept = [&](QualType T) -> bool {
10683         // Strip off declarator chunks that could be between us and a function
10684         // type. We don't need to look far, exception specifications are very
10685         // restricted prior to C++17.
10686         if (auto *RT = T->getAs<ReferenceType>())
10687           T = RT->getPointeeType();
10688         else if (T->isAnyPointerType())
10689           T = T->getPointeeType();
10690         else if (auto *MPT = T->getAs<MemberPointerType>())
10691           T = MPT->getPointeeType();
10692         if (auto *FPT = T->getAs<FunctionProtoType>())
10693           if (FPT->isNothrow())
10694             return true;
10695         return false;
10696       };
10697
10698       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10699       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10700       for (QualType T : FPT->param_types())
10701         AnyNoexcept |= HasNoexcept(T);
10702       if (AnyNoexcept)
10703         Diag(NewFD->getLocation(),
10704              diag::warn_cxx17_compat_exception_spec_in_signature)
10705             << NewFD;
10706     }
10707
10708     if (!Redeclaration && LangOpts.CUDA)
10709       checkCUDATargetOverload(NewFD, Previous);
10710   }
10711   return Redeclaration;
10712 }
10713
10714 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10715   // C++11 [basic.start.main]p3:
10716   //   A program that [...] declares main to be inline, static or
10717   //   constexpr is ill-formed.
10718   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10719   //   appear in a declaration of main.
10720   // static main is not an error under C99, but we should warn about it.
10721   // We accept _Noreturn main as an extension.
10722   if (FD->getStorageClass() == SC_Static)
10723     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10724          ? diag::err_static_main : diag::warn_static_main)
10725       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10726   if (FD->isInlineSpecified())
10727     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10728       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10729   if (DS.isNoreturnSpecified()) {
10730     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10731     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10732     Diag(NoreturnLoc, diag::ext_noreturn_main);
10733     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10734       << FixItHint::CreateRemoval(NoreturnRange);
10735   }
10736   if (FD->isConstexpr()) {
10737     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10738         << FD->isConsteval()
10739         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10740     FD->setConstexprKind(CSK_unspecified);
10741   }
10742
10743   if (getLangOpts().OpenCL) {
10744     Diag(FD->getLocation(), diag::err_opencl_no_main)
10745         << FD->hasAttr<OpenCLKernelAttr>();
10746     FD->setInvalidDecl();
10747     return;
10748   }
10749
10750   QualType T = FD->getType();
10751   assert(T->isFunctionType() && "function decl is not of function type");
10752   const FunctionType* FT = T->castAs<FunctionType>();
10753
10754   // Set default calling convention for main()
10755   if (FT->getCallConv() != CC_C) {
10756     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10757     FD->setType(QualType(FT, 0));
10758     T = Context.getCanonicalType(FD->getType());
10759   }
10760
10761   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10762     // In C with GNU extensions we allow main() to have non-integer return
10763     // type, but we should warn about the extension, and we disable the
10764     // implicit-return-zero rule.
10765
10766     // GCC in C mode accepts qualified 'int'.
10767     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10768       FD->setHasImplicitReturnZero(true);
10769     else {
10770       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10771       SourceRange RTRange = FD->getReturnTypeSourceRange();
10772       if (RTRange.isValid())
10773         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10774             << FixItHint::CreateReplacement(RTRange, "int");
10775     }
10776   } else {
10777     // In C and C++, main magically returns 0 if you fall off the end;
10778     // set the flag which tells us that.
10779     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10780
10781     // All the standards say that main() should return 'int'.
10782     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10783       FD->setHasImplicitReturnZero(true);
10784     else {
10785       // Otherwise, this is just a flat-out error.
10786       SourceRange RTRange = FD->getReturnTypeSourceRange();
10787       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10788           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10789                                 : FixItHint());
10790       FD->setInvalidDecl(true);
10791     }
10792   }
10793
10794   // Treat protoless main() as nullary.
10795   if (isa<FunctionNoProtoType>(FT)) return;
10796
10797   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10798   unsigned nparams = FTP->getNumParams();
10799   assert(FD->getNumParams() == nparams);
10800
10801   bool HasExtraParameters = (nparams > 3);
10802
10803   if (FTP->isVariadic()) {
10804     Diag(FD->getLocation(), diag::ext_variadic_main);
10805     // FIXME: if we had information about the location of the ellipsis, we
10806     // could add a FixIt hint to remove it as a parameter.
10807   }
10808
10809   // Darwin passes an undocumented fourth argument of type char**.  If
10810   // other platforms start sprouting these, the logic below will start
10811   // getting shifty.
10812   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10813     HasExtraParameters = false;
10814
10815   if (HasExtraParameters) {
10816     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10817     FD->setInvalidDecl(true);
10818     nparams = 3;
10819   }
10820
10821   // FIXME: a lot of the following diagnostics would be improved
10822   // if we had some location information about types.
10823
10824   QualType CharPP =
10825     Context.getPointerType(Context.getPointerType(Context.CharTy));
10826   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10827
10828   for (unsigned i = 0; i < nparams; ++i) {
10829     QualType AT = FTP->getParamType(i);
10830
10831     bool mismatch = true;
10832
10833     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10834       mismatch = false;
10835     else if (Expected[i] == CharPP) {
10836       // As an extension, the following forms are okay:
10837       //   char const **
10838       //   char const * const *
10839       //   char * const *
10840
10841       QualifierCollector qs;
10842       const PointerType* PT;
10843       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10844           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10845           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10846                               Context.CharTy)) {
10847         qs.removeConst();
10848         mismatch = !qs.empty();
10849       }
10850     }
10851
10852     if (mismatch) {
10853       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10854       // TODO: suggest replacing given type with expected type
10855       FD->setInvalidDecl(true);
10856     }
10857   }
10858
10859   if (nparams == 1 && !FD->isInvalidDecl()) {
10860     Diag(FD->getLocation(), diag::warn_main_one_arg);
10861   }
10862
10863   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10864     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10865     FD->setInvalidDecl();
10866   }
10867 }
10868
10869 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10870   QualType T = FD->getType();
10871   assert(T->isFunctionType() && "function decl is not of function type");
10872   const FunctionType *FT = T->castAs<FunctionType>();
10873
10874   // Set an implicit return of 'zero' if the function can return some integral,
10875   // enumeration, pointer or nullptr type.
10876   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10877       FT->getReturnType()->isAnyPointerType() ||
10878       FT->getReturnType()->isNullPtrType())
10879     // DllMain is exempt because a return value of zero means it failed.
10880     if (FD->getName() != "DllMain")
10881       FD->setHasImplicitReturnZero(true);
10882
10883   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10884     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10885     FD->setInvalidDecl();
10886   }
10887 }
10888
10889 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10890   // FIXME: Need strict checking.  In C89, we need to check for
10891   // any assignment, increment, decrement, function-calls, or
10892   // commas outside of a sizeof.  In C99, it's the same list,
10893   // except that the aforementioned are allowed in unevaluated
10894   // expressions.  Everything else falls under the
10895   // "may accept other forms of constant expressions" exception.
10896   // (We never end up here for C++, so the constant expression
10897   // rules there don't matter.)
10898   const Expr *Culprit;
10899   if (Init->isConstantInitializer(Context, false, &Culprit))
10900     return false;
10901   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10902     << Culprit->getSourceRange();
10903   return true;
10904 }
10905
10906 namespace {
10907   // Visits an initialization expression to see if OrigDecl is evaluated in
10908   // its own initialization and throws a warning if it does.
10909   class SelfReferenceChecker
10910       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10911     Sema &S;
10912     Decl *OrigDecl;
10913     bool isRecordType;
10914     bool isPODType;
10915     bool isReferenceType;
10916
10917     bool isInitList;
10918     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10919
10920   public:
10921     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10922
10923     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10924                                                     S(S), OrigDecl(OrigDecl) {
10925       isPODType = false;
10926       isRecordType = false;
10927       isReferenceType = false;
10928       isInitList = false;
10929       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10930         isPODType = VD->getType().isPODType(S.Context);
10931         isRecordType = VD->getType()->isRecordType();
10932         isReferenceType = VD->getType()->isReferenceType();
10933       }
10934     }
10935
10936     // For most expressions, just call the visitor.  For initializer lists,
10937     // track the index of the field being initialized since fields are
10938     // initialized in order allowing use of previously initialized fields.
10939     void CheckExpr(Expr *E) {
10940       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10941       if (!InitList) {
10942         Visit(E);
10943         return;
10944       }
10945
10946       // Track and increment the index here.
10947       isInitList = true;
10948       InitFieldIndex.push_back(0);
10949       for (auto Child : InitList->children()) {
10950         CheckExpr(cast<Expr>(Child));
10951         ++InitFieldIndex.back();
10952       }
10953       InitFieldIndex.pop_back();
10954     }
10955
10956     // Returns true if MemberExpr is checked and no further checking is needed.
10957     // Returns false if additional checking is required.
10958     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10959       llvm::SmallVector<FieldDecl*, 4> Fields;
10960       Expr *Base = E;
10961       bool ReferenceField = false;
10962
10963       // Get the field members used.
10964       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10965         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10966         if (!FD)
10967           return false;
10968         Fields.push_back(FD);
10969         if (FD->getType()->isReferenceType())
10970           ReferenceField = true;
10971         Base = ME->getBase()->IgnoreParenImpCasts();
10972       }
10973
10974       // Keep checking only if the base Decl is the same.
10975       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10976       if (!DRE || DRE->getDecl() != OrigDecl)
10977         return false;
10978
10979       // A reference field can be bound to an unininitialized field.
10980       if (CheckReference && !ReferenceField)
10981         return true;
10982
10983       // Convert FieldDecls to their index number.
10984       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10985       for (const FieldDecl *I : llvm::reverse(Fields))
10986         UsedFieldIndex.push_back(I->getFieldIndex());
10987
10988       // See if a warning is needed by checking the first difference in index
10989       // numbers.  If field being used has index less than the field being
10990       // initialized, then the use is safe.
10991       for (auto UsedIter = UsedFieldIndex.begin(),
10992                 UsedEnd = UsedFieldIndex.end(),
10993                 OrigIter = InitFieldIndex.begin(),
10994                 OrigEnd = InitFieldIndex.end();
10995            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10996         if (*UsedIter < *OrigIter)
10997           return true;
10998         if (*UsedIter > *OrigIter)
10999           break;
11000       }
11001
11002       // TODO: Add a different warning which will print the field names.
11003       HandleDeclRefExpr(DRE);
11004       return true;
11005     }
11006
11007     // For most expressions, the cast is directly above the DeclRefExpr.
11008     // For conditional operators, the cast can be outside the conditional
11009     // operator if both expressions are DeclRefExpr's.
11010     void HandleValue(Expr *E) {
11011       E = E->IgnoreParens();
11012       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11013         HandleDeclRefExpr(DRE);
11014         return;
11015       }
11016
11017       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11018         Visit(CO->getCond());
11019         HandleValue(CO->getTrueExpr());
11020         HandleValue(CO->getFalseExpr());
11021         return;
11022       }
11023
11024       if (BinaryConditionalOperator *BCO =
11025               dyn_cast<BinaryConditionalOperator>(E)) {
11026         Visit(BCO->getCond());
11027         HandleValue(BCO->getFalseExpr());
11028         return;
11029       }
11030
11031       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11032         HandleValue(OVE->getSourceExpr());
11033         return;
11034       }
11035
11036       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11037         if (BO->getOpcode() == BO_Comma) {
11038           Visit(BO->getLHS());
11039           HandleValue(BO->getRHS());
11040           return;
11041         }
11042       }
11043
11044       if (isa<MemberExpr>(E)) {
11045         if (isInitList) {
11046           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11047                                       false /*CheckReference*/))
11048             return;
11049         }
11050
11051         Expr *Base = E->IgnoreParenImpCasts();
11052         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11053           // Check for static member variables and don't warn on them.
11054           if (!isa<FieldDecl>(ME->getMemberDecl()))
11055             return;
11056           Base = ME->getBase()->IgnoreParenImpCasts();
11057         }
11058         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11059           HandleDeclRefExpr(DRE);
11060         return;
11061       }
11062
11063       Visit(E);
11064     }
11065
11066     // Reference types not handled in HandleValue are handled here since all
11067     // uses of references are bad, not just r-value uses.
11068     void VisitDeclRefExpr(DeclRefExpr *E) {
11069       if (isReferenceType)
11070         HandleDeclRefExpr(E);
11071     }
11072
11073     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11074       if (E->getCastKind() == CK_LValueToRValue) {
11075         HandleValue(E->getSubExpr());
11076         return;
11077       }
11078
11079       Inherited::VisitImplicitCastExpr(E);
11080     }
11081
11082     void VisitMemberExpr(MemberExpr *E) {
11083       if (isInitList) {
11084         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11085           return;
11086       }
11087
11088       // Don't warn on arrays since they can be treated as pointers.
11089       if (E->getType()->canDecayToPointerType()) return;
11090
11091       // Warn when a non-static method call is followed by non-static member
11092       // field accesses, which is followed by a DeclRefExpr.
11093       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11094       bool Warn = (MD && !MD->isStatic());
11095       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11096       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11097         if (!isa<FieldDecl>(ME->getMemberDecl()))
11098           Warn = false;
11099         Base = ME->getBase()->IgnoreParenImpCasts();
11100       }
11101
11102       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11103         if (Warn)
11104           HandleDeclRefExpr(DRE);
11105         return;
11106       }
11107
11108       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11109       // Visit that expression.
11110       Visit(Base);
11111     }
11112
11113     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11114       Expr *Callee = E->getCallee();
11115
11116       if (isa<UnresolvedLookupExpr>(Callee))
11117         return Inherited::VisitCXXOperatorCallExpr(E);
11118
11119       Visit(Callee);
11120       for (auto Arg: E->arguments())
11121         HandleValue(Arg->IgnoreParenImpCasts());
11122     }
11123
11124     void VisitUnaryOperator(UnaryOperator *E) {
11125       // For POD record types, addresses of its own members are well-defined.
11126       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11127           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11128         if (!isPODType)
11129           HandleValue(E->getSubExpr());
11130         return;
11131       }
11132
11133       if (E->isIncrementDecrementOp()) {
11134         HandleValue(E->getSubExpr());
11135         return;
11136       }
11137
11138       Inherited::VisitUnaryOperator(E);
11139     }
11140
11141     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11142
11143     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11144       if (E->getConstructor()->isCopyConstructor()) {
11145         Expr *ArgExpr = E->getArg(0);
11146         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11147           if (ILE->getNumInits() == 1)
11148             ArgExpr = ILE->getInit(0);
11149         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11150           if (ICE->getCastKind() == CK_NoOp)
11151             ArgExpr = ICE->getSubExpr();
11152         HandleValue(ArgExpr);
11153         return;
11154       }
11155       Inherited::VisitCXXConstructExpr(E);
11156     }
11157
11158     void VisitCallExpr(CallExpr *E) {
11159       // Treat std::move as a use.
11160       if (E->isCallToStdMove()) {
11161         HandleValue(E->getArg(0));
11162         return;
11163       }
11164
11165       Inherited::VisitCallExpr(E);
11166     }
11167
11168     void VisitBinaryOperator(BinaryOperator *E) {
11169       if (E->isCompoundAssignmentOp()) {
11170         HandleValue(E->getLHS());
11171         Visit(E->getRHS());
11172         return;
11173       }
11174
11175       Inherited::VisitBinaryOperator(E);
11176     }
11177
11178     // A custom visitor for BinaryConditionalOperator is needed because the
11179     // regular visitor would check the condition and true expression separately
11180     // but both point to the same place giving duplicate diagnostics.
11181     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11182       Visit(E->getCond());
11183       Visit(E->getFalseExpr());
11184     }
11185
11186     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11187       Decl* ReferenceDecl = DRE->getDecl();
11188       if (OrigDecl != ReferenceDecl) return;
11189       unsigned diag;
11190       if (isReferenceType) {
11191         diag = diag::warn_uninit_self_reference_in_reference_init;
11192       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11193         diag = diag::warn_static_self_reference_in_init;
11194       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11195                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11196                  DRE->getDecl()->getType()->isRecordType()) {
11197         diag = diag::warn_uninit_self_reference_in_init;
11198       } else {
11199         // Local variables will be handled by the CFG analysis.
11200         return;
11201       }
11202
11203       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11204                             S.PDiag(diag)
11205                                 << DRE->getDecl() << OrigDecl->getLocation()
11206                                 << DRE->getSourceRange());
11207     }
11208   };
11209
11210   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11211   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11212                                  bool DirectInit) {
11213     // Parameters arguments are occassionially constructed with itself,
11214     // for instance, in recursive functions.  Skip them.
11215     if (isa<ParmVarDecl>(OrigDecl))
11216       return;
11217
11218     E = E->IgnoreParens();
11219
11220     // Skip checking T a = a where T is not a record or reference type.
11221     // Doing so is a way to silence uninitialized warnings.
11222     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11223       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11224         if (ICE->getCastKind() == CK_LValueToRValue)
11225           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11226             if (DRE->getDecl() == OrigDecl)
11227               return;
11228
11229     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11230   }
11231 } // end anonymous namespace
11232
11233 namespace {
11234   // Simple wrapper to add the name of a variable or (if no variable is
11235   // available) a DeclarationName into a diagnostic.
11236   struct VarDeclOrName {
11237     VarDecl *VDecl;
11238     DeclarationName Name;
11239
11240     friend const Sema::SemaDiagnosticBuilder &
11241     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11242       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11243     }
11244   };
11245 } // end anonymous namespace
11246
11247 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11248                                             DeclarationName Name, QualType Type,
11249                                             TypeSourceInfo *TSI,
11250                                             SourceRange Range, bool DirectInit,
11251                                             Expr *Init) {
11252   bool IsInitCapture = !VDecl;
11253   assert((!VDecl || !VDecl->isInitCapture()) &&
11254          "init captures are expected to be deduced prior to initialization");
11255
11256   VarDeclOrName VN{VDecl, Name};
11257
11258   DeducedType *Deduced = Type->getContainedDeducedType();
11259   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11260
11261   // C++11 [dcl.spec.auto]p3
11262   if (!Init) {
11263     assert(VDecl && "no init for init capture deduction?");
11264
11265     // Except for class argument deduction, and then for an initializing
11266     // declaration only, i.e. no static at class scope or extern.
11267     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11268         VDecl->hasExternalStorage() ||
11269         VDecl->isStaticDataMember()) {
11270       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11271         << VDecl->getDeclName() << Type;
11272       return QualType();
11273     }
11274   }
11275
11276   ArrayRef<Expr*> DeduceInits;
11277   if (Init)
11278     DeduceInits = Init;
11279
11280   if (DirectInit) {
11281     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11282       DeduceInits = PL->exprs();
11283   }
11284
11285   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11286     assert(VDecl && "non-auto type for init capture deduction?");
11287     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11288     InitializationKind Kind = InitializationKind::CreateForInit(
11289         VDecl->getLocation(), DirectInit, Init);
11290     // FIXME: Initialization should not be taking a mutable list of inits.
11291     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11292     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11293                                                        InitsCopy);
11294   }
11295
11296   if (DirectInit) {
11297     if (auto *IL = dyn_cast<InitListExpr>(Init))
11298       DeduceInits = IL->inits();
11299   }
11300
11301   // Deduction only works if we have exactly one source expression.
11302   if (DeduceInits.empty()) {
11303     // It isn't possible to write this directly, but it is possible to
11304     // end up in this situation with "auto x(some_pack...);"
11305     Diag(Init->getBeginLoc(), IsInitCapture
11306                                   ? diag::err_init_capture_no_expression
11307                                   : diag::err_auto_var_init_no_expression)
11308         << VN << Type << Range;
11309     return QualType();
11310   }
11311
11312   if (DeduceInits.size() > 1) {
11313     Diag(DeduceInits[1]->getBeginLoc(),
11314          IsInitCapture ? diag::err_init_capture_multiple_expressions
11315                        : diag::err_auto_var_init_multiple_expressions)
11316         << VN << Type << Range;
11317     return QualType();
11318   }
11319
11320   Expr *DeduceInit = DeduceInits[0];
11321   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11322     Diag(Init->getBeginLoc(), IsInitCapture
11323                                   ? diag::err_init_capture_paren_braces
11324                                   : diag::err_auto_var_init_paren_braces)
11325         << isa<InitListExpr>(Init) << VN << Type << Range;
11326     return QualType();
11327   }
11328
11329   // Expressions default to 'id' when we're in a debugger.
11330   bool DefaultedAnyToId = false;
11331   if (getLangOpts().DebuggerCastResultToId &&
11332       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11333     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11334     if (Result.isInvalid()) {
11335       return QualType();
11336     }
11337     Init = Result.get();
11338     DefaultedAnyToId = true;
11339   }
11340
11341   // C++ [dcl.decomp]p1:
11342   //   If the assignment-expression [...] has array type A and no ref-qualifier
11343   //   is present, e has type cv A
11344   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11345       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11346       DeduceInit->getType()->isConstantArrayType())
11347     return Context.getQualifiedType(DeduceInit->getType(),
11348                                     Type.getQualifiers());
11349
11350   QualType DeducedType;
11351   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11352     if (!IsInitCapture)
11353       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11354     else if (isa<InitListExpr>(Init))
11355       Diag(Range.getBegin(),
11356            diag::err_init_capture_deduction_failure_from_init_list)
11357           << VN
11358           << (DeduceInit->getType().isNull() ? TSI->getType()
11359                                              : DeduceInit->getType())
11360           << DeduceInit->getSourceRange();
11361     else
11362       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11363           << VN << TSI->getType()
11364           << (DeduceInit->getType().isNull() ? TSI->getType()
11365                                              : DeduceInit->getType())
11366           << DeduceInit->getSourceRange();
11367   }
11368
11369   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11370   // 'id' instead of a specific object type prevents most of our usual
11371   // checks.
11372   // We only want to warn outside of template instantiations, though:
11373   // inside a template, the 'id' could have come from a parameter.
11374   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11375       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11376     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11377     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11378   }
11379
11380   return DeducedType;
11381 }
11382
11383 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11384                                          Expr *Init) {
11385   QualType DeducedType = deduceVarTypeFromInitializer(
11386       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11387       VDecl->getSourceRange(), DirectInit, Init);
11388   if (DeducedType.isNull()) {
11389     VDecl->setInvalidDecl();
11390     return true;
11391   }
11392
11393   VDecl->setType(DeducedType);
11394   assert(VDecl->isLinkageValid());
11395
11396   // In ARC, infer lifetime.
11397   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11398     VDecl->setInvalidDecl();
11399
11400   if (getLangOpts().OpenCL)
11401     deduceOpenCLAddressSpace(VDecl);
11402
11403   // If this is a redeclaration, check that the type we just deduced matches
11404   // the previously declared type.
11405   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11406     // We never need to merge the type, because we cannot form an incomplete
11407     // array of auto, nor deduce such a type.
11408     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11409   }
11410
11411   // Check the deduced type is valid for a variable declaration.
11412   CheckVariableDeclarationType(VDecl);
11413   return VDecl->isInvalidDecl();
11414 }
11415
11416 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11417                                               SourceLocation Loc) {
11418   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11419     Init = CE->getSubExpr();
11420
11421   QualType InitType = Init->getType();
11422   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11423           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11424          "shouldn't be called if type doesn't have a non-trivial C struct");
11425   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11426     for (auto I : ILE->inits()) {
11427       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11428           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11429         continue;
11430       SourceLocation SL = I->getExprLoc();
11431       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11432     }
11433     return;
11434   }
11435
11436   if (isa<ImplicitValueInitExpr>(Init)) {
11437     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11438       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11439                             NTCUK_Init);
11440   } else {
11441     // Assume all other explicit initializers involving copying some existing
11442     // object.
11443     // TODO: ignore any explicit initializers where we can guarantee
11444     // copy-elision.
11445     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11446       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11447   }
11448 }
11449
11450 namespace {
11451
11452 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11453   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11454   // in the source code or implicitly by the compiler if it is in a union
11455   // defined in a system header and has non-trivial ObjC ownership
11456   // qualifications. We don't want those fields to participate in determining
11457   // whether the containing union is non-trivial.
11458   return FD->hasAttr<UnavailableAttr>();
11459 }
11460
11461 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11462     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11463                                     void> {
11464   using Super =
11465       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11466                                     void>;
11467
11468   DiagNonTrivalCUnionDefaultInitializeVisitor(
11469       QualType OrigTy, SourceLocation OrigLoc,
11470       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11471       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11472
11473   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11474                      const FieldDecl *FD, bool InNonTrivialUnion) {
11475     if (const auto *AT = S.Context.getAsArrayType(QT))
11476       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11477                                      InNonTrivialUnion);
11478     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11479   }
11480
11481   void visitARCStrong(QualType QT, const FieldDecl *FD,
11482                       bool InNonTrivialUnion) {
11483     if (InNonTrivialUnion)
11484       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11485           << 1 << 0 << QT << FD->getName();
11486   }
11487
11488   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11489     if (InNonTrivialUnion)
11490       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11491           << 1 << 0 << QT << FD->getName();
11492   }
11493
11494   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11495     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11496     if (RD->isUnion()) {
11497       if (OrigLoc.isValid()) {
11498         bool IsUnion = false;
11499         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11500           IsUnion = OrigRD->isUnion();
11501         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11502             << 0 << OrigTy << IsUnion << UseContext;
11503         // Reset OrigLoc so that this diagnostic is emitted only once.
11504         OrigLoc = SourceLocation();
11505       }
11506       InNonTrivialUnion = true;
11507     }
11508
11509     if (InNonTrivialUnion)
11510       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11511           << 0 << 0 << QT.getUnqualifiedType() << "";
11512
11513     for (const FieldDecl *FD : RD->fields())
11514       if (!shouldIgnoreForRecordTriviality(FD))
11515         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11516   }
11517
11518   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11519
11520   // The non-trivial C union type or the struct/union type that contains a
11521   // non-trivial C union.
11522   QualType OrigTy;
11523   SourceLocation OrigLoc;
11524   Sema::NonTrivialCUnionContext UseContext;
11525   Sema &S;
11526 };
11527
11528 struct DiagNonTrivalCUnionDestructedTypeVisitor
11529     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11530   using Super =
11531       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11532
11533   DiagNonTrivalCUnionDestructedTypeVisitor(
11534       QualType OrigTy, SourceLocation OrigLoc,
11535       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11536       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11537
11538   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11539                      const FieldDecl *FD, bool InNonTrivialUnion) {
11540     if (const auto *AT = S.Context.getAsArrayType(QT))
11541       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11542                                      InNonTrivialUnion);
11543     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11544   }
11545
11546   void visitARCStrong(QualType QT, const FieldDecl *FD,
11547                       bool InNonTrivialUnion) {
11548     if (InNonTrivialUnion)
11549       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11550           << 1 << 1 << QT << FD->getName();
11551   }
11552
11553   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11554     if (InNonTrivialUnion)
11555       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11556           << 1 << 1 << QT << FD->getName();
11557   }
11558
11559   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11560     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11561     if (RD->isUnion()) {
11562       if (OrigLoc.isValid()) {
11563         bool IsUnion = false;
11564         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11565           IsUnion = OrigRD->isUnion();
11566         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11567             << 1 << OrigTy << IsUnion << UseContext;
11568         // Reset OrigLoc so that this diagnostic is emitted only once.
11569         OrigLoc = SourceLocation();
11570       }
11571       InNonTrivialUnion = true;
11572     }
11573
11574     if (InNonTrivialUnion)
11575       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11576           << 0 << 1 << QT.getUnqualifiedType() << "";
11577
11578     for (const FieldDecl *FD : RD->fields())
11579       if (!shouldIgnoreForRecordTriviality(FD))
11580         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11581   }
11582
11583   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11584   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11585                           bool InNonTrivialUnion) {}
11586
11587   // The non-trivial C union type or the struct/union type that contains a
11588   // non-trivial C union.
11589   QualType OrigTy;
11590   SourceLocation OrigLoc;
11591   Sema::NonTrivialCUnionContext UseContext;
11592   Sema &S;
11593 };
11594
11595 struct DiagNonTrivalCUnionCopyVisitor
11596     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11597   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11598
11599   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11600                                  Sema::NonTrivialCUnionContext UseContext,
11601                                  Sema &S)
11602       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11603
11604   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11605                      const FieldDecl *FD, bool InNonTrivialUnion) {
11606     if (const auto *AT = S.Context.getAsArrayType(QT))
11607       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11608                                      InNonTrivialUnion);
11609     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11610   }
11611
11612   void visitARCStrong(QualType QT, const FieldDecl *FD,
11613                       bool InNonTrivialUnion) {
11614     if (InNonTrivialUnion)
11615       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11616           << 1 << 2 << QT << FD->getName();
11617   }
11618
11619   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11620     if (InNonTrivialUnion)
11621       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11622           << 1 << 2 << QT << FD->getName();
11623   }
11624
11625   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11626     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11627     if (RD->isUnion()) {
11628       if (OrigLoc.isValid()) {
11629         bool IsUnion = false;
11630         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11631           IsUnion = OrigRD->isUnion();
11632         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11633             << 2 << OrigTy << IsUnion << UseContext;
11634         // Reset OrigLoc so that this diagnostic is emitted only once.
11635         OrigLoc = SourceLocation();
11636       }
11637       InNonTrivialUnion = true;
11638     }
11639
11640     if (InNonTrivialUnion)
11641       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11642           << 0 << 2 << QT.getUnqualifiedType() << "";
11643
11644     for (const FieldDecl *FD : RD->fields())
11645       if (!shouldIgnoreForRecordTriviality(FD))
11646         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11647   }
11648
11649   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11650                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11651   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11652   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11653                             bool InNonTrivialUnion) {}
11654
11655   // The non-trivial C union type or the struct/union type that contains a
11656   // non-trivial C union.
11657   QualType OrigTy;
11658   SourceLocation OrigLoc;
11659   Sema::NonTrivialCUnionContext UseContext;
11660   Sema &S;
11661 };
11662
11663 } // namespace
11664
11665 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11666                                  NonTrivialCUnionContext UseContext,
11667                                  unsigned NonTrivialKind) {
11668   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11669           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11670           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11671          "shouldn't be called if type doesn't have a non-trivial C union");
11672
11673   if ((NonTrivialKind & NTCUK_Init) &&
11674       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11675     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11676         .visit(QT, nullptr, false);
11677   if ((NonTrivialKind & NTCUK_Destruct) &&
11678       QT.hasNonTrivialToPrimitiveDestructCUnion())
11679     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11680         .visit(QT, nullptr, false);
11681   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11682     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11683         .visit(QT, nullptr, false);
11684 }
11685
11686 /// AddInitializerToDecl - Adds the initializer Init to the
11687 /// declaration dcl. If DirectInit is true, this is C++ direct
11688 /// initialization rather than copy initialization.
11689 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11690   // If there is no declaration, there was an error parsing it.  Just ignore
11691   // the initializer.
11692   if (!RealDecl || RealDecl->isInvalidDecl()) {
11693     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11694     return;
11695   }
11696
11697   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11698     // Pure-specifiers are handled in ActOnPureSpecifier.
11699     Diag(Method->getLocation(), diag::err_member_function_initialization)
11700       << Method->getDeclName() << Init->getSourceRange();
11701     Method->setInvalidDecl();
11702     return;
11703   }
11704
11705   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11706   if (!VDecl) {
11707     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11708     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11709     RealDecl->setInvalidDecl();
11710     return;
11711   }
11712
11713   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11714   if (VDecl->getType()->isUndeducedType()) {
11715     // Attempt typo correction early so that the type of the init expression can
11716     // be deduced based on the chosen correction if the original init contains a
11717     // TypoExpr.
11718     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11719     if (!Res.isUsable()) {
11720       RealDecl->setInvalidDecl();
11721       return;
11722     }
11723     Init = Res.get();
11724
11725     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11726       return;
11727   }
11728
11729   // dllimport cannot be used on variable definitions.
11730   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11731     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11732     VDecl->setInvalidDecl();
11733     return;
11734   }
11735
11736   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11737     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11738     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11739     VDecl->setInvalidDecl();
11740     return;
11741   }
11742
11743   if (!VDecl->getType()->isDependentType()) {
11744     // A definition must end up with a complete type, which means it must be
11745     // complete with the restriction that an array type might be completed by
11746     // the initializer; note that later code assumes this restriction.
11747     QualType BaseDeclType = VDecl->getType();
11748     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11749       BaseDeclType = Array->getElementType();
11750     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11751                             diag::err_typecheck_decl_incomplete_type)) {
11752       RealDecl->setInvalidDecl();
11753       return;
11754     }
11755
11756     // The variable can not have an abstract class type.
11757     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11758                                diag::err_abstract_type_in_decl,
11759                                AbstractVariableType))
11760       VDecl->setInvalidDecl();
11761   }
11762
11763   // If adding the initializer will turn this declaration into a definition,
11764   // and we already have a definition for this variable, diagnose or otherwise
11765   // handle the situation.
11766   VarDecl *Def;
11767   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11768       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11769       !VDecl->isThisDeclarationADemotedDefinition() &&
11770       checkVarDeclRedefinition(Def, VDecl))
11771     return;
11772
11773   if (getLangOpts().CPlusPlus) {
11774     // C++ [class.static.data]p4
11775     //   If a static data member is of const integral or const
11776     //   enumeration type, its declaration in the class definition can
11777     //   specify a constant-initializer which shall be an integral
11778     //   constant expression (5.19). In that case, the member can appear
11779     //   in integral constant expressions. The member shall still be
11780     //   defined in a namespace scope if it is used in the program and the
11781     //   namespace scope definition shall not contain an initializer.
11782     //
11783     // We already performed a redefinition check above, but for static
11784     // data members we also need to check whether there was an in-class
11785     // declaration with an initializer.
11786     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11787       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11788           << VDecl->getDeclName();
11789       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11790            diag::note_previous_initializer)
11791           << 0;
11792       return;
11793     }
11794
11795     if (VDecl->hasLocalStorage())
11796       setFunctionHasBranchProtectedScope();
11797
11798     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11799       VDecl->setInvalidDecl();
11800       return;
11801     }
11802   }
11803
11804   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11805   // a kernel function cannot be initialized."
11806   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11807     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11808     VDecl->setInvalidDecl();
11809     return;
11810   }
11811
11812   // Get the decls type and save a reference for later, since
11813   // CheckInitializerTypes may change it.
11814   QualType DclT = VDecl->getType(), SavT = DclT;
11815
11816   // Expressions default to 'id' when we're in a debugger
11817   // and we are assigning it to a variable of Objective-C pointer type.
11818   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11819       Init->getType() == Context.UnknownAnyTy) {
11820     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11821     if (Result.isInvalid()) {
11822       VDecl->setInvalidDecl();
11823       return;
11824     }
11825     Init = Result.get();
11826   }
11827
11828   // Perform the initialization.
11829   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11830   if (!VDecl->isInvalidDecl()) {
11831     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11832     InitializationKind Kind = InitializationKind::CreateForInit(
11833         VDecl->getLocation(), DirectInit, Init);
11834
11835     MultiExprArg Args = Init;
11836     if (CXXDirectInit)
11837       Args = MultiExprArg(CXXDirectInit->getExprs(),
11838                           CXXDirectInit->getNumExprs());
11839
11840     // Try to correct any TypoExprs in the initialization arguments.
11841     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11842       ExprResult Res = CorrectDelayedTyposInExpr(
11843           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11844             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11845             return Init.Failed() ? ExprError() : E;
11846           });
11847       if (Res.isInvalid()) {
11848         VDecl->setInvalidDecl();
11849       } else if (Res.get() != Args[Idx]) {
11850         Args[Idx] = Res.get();
11851       }
11852     }
11853     if (VDecl->isInvalidDecl())
11854       return;
11855
11856     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11857                                    /*TopLevelOfInitList=*/false,
11858                                    /*TreatUnavailableAsInvalid=*/false);
11859     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11860     if (Result.isInvalid()) {
11861       VDecl->setInvalidDecl();
11862       return;
11863     }
11864
11865     Init = Result.getAs<Expr>();
11866   }
11867
11868   // Check for self-references within variable initializers.
11869   // Variables declared within a function/method body (except for references)
11870   // are handled by a dataflow analysis.
11871   // This is undefined behavior in C++, but valid in C.
11872   if (getLangOpts().CPlusPlus) {
11873     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11874         VDecl->getType()->isReferenceType()) {
11875       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11876     }
11877   }
11878
11879   // If the type changed, it means we had an incomplete type that was
11880   // completed by the initializer. For example:
11881   //   int ary[] = { 1, 3, 5 };
11882   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11883   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11884     VDecl->setType(DclT);
11885
11886   if (!VDecl->isInvalidDecl()) {
11887     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11888
11889     if (VDecl->hasAttr<BlocksAttr>())
11890       checkRetainCycles(VDecl, Init);
11891
11892     // It is safe to assign a weak reference into a strong variable.
11893     // Although this code can still have problems:
11894     //   id x = self.weakProp;
11895     //   id y = self.weakProp;
11896     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11897     // paths through the function. This should be revisited if
11898     // -Wrepeated-use-of-weak is made flow-sensitive.
11899     if (FunctionScopeInfo *FSI = getCurFunction())
11900       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11901            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11902           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11903                            Init->getBeginLoc()))
11904         FSI->markSafeWeakUse(Init);
11905   }
11906
11907   // The initialization is usually a full-expression.
11908   //
11909   // FIXME: If this is a braced initialization of an aggregate, it is not
11910   // an expression, and each individual field initializer is a separate
11911   // full-expression. For instance, in:
11912   //
11913   //   struct Temp { ~Temp(); };
11914   //   struct S { S(Temp); };
11915   //   struct T { S a, b; } t = { Temp(), Temp() }
11916   //
11917   // we should destroy the first Temp before constructing the second.
11918   ExprResult Result =
11919       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11920                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11921   if (Result.isInvalid()) {
11922     VDecl->setInvalidDecl();
11923     return;
11924   }
11925   Init = Result.get();
11926
11927   // Attach the initializer to the decl.
11928   VDecl->setInit(Init);
11929
11930   if (VDecl->isLocalVarDecl()) {
11931     // Don't check the initializer if the declaration is malformed.
11932     if (VDecl->isInvalidDecl()) {
11933       // do nothing
11934
11935     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11936     // This is true even in C++ for OpenCL.
11937     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11938       CheckForConstantInitializer(Init, DclT);
11939
11940     // Otherwise, C++ does not restrict the initializer.
11941     } else if (getLangOpts().CPlusPlus) {
11942       // do nothing
11943
11944     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11945     // static storage duration shall be constant expressions or string literals.
11946     } else if (VDecl->getStorageClass() == SC_Static) {
11947       CheckForConstantInitializer(Init, DclT);
11948
11949     // C89 is stricter than C99 for aggregate initializers.
11950     // C89 6.5.7p3: All the expressions [...] in an initializer list
11951     // for an object that has aggregate or union type shall be
11952     // constant expressions.
11953     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11954                isa<InitListExpr>(Init)) {
11955       const Expr *Culprit;
11956       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11957         Diag(Culprit->getExprLoc(),
11958              diag::ext_aggregate_init_not_constant)
11959           << Culprit->getSourceRange();
11960       }
11961     }
11962
11963     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11964       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11965         if (VDecl->hasLocalStorage())
11966           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11967   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11968              VDecl->getLexicalDeclContext()->isRecord()) {
11969     // This is an in-class initialization for a static data member, e.g.,
11970     //
11971     // struct S {
11972     //   static const int value = 17;
11973     // };
11974
11975     // C++ [class.mem]p4:
11976     //   A member-declarator can contain a constant-initializer only
11977     //   if it declares a static member (9.4) of const integral or
11978     //   const enumeration type, see 9.4.2.
11979     //
11980     // C++11 [class.static.data]p3:
11981     //   If a non-volatile non-inline const static data member is of integral
11982     //   or enumeration type, its declaration in the class definition can
11983     //   specify a brace-or-equal-initializer in which every initializer-clause
11984     //   that is an assignment-expression is a constant expression. A static
11985     //   data member of literal type can be declared in the class definition
11986     //   with the constexpr specifier; if so, its declaration shall specify a
11987     //   brace-or-equal-initializer in which every initializer-clause that is
11988     //   an assignment-expression is a constant expression.
11989
11990     // Do nothing on dependent types.
11991     if (DclT->isDependentType()) {
11992
11993     // Allow any 'static constexpr' members, whether or not they are of literal
11994     // type. We separately check that every constexpr variable is of literal
11995     // type.
11996     } else if (VDecl->isConstexpr()) {
11997
11998     // Require constness.
11999     } else if (!DclT.isConstQualified()) {
12000       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12001         << Init->getSourceRange();
12002       VDecl->setInvalidDecl();
12003
12004     // We allow integer constant expressions in all cases.
12005     } else if (DclT->isIntegralOrEnumerationType()) {
12006       // Check whether the expression is a constant expression.
12007       SourceLocation Loc;
12008       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12009         // In C++11, a non-constexpr const static data member with an
12010         // in-class initializer cannot be volatile.
12011         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12012       else if (Init->isValueDependent())
12013         ; // Nothing to check.
12014       else if (Init->isIntegerConstantExpr(Context, &Loc))
12015         ; // Ok, it's an ICE!
12016       else if (Init->getType()->isScopedEnumeralType() &&
12017                Init->isCXX11ConstantExpr(Context))
12018         ; // Ok, it is a scoped-enum constant expression.
12019       else if (Init->isEvaluatable(Context)) {
12020         // If we can constant fold the initializer through heroics, accept it,
12021         // but report this as a use of an extension for -pedantic.
12022         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12023           << Init->getSourceRange();
12024       } else {
12025         // Otherwise, this is some crazy unknown case.  Report the issue at the
12026         // location provided by the isIntegerConstantExpr failed check.
12027         Diag(Loc, diag::err_in_class_initializer_non_constant)
12028           << Init->getSourceRange();
12029         VDecl->setInvalidDecl();
12030       }
12031
12032     // We allow foldable floating-point constants as an extension.
12033     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12034       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12035       // it anyway and provide a fixit to add the 'constexpr'.
12036       if (getLangOpts().CPlusPlus11) {
12037         Diag(VDecl->getLocation(),
12038              diag::ext_in_class_initializer_float_type_cxx11)
12039             << DclT << Init->getSourceRange();
12040         Diag(VDecl->getBeginLoc(),
12041              diag::note_in_class_initializer_float_type_cxx11)
12042             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12043       } else {
12044         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12045           << DclT << Init->getSourceRange();
12046
12047         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12048           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12049             << Init->getSourceRange();
12050           VDecl->setInvalidDecl();
12051         }
12052       }
12053
12054     // Suggest adding 'constexpr' in C++11 for literal types.
12055     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12056       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12057           << DclT << Init->getSourceRange()
12058           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12059       VDecl->setConstexpr(true);
12060
12061     } else {
12062       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12063         << DclT << Init->getSourceRange();
12064       VDecl->setInvalidDecl();
12065     }
12066   } else if (VDecl->isFileVarDecl()) {
12067     // In C, extern is typically used to avoid tentative definitions when
12068     // declaring variables in headers, but adding an intializer makes it a
12069     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12070     // In C++, extern is often used to give implictly static const variables
12071     // external linkage, so don't warn in that case. If selectany is present,
12072     // this might be header code intended for C and C++ inclusion, so apply the
12073     // C++ rules.
12074     if (VDecl->getStorageClass() == SC_Extern &&
12075         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12076          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12077         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12078         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12079       Diag(VDecl->getLocation(), diag::warn_extern_init);
12080
12081     // In Microsoft C++ mode, a const variable defined in namespace scope has
12082     // external linkage by default if the variable is declared with
12083     // __declspec(dllexport).
12084     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12085         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12086         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12087       VDecl->setStorageClass(SC_Extern);
12088
12089     // C99 6.7.8p4. All file scoped initializers need to be constant.
12090     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12091       CheckForConstantInitializer(Init, DclT);
12092   }
12093
12094   QualType InitType = Init->getType();
12095   if (!InitType.isNull() &&
12096       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12097        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12098     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12099
12100   // We will represent direct-initialization similarly to copy-initialization:
12101   //    int x(1);  -as-> int x = 1;
12102   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12103   //
12104   // Clients that want to distinguish between the two forms, can check for
12105   // direct initializer using VarDecl::getInitStyle().
12106   // A major benefit is that clients that don't particularly care about which
12107   // exactly form was it (like the CodeGen) can handle both cases without
12108   // special case code.
12109
12110   // C++ 8.5p11:
12111   // The form of initialization (using parentheses or '=') is generally
12112   // insignificant, but does matter when the entity being initialized has a
12113   // class type.
12114   if (CXXDirectInit) {
12115     assert(DirectInit && "Call-style initializer must be direct init.");
12116     VDecl->setInitStyle(VarDecl::CallInit);
12117   } else if (DirectInit) {
12118     // This must be list-initialization. No other way is direct-initialization.
12119     VDecl->setInitStyle(VarDecl::ListInit);
12120   }
12121
12122   CheckCompleteVariableDeclaration(VDecl);
12123 }
12124
12125 /// ActOnInitializerError - Given that there was an error parsing an
12126 /// initializer for the given declaration, try to return to some form
12127 /// of sanity.
12128 void Sema::ActOnInitializerError(Decl *D) {
12129   // Our main concern here is re-establishing invariants like "a
12130   // variable's type is either dependent or complete".
12131   if (!D || D->isInvalidDecl()) return;
12132
12133   VarDecl *VD = dyn_cast<VarDecl>(D);
12134   if (!VD) return;
12135
12136   // Bindings are not usable if we can't make sense of the initializer.
12137   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12138     for (auto *BD : DD->bindings())
12139       BD->setInvalidDecl();
12140
12141   // Auto types are meaningless if we can't make sense of the initializer.
12142   if (ParsingInitForAutoVars.count(D)) {
12143     D->setInvalidDecl();
12144     return;
12145   }
12146
12147   QualType Ty = VD->getType();
12148   if (Ty->isDependentType()) return;
12149
12150   // Require a complete type.
12151   if (RequireCompleteType(VD->getLocation(),
12152                           Context.getBaseElementType(Ty),
12153                           diag::err_typecheck_decl_incomplete_type)) {
12154     VD->setInvalidDecl();
12155     return;
12156   }
12157
12158   // Require a non-abstract type.
12159   if (RequireNonAbstractType(VD->getLocation(), Ty,
12160                              diag::err_abstract_type_in_decl,
12161                              AbstractVariableType)) {
12162     VD->setInvalidDecl();
12163     return;
12164   }
12165
12166   // Don't bother complaining about constructors or destructors,
12167   // though.
12168 }
12169
12170 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12171   // If there is no declaration, there was an error parsing it. Just ignore it.
12172   if (!RealDecl)
12173     return;
12174
12175   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12176     QualType Type = Var->getType();
12177
12178     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12179     if (isa<DecompositionDecl>(RealDecl)) {
12180       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12181       Var->setInvalidDecl();
12182       return;
12183     }
12184
12185     if (Type->isUndeducedType() &&
12186         DeduceVariableDeclarationType(Var, false, nullptr))
12187       return;
12188
12189     // C++11 [class.static.data]p3: A static data member can be declared with
12190     // the constexpr specifier; if so, its declaration shall specify
12191     // a brace-or-equal-initializer.
12192     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12193     // the definition of a variable [...] or the declaration of a static data
12194     // member.
12195     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12196         !Var->isThisDeclarationADemotedDefinition()) {
12197       if (Var->isStaticDataMember()) {
12198         // C++1z removes the relevant rule; the in-class declaration is always
12199         // a definition there.
12200         if (!getLangOpts().CPlusPlus17 &&
12201             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12202           Diag(Var->getLocation(),
12203                diag::err_constexpr_static_mem_var_requires_init)
12204             << Var->getDeclName();
12205           Var->setInvalidDecl();
12206           return;
12207         }
12208       } else {
12209         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12210         Var->setInvalidDecl();
12211         return;
12212       }
12213     }
12214
12215     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12216     // be initialized.
12217     if (!Var->isInvalidDecl() &&
12218         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12219         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12220       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12221       Var->setInvalidDecl();
12222       return;
12223     }
12224
12225     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12226     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12227         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12228       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12229                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12230
12231
12232     switch (DefKind) {
12233     case VarDecl::Definition:
12234       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12235         break;
12236
12237       // We have an out-of-line definition of a static data member
12238       // that has an in-class initializer, so we type-check this like
12239       // a declaration.
12240       //
12241       LLVM_FALLTHROUGH;
12242
12243     case VarDecl::DeclarationOnly:
12244       // It's only a declaration.
12245
12246       // Block scope. C99 6.7p7: If an identifier for an object is
12247       // declared with no linkage (C99 6.2.2p6), the type for the
12248       // object shall be complete.
12249       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12250           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12251           RequireCompleteType(Var->getLocation(), Type,
12252                               diag::err_typecheck_decl_incomplete_type))
12253         Var->setInvalidDecl();
12254
12255       // Make sure that the type is not abstract.
12256       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12257           RequireNonAbstractType(Var->getLocation(), Type,
12258                                  diag::err_abstract_type_in_decl,
12259                                  AbstractVariableType))
12260         Var->setInvalidDecl();
12261       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12262           Var->getStorageClass() == SC_PrivateExtern) {
12263         Diag(Var->getLocation(), diag::warn_private_extern);
12264         Diag(Var->getLocation(), diag::note_private_extern);
12265       }
12266
12267       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12268           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12269         ExternalDeclarations.push_back(Var);
12270
12271       return;
12272
12273     case VarDecl::TentativeDefinition:
12274       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12275       // object that has file scope without an initializer, and without a
12276       // storage-class specifier or with the storage-class specifier "static",
12277       // constitutes a tentative definition. Note: A tentative definition with
12278       // external linkage is valid (C99 6.2.2p5).
12279       if (!Var->isInvalidDecl()) {
12280         if (const IncompleteArrayType *ArrayT
12281                                     = Context.getAsIncompleteArrayType(Type)) {
12282           if (RequireCompleteType(Var->getLocation(),
12283                                   ArrayT->getElementType(),
12284                                   diag::err_illegal_decl_array_incomplete_type))
12285             Var->setInvalidDecl();
12286         } else if (Var->getStorageClass() == SC_Static) {
12287           // C99 6.9.2p3: If the declaration of an identifier for an object is
12288           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12289           // declared type shall not be an incomplete type.
12290           // NOTE: code such as the following
12291           //     static struct s;
12292           //     struct s { int a; };
12293           // is accepted by gcc. Hence here we issue a warning instead of
12294           // an error and we do not invalidate the static declaration.
12295           // NOTE: to avoid multiple warnings, only check the first declaration.
12296           if (Var->isFirstDecl())
12297             RequireCompleteType(Var->getLocation(), Type,
12298                                 diag::ext_typecheck_decl_incomplete_type);
12299         }
12300       }
12301
12302       // Record the tentative definition; we're done.
12303       if (!Var->isInvalidDecl())
12304         TentativeDefinitions.push_back(Var);
12305       return;
12306     }
12307
12308     // Provide a specific diagnostic for uninitialized variable
12309     // definitions with incomplete array type.
12310     if (Type->isIncompleteArrayType()) {
12311       Diag(Var->getLocation(),
12312            diag::err_typecheck_incomplete_array_needs_initializer);
12313       Var->setInvalidDecl();
12314       return;
12315     }
12316
12317     // Provide a specific diagnostic for uninitialized variable
12318     // definitions with reference type.
12319     if (Type->isReferenceType()) {
12320       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12321         << Var->getDeclName()
12322         << SourceRange(Var->getLocation(), Var->getLocation());
12323       Var->setInvalidDecl();
12324       return;
12325     }
12326
12327     // Do not attempt to type-check the default initializer for a
12328     // variable with dependent type.
12329     if (Type->isDependentType())
12330       return;
12331
12332     if (Var->isInvalidDecl())
12333       return;
12334
12335     if (!Var->hasAttr<AliasAttr>()) {
12336       if (RequireCompleteType(Var->getLocation(),
12337                               Context.getBaseElementType(Type),
12338                               diag::err_typecheck_decl_incomplete_type)) {
12339         Var->setInvalidDecl();
12340         return;
12341       }
12342     } else {
12343       return;
12344     }
12345
12346     // The variable can not have an abstract class type.
12347     if (RequireNonAbstractType(Var->getLocation(), Type,
12348                                diag::err_abstract_type_in_decl,
12349                                AbstractVariableType)) {
12350       Var->setInvalidDecl();
12351       return;
12352     }
12353
12354     // Check for jumps past the implicit initializer.  C++0x
12355     // clarifies that this applies to a "variable with automatic
12356     // storage duration", not a "local variable".
12357     // C++11 [stmt.dcl]p3
12358     //   A program that jumps from a point where a variable with automatic
12359     //   storage duration is not in scope to a point where it is in scope is
12360     //   ill-formed unless the variable has scalar type, class type with a
12361     //   trivial default constructor and a trivial destructor, a cv-qualified
12362     //   version of one of these types, or an array of one of the preceding
12363     //   types and is declared without an initializer.
12364     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12365       if (const RecordType *Record
12366             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12367         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12368         // Mark the function (if we're in one) for further checking even if the
12369         // looser rules of C++11 do not require such checks, so that we can
12370         // diagnose incompatibilities with C++98.
12371         if (!CXXRecord->isPOD())
12372           setFunctionHasBranchProtectedScope();
12373       }
12374     }
12375     // In OpenCL, we can't initialize objects in the __local address space,
12376     // even implicitly, so don't synthesize an implicit initializer.
12377     if (getLangOpts().OpenCL &&
12378         Var->getType().getAddressSpace() == LangAS::opencl_local)
12379       return;
12380     // C++03 [dcl.init]p9:
12381     //   If no initializer is specified for an object, and the
12382     //   object is of (possibly cv-qualified) non-POD class type (or
12383     //   array thereof), the object shall be default-initialized; if
12384     //   the object is of const-qualified type, the underlying class
12385     //   type shall have a user-declared default
12386     //   constructor. Otherwise, if no initializer is specified for
12387     //   a non- static object, the object and its subobjects, if
12388     //   any, have an indeterminate initial value); if the object
12389     //   or any of its subobjects are of const-qualified type, the
12390     //   program is ill-formed.
12391     // C++0x [dcl.init]p11:
12392     //   If no initializer is specified for an object, the object is
12393     //   default-initialized; [...].
12394     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12395     InitializationKind Kind
12396       = InitializationKind::CreateDefault(Var->getLocation());
12397
12398     InitializationSequence InitSeq(*this, Entity, Kind, None);
12399     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12400     if (Init.isInvalid())
12401       Var->setInvalidDecl();
12402     else if (Init.get()) {
12403       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12404       // This is important for template substitution.
12405       Var->setInitStyle(VarDecl::CallInit);
12406     }
12407
12408     CheckCompleteVariableDeclaration(Var);
12409   }
12410 }
12411
12412 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12413   // If there is no declaration, there was an error parsing it. Ignore it.
12414   if (!D)
12415     return;
12416
12417   VarDecl *VD = dyn_cast<VarDecl>(D);
12418   if (!VD) {
12419     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12420     D->setInvalidDecl();
12421     return;
12422   }
12423
12424   VD->setCXXForRangeDecl(true);
12425
12426   // for-range-declaration cannot be given a storage class specifier.
12427   int Error = -1;
12428   switch (VD->getStorageClass()) {
12429   case SC_None:
12430     break;
12431   case SC_Extern:
12432     Error = 0;
12433     break;
12434   case SC_Static:
12435     Error = 1;
12436     break;
12437   case SC_PrivateExtern:
12438     Error = 2;
12439     break;
12440   case SC_Auto:
12441     Error = 3;
12442     break;
12443   case SC_Register:
12444     Error = 4;
12445     break;
12446   }
12447   if (Error != -1) {
12448     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12449       << VD->getDeclName() << Error;
12450     D->setInvalidDecl();
12451   }
12452 }
12453
12454 StmtResult
12455 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12456                                  IdentifierInfo *Ident,
12457                                  ParsedAttributes &Attrs,
12458                                  SourceLocation AttrEnd) {
12459   // C++1y [stmt.iter]p1:
12460   //   A range-based for statement of the form
12461   //      for ( for-range-identifier : for-range-initializer ) statement
12462   //   is equivalent to
12463   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12464   DeclSpec DS(Attrs.getPool().getFactory());
12465
12466   const char *PrevSpec;
12467   unsigned DiagID;
12468   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12469                      getPrintingPolicy());
12470
12471   Declarator D(DS, DeclaratorContext::ForContext);
12472   D.SetIdentifier(Ident, IdentLoc);
12473   D.takeAttributes(Attrs, AttrEnd);
12474
12475   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12476                 IdentLoc);
12477   Decl *Var = ActOnDeclarator(S, D);
12478   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12479   FinalizeDeclaration(Var);
12480   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12481                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12482 }
12483
12484 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12485   if (var->isInvalidDecl()) return;
12486
12487   if (getLangOpts().OpenCL) {
12488     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12489     // initialiser
12490     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12491         !var->hasInit()) {
12492       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12493           << 1 /*Init*/;
12494       var->setInvalidDecl();
12495       return;
12496     }
12497   }
12498
12499   // In Objective-C, don't allow jumps past the implicit initialization of a
12500   // local retaining variable.
12501   if (getLangOpts().ObjC &&
12502       var->hasLocalStorage()) {
12503     switch (var->getType().getObjCLifetime()) {
12504     case Qualifiers::OCL_None:
12505     case Qualifiers::OCL_ExplicitNone:
12506     case Qualifiers::OCL_Autoreleasing:
12507       break;
12508
12509     case Qualifiers::OCL_Weak:
12510     case Qualifiers::OCL_Strong:
12511       setFunctionHasBranchProtectedScope();
12512       break;
12513     }
12514   }
12515
12516   if (var->hasLocalStorage() &&
12517       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12518     setFunctionHasBranchProtectedScope();
12519
12520   // Warn about externally-visible variables being defined without a
12521   // prior declaration.  We only want to do this for global
12522   // declarations, but we also specifically need to avoid doing it for
12523   // class members because the linkage of an anonymous class can
12524   // change if it's later given a typedef name.
12525   if (var->isThisDeclarationADefinition() &&
12526       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12527       var->isExternallyVisible() && var->hasLinkage() &&
12528       !var->isInline() && !var->getDescribedVarTemplate() &&
12529       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12530       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12531                                   var->getLocation())) {
12532     // Find a previous declaration that's not a definition.
12533     VarDecl *prev = var->getPreviousDecl();
12534     while (prev && prev->isThisDeclarationADefinition())
12535       prev = prev->getPreviousDecl();
12536
12537     if (!prev) {
12538       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12539       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12540           << /* variable */ 0;
12541     }
12542   }
12543
12544   // Cache the result of checking for constant initialization.
12545   Optional<bool> CacheHasConstInit;
12546   const Expr *CacheCulprit = nullptr;
12547   auto checkConstInit = [&]() mutable {
12548     if (!CacheHasConstInit)
12549       CacheHasConstInit = var->getInit()->isConstantInitializer(
12550             Context, var->getType()->isReferenceType(), &CacheCulprit);
12551     return *CacheHasConstInit;
12552   };
12553
12554   if (var->getTLSKind() == VarDecl::TLS_Static) {
12555     if (var->getType().isDestructedType()) {
12556       // GNU C++98 edits for __thread, [basic.start.term]p3:
12557       //   The type of an object with thread storage duration shall not
12558       //   have a non-trivial destructor.
12559       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12560       if (getLangOpts().CPlusPlus11)
12561         Diag(var->getLocation(), diag::note_use_thread_local);
12562     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12563       if (!checkConstInit()) {
12564         // GNU C++98 edits for __thread, [basic.start.init]p4:
12565         //   An object of thread storage duration shall not require dynamic
12566         //   initialization.
12567         // FIXME: Need strict checking here.
12568         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12569           << CacheCulprit->getSourceRange();
12570         if (getLangOpts().CPlusPlus11)
12571           Diag(var->getLocation(), diag::note_use_thread_local);
12572       }
12573     }
12574   }
12575
12576   // Apply section attributes and pragmas to global variables.
12577   bool GlobalStorage = var->hasGlobalStorage();
12578   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12579       !inTemplateInstantiation()) {
12580     PragmaStack<StringLiteral *> *Stack = nullptr;
12581     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12582     if (var->getType().isConstQualified())
12583       Stack = &ConstSegStack;
12584     else if (!var->getInit()) {
12585       Stack = &BSSSegStack;
12586       SectionFlags |= ASTContext::PSF_Write;
12587     } else {
12588       Stack = &DataSegStack;
12589       SectionFlags |= ASTContext::PSF_Write;
12590     }
12591     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12592       var->addAttr(SectionAttr::CreateImplicit(
12593           Context, Stack->CurrentValue->getString(),
12594           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12595           SectionAttr::Declspec_allocate));
12596     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12597       if (UnifySection(SA->getName(), SectionFlags, var))
12598         var->dropAttr<SectionAttr>();
12599
12600     // Apply the init_seg attribute if this has an initializer.  If the
12601     // initializer turns out to not be dynamic, we'll end up ignoring this
12602     // attribute.
12603     if (CurInitSeg && var->getInit())
12604       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12605                                                CurInitSegLoc,
12606                                                AttributeCommonInfo::AS_Pragma));
12607   }
12608
12609   // All the following checks are C++ only.
12610   if (!getLangOpts().CPlusPlus) {
12611       // If this variable must be emitted, add it as an initializer for the
12612       // current module.
12613      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12614        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12615      return;
12616   }
12617
12618   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12619     CheckCompleteDecompositionDeclaration(DD);
12620
12621   QualType type = var->getType();
12622   if (type->isDependentType()) return;
12623
12624   if (var->hasAttr<BlocksAttr>())
12625     getCurFunction()->addByrefBlockVar(var);
12626
12627   Expr *Init = var->getInit();
12628   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12629   QualType baseType = Context.getBaseElementType(type);
12630
12631   if (Init && !Init->isValueDependent()) {
12632     if (var->isConstexpr()) {
12633       SmallVector<PartialDiagnosticAt, 8> Notes;
12634       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12635         SourceLocation DiagLoc = var->getLocation();
12636         // If the note doesn't add any useful information other than a source
12637         // location, fold it into the primary diagnostic.
12638         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12639               diag::note_invalid_subexpr_in_const_expr) {
12640           DiagLoc = Notes[0].first;
12641           Notes.clear();
12642         }
12643         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12644           << var << Init->getSourceRange();
12645         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12646           Diag(Notes[I].first, Notes[I].second);
12647       }
12648     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12649       // Check whether the initializer of a const variable of integral or
12650       // enumeration type is an ICE now, since we can't tell whether it was
12651       // initialized by a constant expression if we check later.
12652       var->checkInitIsICE();
12653     }
12654
12655     // Don't emit further diagnostics about constexpr globals since they
12656     // were just diagnosed.
12657     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12658       // FIXME: Need strict checking in C++03 here.
12659       bool DiagErr = getLangOpts().CPlusPlus11
12660           ? !var->checkInitIsICE() : !checkConstInit();
12661       if (DiagErr) {
12662         auto *Attr = var->getAttr<ConstInitAttr>();
12663         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12664           << Init->getSourceRange();
12665         Diag(Attr->getLocation(),
12666              diag::note_declared_required_constant_init_here)
12667             << Attr->getRange() << Attr->isConstinit();
12668         if (getLangOpts().CPlusPlus11) {
12669           APValue Value;
12670           SmallVector<PartialDiagnosticAt, 8> Notes;
12671           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12672           for (auto &it : Notes)
12673             Diag(it.first, it.second);
12674         } else {
12675           Diag(CacheCulprit->getExprLoc(),
12676                diag::note_invalid_subexpr_in_const_expr)
12677               << CacheCulprit->getSourceRange();
12678         }
12679       }
12680     }
12681     else if (!var->isConstexpr() && IsGlobal &&
12682              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12683                                     var->getLocation())) {
12684       // Warn about globals which don't have a constant initializer.  Don't
12685       // warn about globals with a non-trivial destructor because we already
12686       // warned about them.
12687       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12688       if (!(RD && !RD->hasTrivialDestructor())) {
12689         if (!checkConstInit())
12690           Diag(var->getLocation(), diag::warn_global_constructor)
12691             << Init->getSourceRange();
12692       }
12693     }
12694   }
12695
12696   // Require the destructor.
12697   if (const RecordType *recordType = baseType->getAs<RecordType>())
12698     FinalizeVarWithDestructor(var, recordType);
12699
12700   // If this variable must be emitted, add it as an initializer for the current
12701   // module.
12702   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12703     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12704 }
12705
12706 /// Determines if a variable's alignment is dependent.
12707 static bool hasDependentAlignment(VarDecl *VD) {
12708   if (VD->getType()->isDependentType())
12709     return true;
12710   for (auto *I : VD->specific_attrs<AlignedAttr>())
12711     if (I->isAlignmentDependent())
12712       return true;
12713   return false;
12714 }
12715
12716 /// Check if VD needs to be dllexport/dllimport due to being in a
12717 /// dllexport/import function.
12718 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12719   assert(VD->isStaticLocal());
12720
12721   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12722
12723   // Find outermost function when VD is in lambda function.
12724   while (FD && !getDLLAttr(FD) &&
12725          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12726          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12727     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12728   }
12729
12730   if (!FD)
12731     return;
12732
12733   // Static locals inherit dll attributes from their function.
12734   if (Attr *A = getDLLAttr(FD)) {
12735     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12736     NewAttr->setInherited(true);
12737     VD->addAttr(NewAttr);
12738   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12739     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12740     NewAttr->setInherited(true);
12741     VD->addAttr(NewAttr);
12742
12743     // Export this function to enforce exporting this static variable even
12744     // if it is not used in this compilation unit.
12745     if (!FD->hasAttr<DLLExportAttr>())
12746       FD->addAttr(NewAttr);
12747
12748   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12749     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12750     NewAttr->setInherited(true);
12751     VD->addAttr(NewAttr);
12752   }
12753 }
12754
12755 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12756 /// any semantic actions necessary after any initializer has been attached.
12757 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12758   // Note that we are no longer parsing the initializer for this declaration.
12759   ParsingInitForAutoVars.erase(ThisDecl);
12760
12761   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12762   if (!VD)
12763     return;
12764
12765   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12766   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12767       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12768     if (PragmaClangBSSSection.Valid)
12769       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12770           Context, PragmaClangBSSSection.SectionName,
12771           PragmaClangBSSSection.PragmaLocation,
12772           AttributeCommonInfo::AS_Pragma));
12773     if (PragmaClangDataSection.Valid)
12774       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12775           Context, PragmaClangDataSection.SectionName,
12776           PragmaClangDataSection.PragmaLocation,
12777           AttributeCommonInfo::AS_Pragma));
12778     if (PragmaClangRodataSection.Valid)
12779       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12780           Context, PragmaClangRodataSection.SectionName,
12781           PragmaClangRodataSection.PragmaLocation,
12782           AttributeCommonInfo::AS_Pragma));
12783     if (PragmaClangRelroSection.Valid)
12784       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12785           Context, PragmaClangRelroSection.SectionName,
12786           PragmaClangRelroSection.PragmaLocation,
12787           AttributeCommonInfo::AS_Pragma));
12788   }
12789
12790   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12791     for (auto *BD : DD->bindings()) {
12792       FinalizeDeclaration(BD);
12793     }
12794   }
12795
12796   checkAttributesAfterMerging(*this, *VD);
12797
12798   // Perform TLS alignment check here after attributes attached to the variable
12799   // which may affect the alignment have been processed. Only perform the check
12800   // if the target has a maximum TLS alignment (zero means no constraints).
12801   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12802     // Protect the check so that it's not performed on dependent types and
12803     // dependent alignments (we can't determine the alignment in that case).
12804     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12805         !VD->isInvalidDecl()) {
12806       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12807       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12808         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12809           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12810           << (unsigned)MaxAlignChars.getQuantity();
12811       }
12812     }
12813   }
12814
12815   if (VD->isStaticLocal()) {
12816     CheckStaticLocalForDllExport(VD);
12817
12818     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12819       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12820       // function, only __shared__ variables or variables without any device
12821       // memory qualifiers may be declared with static storage class.
12822       // Note: It is unclear how a function-scope non-const static variable
12823       // without device memory qualifier is implemented, therefore only static
12824       // const variable without device memory qualifier is allowed.
12825       [&]() {
12826         if (!getLangOpts().CUDA)
12827           return;
12828         if (VD->hasAttr<CUDASharedAttr>())
12829           return;
12830         if (VD->getType().isConstQualified() &&
12831             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12832           return;
12833         if (CUDADiagIfDeviceCode(VD->getLocation(),
12834                                  diag::err_device_static_local_var)
12835             << CurrentCUDATarget())
12836           VD->setInvalidDecl();
12837       }();
12838     }
12839   }
12840
12841   // Perform check for initializers of device-side global variables.
12842   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12843   // 7.5). We must also apply the same checks to all __shared__
12844   // variables whether they are local or not. CUDA also allows
12845   // constant initializers for __constant__ and __device__ variables.
12846   if (getLangOpts().CUDA)
12847     checkAllowedCUDAInitializer(VD);
12848
12849   // Grab the dllimport or dllexport attribute off of the VarDecl.
12850   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12851
12852   // Imported static data members cannot be defined out-of-line.
12853   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12854     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12855         VD->isThisDeclarationADefinition()) {
12856       // We allow definitions of dllimport class template static data members
12857       // with a warning.
12858       CXXRecordDecl *Context =
12859         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12860       bool IsClassTemplateMember =
12861           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12862           Context->getDescribedClassTemplate();
12863
12864       Diag(VD->getLocation(),
12865            IsClassTemplateMember
12866                ? diag::warn_attribute_dllimport_static_field_definition
12867                : diag::err_attribute_dllimport_static_field_definition);
12868       Diag(IA->getLocation(), diag::note_attribute);
12869       if (!IsClassTemplateMember)
12870         VD->setInvalidDecl();
12871     }
12872   }
12873
12874   // dllimport/dllexport variables cannot be thread local, their TLS index
12875   // isn't exported with the variable.
12876   if (DLLAttr && VD->getTLSKind()) {
12877     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12878     if (F && getDLLAttr(F)) {
12879       assert(VD->isStaticLocal());
12880       // But if this is a static local in a dlimport/dllexport function, the
12881       // function will never be inlined, which means the var would never be
12882       // imported, so having it marked import/export is safe.
12883     } else {
12884       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12885                                                                     << DLLAttr;
12886       VD->setInvalidDecl();
12887     }
12888   }
12889
12890   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12891     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12892       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12893       VD->dropAttr<UsedAttr>();
12894     }
12895   }
12896
12897   const DeclContext *DC = VD->getDeclContext();
12898   // If there's a #pragma GCC visibility in scope, and this isn't a class
12899   // member, set the visibility of this variable.
12900   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12901     AddPushedVisibilityAttribute(VD);
12902
12903   // FIXME: Warn on unused var template partial specializations.
12904   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12905     MarkUnusedFileScopedDecl(VD);
12906
12907   // Now we have parsed the initializer and can update the table of magic
12908   // tag values.
12909   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12910       !VD->getType()->isIntegralOrEnumerationType())
12911     return;
12912
12913   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12914     const Expr *MagicValueExpr = VD->getInit();
12915     if (!MagicValueExpr) {
12916       continue;
12917     }
12918     llvm::APSInt MagicValueInt;
12919     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12920       Diag(I->getRange().getBegin(),
12921            diag::err_type_tag_for_datatype_not_ice)
12922         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12923       continue;
12924     }
12925     if (MagicValueInt.getActiveBits() > 64) {
12926       Diag(I->getRange().getBegin(),
12927            diag::err_type_tag_for_datatype_too_large)
12928         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12929       continue;
12930     }
12931     uint64_t MagicValue = MagicValueInt.getZExtValue();
12932     RegisterTypeTagForDatatype(I->getArgumentKind(),
12933                                MagicValue,
12934                                I->getMatchingCType(),
12935                                I->getLayoutCompatible(),
12936                                I->getMustBeNull());
12937   }
12938 }
12939
12940 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12941   auto *VD = dyn_cast<VarDecl>(DD);
12942   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12943 }
12944
12945 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12946                                                    ArrayRef<Decl *> Group) {
12947   SmallVector<Decl*, 8> Decls;
12948
12949   if (DS.isTypeSpecOwned())
12950     Decls.push_back(DS.getRepAsDecl());
12951
12952   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12953   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12954   bool DiagnosedMultipleDecomps = false;
12955   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12956   bool DiagnosedNonDeducedAuto = false;
12957
12958   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12959     if (Decl *D = Group[i]) {
12960       // For declarators, there are some additional syntactic-ish checks we need
12961       // to perform.
12962       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12963         if (!FirstDeclaratorInGroup)
12964           FirstDeclaratorInGroup = DD;
12965         if (!FirstDecompDeclaratorInGroup)
12966           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12967         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12968             !hasDeducedAuto(DD))
12969           FirstNonDeducedAutoInGroup = DD;
12970
12971         if (FirstDeclaratorInGroup != DD) {
12972           // A decomposition declaration cannot be combined with any other
12973           // declaration in the same group.
12974           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12975             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12976                  diag::err_decomp_decl_not_alone)
12977                 << FirstDeclaratorInGroup->getSourceRange()
12978                 << DD->getSourceRange();
12979             DiagnosedMultipleDecomps = true;
12980           }
12981
12982           // A declarator that uses 'auto' in any way other than to declare a
12983           // variable with a deduced type cannot be combined with any other
12984           // declarator in the same group.
12985           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12986             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12987                  diag::err_auto_non_deduced_not_alone)
12988                 << FirstNonDeducedAutoInGroup->getType()
12989                        ->hasAutoForTrailingReturnType()
12990                 << FirstDeclaratorInGroup->getSourceRange()
12991                 << DD->getSourceRange();
12992             DiagnosedNonDeducedAuto = true;
12993           }
12994         }
12995       }
12996
12997       Decls.push_back(D);
12998     }
12999   }
13000
13001   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13002     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13003       handleTagNumbering(Tag, S);
13004       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13005           getLangOpts().CPlusPlus)
13006         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13007     }
13008   }
13009
13010   return BuildDeclaratorGroup(Decls);
13011 }
13012
13013 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13014 /// group, performing any necessary semantic checking.
13015 Sema::DeclGroupPtrTy
13016 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13017   // C++14 [dcl.spec.auto]p7: (DR1347)
13018   //   If the type that replaces the placeholder type is not the same in each
13019   //   deduction, the program is ill-formed.
13020   if (Group.size() > 1) {
13021     QualType Deduced;
13022     VarDecl *DeducedDecl = nullptr;
13023     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13024       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13025       if (!D || D->isInvalidDecl())
13026         break;
13027       DeducedType *DT = D->getType()->getContainedDeducedType();
13028       if (!DT || DT->getDeducedType().isNull())
13029         continue;
13030       if (Deduced.isNull()) {
13031         Deduced = DT->getDeducedType();
13032         DeducedDecl = D;
13033       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13034         auto *AT = dyn_cast<AutoType>(DT);
13035         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13036              diag::err_auto_different_deductions)
13037           << (AT ? (unsigned)AT->getKeyword() : 3)
13038           << Deduced << DeducedDecl->getDeclName()
13039           << DT->getDeducedType() << D->getDeclName()
13040           << DeducedDecl->getInit()->getSourceRange()
13041           << D->getInit()->getSourceRange();
13042         D->setInvalidDecl();
13043         break;
13044       }
13045     }
13046   }
13047
13048   ActOnDocumentableDecls(Group);
13049
13050   return DeclGroupPtrTy::make(
13051       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13052 }
13053
13054 void Sema::ActOnDocumentableDecl(Decl *D) {
13055   ActOnDocumentableDecls(D);
13056 }
13057
13058 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13059   // Don't parse the comment if Doxygen diagnostics are ignored.
13060   if (Group.empty() || !Group[0])
13061     return;
13062
13063   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13064                       Group[0]->getLocation()) &&
13065       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13066                       Group[0]->getLocation()))
13067     return;
13068
13069   if (Group.size() >= 2) {
13070     // This is a decl group.  Normally it will contain only declarations
13071     // produced from declarator list.  But in case we have any definitions or
13072     // additional declaration references:
13073     //   'typedef struct S {} S;'
13074     //   'typedef struct S *S;'
13075     //   'struct S *pS;'
13076     // FinalizeDeclaratorGroup adds these as separate declarations.
13077     Decl *MaybeTagDecl = Group[0];
13078     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13079       Group = Group.slice(1);
13080     }
13081   }
13082
13083   // FIMXE: We assume every Decl in the group is in the same file.
13084   // This is false when preprocessor constructs the group from decls in
13085   // different files (e. g. macros or #include).
13086   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13087 }
13088
13089 /// Common checks for a parameter-declaration that should apply to both function
13090 /// parameters and non-type template parameters.
13091 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13092   // Check that there are no default arguments inside the type of this
13093   // parameter.
13094   if (getLangOpts().CPlusPlus)
13095     CheckExtraCXXDefaultArguments(D);
13096
13097   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13098   if (D.getCXXScopeSpec().isSet()) {
13099     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13100       << D.getCXXScopeSpec().getRange();
13101   }
13102
13103   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13104   // simple identifier except [...irrelevant cases...].
13105   switch (D.getName().getKind()) {
13106   case UnqualifiedIdKind::IK_Identifier:
13107     break;
13108
13109   case UnqualifiedIdKind::IK_OperatorFunctionId:
13110   case UnqualifiedIdKind::IK_ConversionFunctionId:
13111   case UnqualifiedIdKind::IK_LiteralOperatorId:
13112   case UnqualifiedIdKind::IK_ConstructorName:
13113   case UnqualifiedIdKind::IK_DestructorName:
13114   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13115   case UnqualifiedIdKind::IK_DeductionGuideName:
13116     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13117       << GetNameForDeclarator(D).getName();
13118     break;
13119
13120   case UnqualifiedIdKind::IK_TemplateId:
13121   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13122     // GetNameForDeclarator would not produce a useful name in this case.
13123     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13124     break;
13125   }
13126 }
13127
13128 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13129 /// to introduce parameters into function prototype scope.
13130 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13131   const DeclSpec &DS = D.getDeclSpec();
13132
13133   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13134
13135   // C++03 [dcl.stc]p2 also permits 'auto'.
13136   StorageClass SC = SC_None;
13137   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13138     SC = SC_Register;
13139     // In C++11, the 'register' storage class specifier is deprecated.
13140     // In C++17, it is not allowed, but we tolerate it as an extension.
13141     if (getLangOpts().CPlusPlus11) {
13142       Diag(DS.getStorageClassSpecLoc(),
13143            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13144                                      : diag::warn_deprecated_register)
13145         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13146     }
13147   } else if (getLangOpts().CPlusPlus &&
13148              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13149     SC = SC_Auto;
13150   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13151     Diag(DS.getStorageClassSpecLoc(),
13152          diag::err_invalid_storage_class_in_func_decl);
13153     D.getMutableDeclSpec().ClearStorageClassSpecs();
13154   }
13155
13156   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13157     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13158       << DeclSpec::getSpecifierName(TSCS);
13159   if (DS.isInlineSpecified())
13160     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13161         << getLangOpts().CPlusPlus17;
13162   if (DS.hasConstexprSpecifier())
13163     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13164         << 0 << D.getDeclSpec().getConstexprSpecifier();
13165
13166   DiagnoseFunctionSpecifiers(DS);
13167
13168   CheckFunctionOrTemplateParamDeclarator(S, D);
13169
13170   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13171   QualType parmDeclType = TInfo->getType();
13172
13173   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13174   IdentifierInfo *II = D.getIdentifier();
13175   if (II) {
13176     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13177                    ForVisibleRedeclaration);
13178     LookupName(R, S);
13179     if (R.isSingleResult()) {
13180       NamedDecl *PrevDecl = R.getFoundDecl();
13181       if (PrevDecl->isTemplateParameter()) {
13182         // Maybe we will complain about the shadowed template parameter.
13183         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13184         // Just pretend that we didn't see the previous declaration.
13185         PrevDecl = nullptr;
13186       } else if (S->isDeclScope(PrevDecl)) {
13187         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13188         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13189
13190         // Recover by removing the name
13191         II = nullptr;
13192         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13193         D.setInvalidType(true);
13194       }
13195     }
13196   }
13197
13198   // Temporarily put parameter variables in the translation unit, not
13199   // the enclosing context.  This prevents them from accidentally
13200   // looking like class members in C++.
13201   ParmVarDecl *New =
13202       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13203                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13204
13205   if (D.isInvalidType())
13206     New->setInvalidDecl();
13207
13208   assert(S->isFunctionPrototypeScope());
13209   assert(S->getFunctionPrototypeDepth() >= 1);
13210   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13211                     S->getNextFunctionPrototypeIndex());
13212
13213   // Add the parameter declaration into this scope.
13214   S->AddDecl(New);
13215   if (II)
13216     IdResolver.AddDecl(New);
13217
13218   ProcessDeclAttributes(S, New, D);
13219
13220   if (D.getDeclSpec().isModulePrivateSpecified())
13221     Diag(New->getLocation(), diag::err_module_private_local)
13222       << 1 << New->getDeclName()
13223       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13224       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13225
13226   if (New->hasAttr<BlocksAttr>()) {
13227     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13228   }
13229
13230   if (getLangOpts().OpenCL)
13231     deduceOpenCLAddressSpace(New);
13232
13233   return New;
13234 }
13235
13236 /// Synthesizes a variable for a parameter arising from a
13237 /// typedef.
13238 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13239                                               SourceLocation Loc,
13240                                               QualType T) {
13241   /* FIXME: setting StartLoc == Loc.
13242      Would it be worth to modify callers so as to provide proper source
13243      location for the unnamed parameters, embedding the parameter's type? */
13244   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13245                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13246                                            SC_None, nullptr);
13247   Param->setImplicit();
13248   return Param;
13249 }
13250
13251 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13252   // Don't diagnose unused-parameter errors in template instantiations; we
13253   // will already have done so in the template itself.
13254   if (inTemplateInstantiation())
13255     return;
13256
13257   for (const ParmVarDecl *Parameter : Parameters) {
13258     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13259         !Parameter->hasAttr<UnusedAttr>()) {
13260       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13261         << Parameter->getDeclName();
13262     }
13263   }
13264 }
13265
13266 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13267     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13268   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13269     return;
13270
13271   // Warn if the return value is pass-by-value and larger than the specified
13272   // threshold.
13273   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13274     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13275     if (Size > LangOpts.NumLargeByValueCopy)
13276       Diag(D->getLocation(), diag::warn_return_value_size)
13277           << D->getDeclName() << Size;
13278   }
13279
13280   // Warn if any parameter is pass-by-value and larger than the specified
13281   // threshold.
13282   for (const ParmVarDecl *Parameter : Parameters) {
13283     QualType T = Parameter->getType();
13284     if (T->isDependentType() || !T.isPODType(Context))
13285       continue;
13286     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13287     if (Size > LangOpts.NumLargeByValueCopy)
13288       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13289           << Parameter->getDeclName() << Size;
13290   }
13291 }
13292
13293 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13294                                   SourceLocation NameLoc, IdentifierInfo *Name,
13295                                   QualType T, TypeSourceInfo *TSInfo,
13296                                   StorageClass SC) {
13297   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13298   if (getLangOpts().ObjCAutoRefCount &&
13299       T.getObjCLifetime() == Qualifiers::OCL_None &&
13300       T->isObjCLifetimeType()) {
13301
13302     Qualifiers::ObjCLifetime lifetime;
13303
13304     // Special cases for arrays:
13305     //   - if it's const, use __unsafe_unretained
13306     //   - otherwise, it's an error
13307     if (T->isArrayType()) {
13308       if (!T.isConstQualified()) {
13309         if (DelayedDiagnostics.shouldDelayDiagnostics())
13310           DelayedDiagnostics.add(
13311               sema::DelayedDiagnostic::makeForbiddenType(
13312               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13313         else
13314           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13315               << TSInfo->getTypeLoc().getSourceRange();
13316       }
13317       lifetime = Qualifiers::OCL_ExplicitNone;
13318     } else {
13319       lifetime = T->getObjCARCImplicitLifetime();
13320     }
13321     T = Context.getLifetimeQualifiedType(T, lifetime);
13322   }
13323
13324   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13325                                          Context.getAdjustedParameterType(T),
13326                                          TSInfo, SC, nullptr);
13327
13328   // Make a note if we created a new pack in the scope of a lambda, so that
13329   // we know that references to that pack must also be expanded within the
13330   // lambda scope.
13331   if (New->isParameterPack())
13332     if (auto *LSI = getEnclosingLambda())
13333       LSI->LocalPacks.push_back(New);
13334
13335   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13336       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13337     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13338                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13339
13340   // Parameters can not be abstract class types.
13341   // For record types, this is done by the AbstractClassUsageDiagnoser once
13342   // the class has been completely parsed.
13343   if (!CurContext->isRecord() &&
13344       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13345                              AbstractParamType))
13346     New->setInvalidDecl();
13347
13348   // Parameter declarators cannot be interface types. All ObjC objects are
13349   // passed by reference.
13350   if (T->isObjCObjectType()) {
13351     SourceLocation TypeEndLoc =
13352         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13353     Diag(NameLoc,
13354          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13355       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13356     T = Context.getObjCObjectPointerType(T);
13357     New->setType(T);
13358   }
13359
13360   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13361   // duration shall not be qualified by an address-space qualifier."
13362   // Since all parameters have automatic store duration, they can not have
13363   // an address space.
13364   if (T.getAddressSpace() != LangAS::Default &&
13365       // OpenCL allows function arguments declared to be an array of a type
13366       // to be qualified with an address space.
13367       !(getLangOpts().OpenCL &&
13368         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13369     Diag(NameLoc, diag::err_arg_with_address_space);
13370     New->setInvalidDecl();
13371   }
13372
13373   return New;
13374 }
13375
13376 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13377                                            SourceLocation LocAfterDecls) {
13378   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13379
13380   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13381   // for a K&R function.
13382   if (!FTI.hasPrototype) {
13383     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13384       --i;
13385       if (FTI.Params[i].Param == nullptr) {
13386         SmallString<256> Code;
13387         llvm::raw_svector_ostream(Code)
13388             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13389         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13390             << FTI.Params[i].Ident
13391             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13392
13393         // Implicitly declare the argument as type 'int' for lack of a better
13394         // type.
13395         AttributeFactory attrs;
13396         DeclSpec DS(attrs);
13397         const char* PrevSpec; // unused
13398         unsigned DiagID; // unused
13399         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13400                            DiagID, Context.getPrintingPolicy());
13401         // Use the identifier location for the type source range.
13402         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13403         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13404         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13405         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13406         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13407       }
13408     }
13409   }
13410 }
13411
13412 Decl *
13413 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13414                               MultiTemplateParamsArg TemplateParameterLists,
13415                               SkipBodyInfo *SkipBody) {
13416   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13417   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13418   Scope *ParentScope = FnBodyScope->getParent();
13419
13420   D.setFunctionDefinitionKind(FDK_Definition);
13421   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13422   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13423 }
13424
13425 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13426   Consumer.HandleInlineFunctionDefinition(D);
13427 }
13428
13429 static bool
13430 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13431                                 const FunctionDecl *&PossiblePrototype) {
13432   // Don't warn about invalid declarations.
13433   if (FD->isInvalidDecl())
13434     return false;
13435
13436   // Or declarations that aren't global.
13437   if (!FD->isGlobal())
13438     return false;
13439
13440   // Don't warn about C++ member functions.
13441   if (isa<CXXMethodDecl>(FD))
13442     return false;
13443
13444   // Don't warn about 'main'.
13445   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13446     if (IdentifierInfo *II = FD->getIdentifier())
13447       if (II->isStr("main"))
13448         return false;
13449
13450   // Don't warn about inline functions.
13451   if (FD->isInlined())
13452     return false;
13453
13454   // Don't warn about function templates.
13455   if (FD->getDescribedFunctionTemplate())
13456     return false;
13457
13458   // Don't warn about function template specializations.
13459   if (FD->isFunctionTemplateSpecialization())
13460     return false;
13461
13462   // Don't warn for OpenCL kernels.
13463   if (FD->hasAttr<OpenCLKernelAttr>())
13464     return false;
13465
13466   // Don't warn on explicitly deleted functions.
13467   if (FD->isDeleted())
13468     return false;
13469
13470   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13471        Prev; Prev = Prev->getPreviousDecl()) {
13472     // Ignore any declarations that occur in function or method
13473     // scope, because they aren't visible from the header.
13474     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13475       continue;
13476
13477     PossiblePrototype = Prev;
13478     return Prev->getType()->isFunctionNoProtoType();
13479   }
13480
13481   return true;
13482 }
13483
13484 void
13485 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13486                                    const FunctionDecl *EffectiveDefinition,
13487                                    SkipBodyInfo *SkipBody) {
13488   const FunctionDecl *Definition = EffectiveDefinition;
13489   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13490     // If this is a friend function defined in a class template, it does not
13491     // have a body until it is used, nevertheless it is a definition, see
13492     // [temp.inst]p2:
13493     //
13494     // ... for the purpose of determining whether an instantiated redeclaration
13495     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13496     // corresponds to a definition in the template is considered to be a
13497     // definition.
13498     //
13499     // The following code must produce redefinition error:
13500     //
13501     //     template<typename T> struct C20 { friend void func_20() {} };
13502     //     C20<int> c20i;
13503     //     void func_20() {}
13504     //
13505     for (auto I : FD->redecls()) {
13506       if (I != FD && !I->isInvalidDecl() &&
13507           I->getFriendObjectKind() != Decl::FOK_None) {
13508         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13509           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13510             // A merged copy of the same function, instantiated as a member of
13511             // the same class, is OK.
13512             if (declaresSameEntity(OrigFD, Original) &&
13513                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13514                                    cast<Decl>(FD->getLexicalDeclContext())))
13515               continue;
13516           }
13517
13518           if (Original->isThisDeclarationADefinition()) {
13519             Definition = I;
13520             break;
13521           }
13522         }
13523       }
13524     }
13525   }
13526
13527   if (!Definition)
13528     // Similar to friend functions a friend function template may be a
13529     // definition and do not have a body if it is instantiated in a class
13530     // template.
13531     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13532       for (auto I : FTD->redecls()) {
13533         auto D = cast<FunctionTemplateDecl>(I);
13534         if (D != FTD) {
13535           assert(!D->isThisDeclarationADefinition() &&
13536                  "More than one definition in redeclaration chain");
13537           if (D->getFriendObjectKind() != Decl::FOK_None)
13538             if (FunctionTemplateDecl *FT =
13539                                        D->getInstantiatedFromMemberTemplate()) {
13540               if (FT->isThisDeclarationADefinition()) {
13541                 Definition = D->getTemplatedDecl();
13542                 break;
13543               }
13544             }
13545         }
13546       }
13547     }
13548
13549   if (!Definition)
13550     return;
13551
13552   if (canRedefineFunction(Definition, getLangOpts()))
13553     return;
13554
13555   // Don't emit an error when this is redefinition of a typo-corrected
13556   // definition.
13557   if (TypoCorrectedFunctionDefinitions.count(Definition))
13558     return;
13559
13560   // If we don't have a visible definition of the function, and it's inline or
13561   // a template, skip the new definition.
13562   if (SkipBody && !hasVisibleDefinition(Definition) &&
13563       (Definition->getFormalLinkage() == InternalLinkage ||
13564        Definition->isInlined() ||
13565        Definition->getDescribedFunctionTemplate() ||
13566        Definition->getNumTemplateParameterLists())) {
13567     SkipBody->ShouldSkip = true;
13568     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13569     if (auto *TD = Definition->getDescribedFunctionTemplate())
13570       makeMergedDefinitionVisible(TD);
13571     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13572     return;
13573   }
13574
13575   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13576       Definition->getStorageClass() == SC_Extern)
13577     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13578         << FD->getDeclName() << getLangOpts().CPlusPlus;
13579   else
13580     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13581
13582   Diag(Definition->getLocation(), diag::note_previous_definition);
13583   FD->setInvalidDecl();
13584 }
13585
13586 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13587                                    Sema &S) {
13588   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13589
13590   LambdaScopeInfo *LSI = S.PushLambdaScope();
13591   LSI->CallOperator = CallOperator;
13592   LSI->Lambda = LambdaClass;
13593   LSI->ReturnType = CallOperator->getReturnType();
13594   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13595
13596   if (LCD == LCD_None)
13597     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13598   else if (LCD == LCD_ByCopy)
13599     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13600   else if (LCD == LCD_ByRef)
13601     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13602   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13603
13604   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13605   LSI->Mutable = !CallOperator->isConst();
13606
13607   // Add the captures to the LSI so they can be noted as already
13608   // captured within tryCaptureVar.
13609   auto I = LambdaClass->field_begin();
13610   for (const auto &C : LambdaClass->captures()) {
13611     if (C.capturesVariable()) {
13612       VarDecl *VD = C.getCapturedVar();
13613       if (VD->isInitCapture())
13614         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13615       QualType CaptureType = VD->getType();
13616       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13617       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13618           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13619           /*EllipsisLoc*/C.isPackExpansion()
13620                          ? C.getEllipsisLoc() : SourceLocation(),
13621           CaptureType, /*Invalid*/false);
13622
13623     } else if (C.capturesThis()) {
13624       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13625                           C.getCaptureKind() == LCK_StarThis);
13626     } else {
13627       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13628                              I->getType());
13629     }
13630     ++I;
13631   }
13632 }
13633
13634 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13635                                     SkipBodyInfo *SkipBody) {
13636   if (!D) {
13637     // Parsing the function declaration failed in some way. Push on a fake scope
13638     // anyway so we can try to parse the function body.
13639     PushFunctionScope();
13640     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13641     return D;
13642   }
13643
13644   FunctionDecl *FD = nullptr;
13645
13646   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13647     FD = FunTmpl->getTemplatedDecl();
13648   else
13649     FD = cast<FunctionDecl>(D);
13650
13651   // Do not push if it is a lambda because one is already pushed when building
13652   // the lambda in ActOnStartOfLambdaDefinition().
13653   if (!isLambdaCallOperator(FD))
13654     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13655
13656   // Check for defining attributes before the check for redefinition.
13657   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13658     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13659     FD->dropAttr<AliasAttr>();
13660     FD->setInvalidDecl();
13661   }
13662   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13663     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13664     FD->dropAttr<IFuncAttr>();
13665     FD->setInvalidDecl();
13666   }
13667
13668   // See if this is a redefinition. If 'will have body' is already set, then
13669   // these checks were already performed when it was set.
13670   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13671     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13672
13673     // If we're skipping the body, we're done. Don't enter the scope.
13674     if (SkipBody && SkipBody->ShouldSkip)
13675       return D;
13676   }
13677
13678   // Mark this function as "will have a body eventually".  This lets users to
13679   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13680   // this function.
13681   FD->setWillHaveBody();
13682
13683   // If we are instantiating a generic lambda call operator, push
13684   // a LambdaScopeInfo onto the function stack.  But use the information
13685   // that's already been calculated (ActOnLambdaExpr) to prime the current
13686   // LambdaScopeInfo.
13687   // When the template operator is being specialized, the LambdaScopeInfo,
13688   // has to be properly restored so that tryCaptureVariable doesn't try
13689   // and capture any new variables. In addition when calculating potential
13690   // captures during transformation of nested lambdas, it is necessary to
13691   // have the LSI properly restored.
13692   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13693     assert(inTemplateInstantiation() &&
13694            "There should be an active template instantiation on the stack "
13695            "when instantiating a generic lambda!");
13696     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13697   } else {
13698     // Enter a new function scope
13699     PushFunctionScope();
13700   }
13701
13702   // Builtin functions cannot be defined.
13703   if (unsigned BuiltinID = FD->getBuiltinID()) {
13704     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13705         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13706       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13707       FD->setInvalidDecl();
13708     }
13709   }
13710
13711   // The return type of a function definition must be complete
13712   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13713   QualType ResultType = FD->getReturnType();
13714   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13715       !FD->isInvalidDecl() &&
13716       RequireCompleteType(FD->getLocation(), ResultType,
13717                           diag::err_func_def_incomplete_result))
13718     FD->setInvalidDecl();
13719
13720   if (FnBodyScope)
13721     PushDeclContext(FnBodyScope, FD);
13722
13723   // Check the validity of our function parameters
13724   CheckParmsForFunctionDef(FD->parameters(),
13725                            /*CheckParameterNames=*/true);
13726
13727   // Add non-parameter declarations already in the function to the current
13728   // scope.
13729   if (FnBodyScope) {
13730     for (Decl *NPD : FD->decls()) {
13731       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13732       if (!NonParmDecl)
13733         continue;
13734       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13735              "parameters should not be in newly created FD yet");
13736
13737       // If the decl has a name, make it accessible in the current scope.
13738       if (NonParmDecl->getDeclName())
13739         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13740
13741       // Similarly, dive into enums and fish their constants out, making them
13742       // accessible in this scope.
13743       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13744         for (auto *EI : ED->enumerators())
13745           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13746       }
13747     }
13748   }
13749
13750   // Introduce our parameters into the function scope
13751   for (auto Param : FD->parameters()) {
13752     Param->setOwningFunction(FD);
13753
13754     // If this has an identifier, add it to the scope stack.
13755     if (Param->getIdentifier() && FnBodyScope) {
13756       CheckShadow(FnBodyScope, Param);
13757
13758       PushOnScopeChains(Param, FnBodyScope);
13759     }
13760   }
13761
13762   // Ensure that the function's exception specification is instantiated.
13763   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13764     ResolveExceptionSpec(D->getLocation(), FPT);
13765
13766   // dllimport cannot be applied to non-inline function definitions.
13767   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13768       !FD->isTemplateInstantiation()) {
13769     assert(!FD->hasAttr<DLLExportAttr>());
13770     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13771     FD->setInvalidDecl();
13772     return D;
13773   }
13774   // We want to attach documentation to original Decl (which might be
13775   // a function template).
13776   ActOnDocumentableDecl(D);
13777   if (getCurLexicalContext()->isObjCContainer() &&
13778       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13779       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13780     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13781
13782   return D;
13783 }
13784
13785 /// Given the set of return statements within a function body,
13786 /// compute the variables that are subject to the named return value
13787 /// optimization.
13788 ///
13789 /// Each of the variables that is subject to the named return value
13790 /// optimization will be marked as NRVO variables in the AST, and any
13791 /// return statement that has a marked NRVO variable as its NRVO candidate can
13792 /// use the named return value optimization.
13793 ///
13794 /// This function applies a very simplistic algorithm for NRVO: if every return
13795 /// statement in the scope of a variable has the same NRVO candidate, that
13796 /// candidate is an NRVO variable.
13797 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13798   ReturnStmt **Returns = Scope->Returns.data();
13799
13800   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13801     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13802       if (!NRVOCandidate->isNRVOVariable())
13803         Returns[I]->setNRVOCandidate(nullptr);
13804     }
13805   }
13806 }
13807
13808 bool Sema::canDelayFunctionBody(const Declarator &D) {
13809   // We can't delay parsing the body of a constexpr function template (yet).
13810   if (D.getDeclSpec().hasConstexprSpecifier())
13811     return false;
13812
13813   // We can't delay parsing the body of a function template with a deduced
13814   // return type (yet).
13815   if (D.getDeclSpec().hasAutoTypeSpec()) {
13816     // If the placeholder introduces a non-deduced trailing return type,
13817     // we can still delay parsing it.
13818     if (D.getNumTypeObjects()) {
13819       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13820       if (Outer.Kind == DeclaratorChunk::Function &&
13821           Outer.Fun.hasTrailingReturnType()) {
13822         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13823         return Ty.isNull() || !Ty->isUndeducedType();
13824       }
13825     }
13826     return false;
13827   }
13828
13829   return true;
13830 }
13831
13832 bool Sema::canSkipFunctionBody(Decl *D) {
13833   // We cannot skip the body of a function (or function template) which is
13834   // constexpr, since we may need to evaluate its body in order to parse the
13835   // rest of the file.
13836   // We cannot skip the body of a function with an undeduced return type,
13837   // because any callers of that function need to know the type.
13838   if (const FunctionDecl *FD = D->getAsFunction()) {
13839     if (FD->isConstexpr())
13840       return false;
13841     // We can't simply call Type::isUndeducedType here, because inside template
13842     // auto can be deduced to a dependent type, which is not considered
13843     // "undeduced".
13844     if (FD->getReturnType()->getContainedDeducedType())
13845       return false;
13846   }
13847   return Consumer.shouldSkipFunctionBody(D);
13848 }
13849
13850 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13851   if (!Decl)
13852     return nullptr;
13853   if (FunctionDecl *FD = Decl->getAsFunction())
13854     FD->setHasSkippedBody();
13855   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13856     MD->setHasSkippedBody();
13857   return Decl;
13858 }
13859
13860 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13861   return ActOnFinishFunctionBody(D, BodyArg, false);
13862 }
13863
13864 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13865 /// body.
13866 class ExitFunctionBodyRAII {
13867 public:
13868   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13869   ~ExitFunctionBodyRAII() {
13870     if (!IsLambda)
13871       S.PopExpressionEvaluationContext();
13872   }
13873
13874 private:
13875   Sema &S;
13876   bool IsLambda = false;
13877 };
13878
13879 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13880   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13881
13882   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13883     if (EscapeInfo.count(BD))
13884       return EscapeInfo[BD];
13885
13886     bool R = false;
13887     const BlockDecl *CurBD = BD;
13888
13889     do {
13890       R = !CurBD->doesNotEscape();
13891       if (R)
13892         break;
13893       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13894     } while (CurBD);
13895
13896     return EscapeInfo[BD] = R;
13897   };
13898
13899   // If the location where 'self' is implicitly retained is inside a escaping
13900   // block, emit a diagnostic.
13901   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13902        S.ImplicitlyRetainedSelfLocs)
13903     if (IsOrNestedInEscapingBlock(P.second))
13904       S.Diag(P.first, diag::warn_implicitly_retains_self)
13905           << FixItHint::CreateInsertion(P.first, "self->");
13906 }
13907
13908 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13909                                     bool IsInstantiation) {
13910   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13911
13912   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13913   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13914
13915   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13916     CheckCompletedCoroutineBody(FD, Body);
13917
13918   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13919   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13920   // meant to pop the context added in ActOnStartOfFunctionDef().
13921   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13922
13923   if (FD) {
13924     FD->setBody(Body);
13925     FD->setWillHaveBody(false);
13926
13927     if (getLangOpts().CPlusPlus14) {
13928       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13929           FD->getReturnType()->isUndeducedType()) {
13930         // If the function has a deduced result type but contains no 'return'
13931         // statements, the result type as written must be exactly 'auto', and
13932         // the deduced result type is 'void'.
13933         if (!FD->getReturnType()->getAs<AutoType>()) {
13934           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13935               << FD->getReturnType();
13936           FD->setInvalidDecl();
13937         } else {
13938           // Substitute 'void' for the 'auto' in the type.
13939           TypeLoc ResultType = getReturnTypeLoc(FD);
13940           Context.adjustDeducedFunctionResultType(
13941               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13942         }
13943       }
13944     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13945       // In C++11, we don't use 'auto' deduction rules for lambda call
13946       // operators because we don't support return type deduction.
13947       auto *LSI = getCurLambda();
13948       if (LSI->HasImplicitReturnType) {
13949         deduceClosureReturnType(*LSI);
13950
13951         // C++11 [expr.prim.lambda]p4:
13952         //   [...] if there are no return statements in the compound-statement
13953         //   [the deduced type is] the type void
13954         QualType RetType =
13955             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13956
13957         // Update the return type to the deduced type.
13958         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13959         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13960                                             Proto->getExtProtoInfo()));
13961       }
13962     }
13963
13964     // If the function implicitly returns zero (like 'main') or is naked,
13965     // don't complain about missing return statements.
13966     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13967       WP.disableCheckFallThrough();
13968
13969     // MSVC permits the use of pure specifier (=0) on function definition,
13970     // defined at class scope, warn about this non-standard construct.
13971     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13972       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13973
13974     if (!FD->isInvalidDecl()) {
13975       // Don't diagnose unused parameters of defaulted or deleted functions.
13976       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13977         DiagnoseUnusedParameters(FD->parameters());
13978       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13979                                              FD->getReturnType(), FD);
13980
13981       // If this is a structor, we need a vtable.
13982       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13983         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13984       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13985         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13986
13987       // Try to apply the named return value optimization. We have to check
13988       // if we can do this here because lambdas keep return statements around
13989       // to deduce an implicit return type.
13990       if (FD->getReturnType()->isRecordType() &&
13991           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13992         computeNRVO(Body, getCurFunction());
13993     }
13994
13995     // GNU warning -Wmissing-prototypes:
13996     //   Warn if a global function is defined without a previous
13997     //   prototype declaration. This warning is issued even if the
13998     //   definition itself provides a prototype. The aim is to detect
13999     //   global functions that fail to be declared in header files.
14000     const FunctionDecl *PossiblePrototype = nullptr;
14001     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14002       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14003
14004       if (PossiblePrototype) {
14005         // We found a declaration that is not a prototype,
14006         // but that could be a zero-parameter prototype
14007         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14008           TypeLoc TL = TI->getTypeLoc();
14009           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14010             Diag(PossiblePrototype->getLocation(),
14011                  diag::note_declaration_not_a_prototype)
14012                 << (FD->getNumParams() != 0)
14013                 << (FD->getNumParams() == 0
14014                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14015                         : FixItHint{});
14016         }
14017       } else {
14018         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14019             << /* function */ 1
14020             << (FD->getStorageClass() == SC_None
14021                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14022                                                  "static ")
14023                     : FixItHint{});
14024       }
14025
14026       // GNU warning -Wstrict-prototypes
14027       //   Warn if K&R function is defined without a previous declaration.
14028       //   This warning is issued only if the definition itself does not provide
14029       //   a prototype. Only K&R definitions do not provide a prototype.
14030       //   An empty list in a function declarator that is part of a definition
14031       //   of that function specifies that the function has no parameters
14032       //   (C99 6.7.5.3p14)
14033       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14034           !LangOpts.CPlusPlus) {
14035         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14036         TypeLoc TL = TI->getTypeLoc();
14037         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14038         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14039       }
14040     }
14041
14042     // Warn on CPUDispatch with an actual body.
14043     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14044       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14045         if (!CmpndBody->body_empty())
14046           Diag(CmpndBody->body_front()->getBeginLoc(),
14047                diag::warn_dispatch_body_ignored);
14048
14049     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14050       const CXXMethodDecl *KeyFunction;
14051       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14052           MD->isVirtual() &&
14053           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14054           MD == KeyFunction->getCanonicalDecl()) {
14055         // Update the key-function state if necessary for this ABI.
14056         if (FD->isInlined() &&
14057             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14058           Context.setNonKeyFunction(MD);
14059
14060           // If the newly-chosen key function is already defined, then we
14061           // need to mark the vtable as used retroactively.
14062           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14063           const FunctionDecl *Definition;
14064           if (KeyFunction && KeyFunction->isDefined(Definition))
14065             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14066         } else {
14067           // We just defined they key function; mark the vtable as used.
14068           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14069         }
14070       }
14071     }
14072
14073     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14074            "Function parsing confused");
14075   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14076     assert(MD == getCurMethodDecl() && "Method parsing confused");
14077     MD->setBody(Body);
14078     if (!MD->isInvalidDecl()) {
14079       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14080                                              MD->getReturnType(), MD);
14081
14082       if (Body)
14083         computeNRVO(Body, getCurFunction());
14084     }
14085     if (getCurFunction()->ObjCShouldCallSuper) {
14086       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14087           << MD->getSelector().getAsString();
14088       getCurFunction()->ObjCShouldCallSuper = false;
14089     }
14090     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14091       const ObjCMethodDecl *InitMethod = nullptr;
14092       bool isDesignated =
14093           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14094       assert(isDesignated && InitMethod);
14095       (void)isDesignated;
14096
14097       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14098         auto IFace = MD->getClassInterface();
14099         if (!IFace)
14100           return false;
14101         auto SuperD = IFace->getSuperClass();
14102         if (!SuperD)
14103           return false;
14104         return SuperD->getIdentifier() ==
14105             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14106       };
14107       // Don't issue this warning for unavailable inits or direct subclasses
14108       // of NSObject.
14109       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14110         Diag(MD->getLocation(),
14111              diag::warn_objc_designated_init_missing_super_call);
14112         Diag(InitMethod->getLocation(),
14113              diag::note_objc_designated_init_marked_here);
14114       }
14115       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14116     }
14117     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14118       // Don't issue this warning for unavaialable inits.
14119       if (!MD->isUnavailable())
14120         Diag(MD->getLocation(),
14121              diag::warn_objc_secondary_init_missing_init_call);
14122       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14123     }
14124
14125     diagnoseImplicitlyRetainedSelf(*this);
14126   } else {
14127     // Parsing the function declaration failed in some way. Pop the fake scope
14128     // we pushed on.
14129     PopFunctionScopeInfo(ActivePolicy, dcl);
14130     return nullptr;
14131   }
14132
14133   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14134     DiagnoseUnguardedAvailabilityViolations(dcl);
14135
14136   assert(!getCurFunction()->ObjCShouldCallSuper &&
14137          "This should only be set for ObjC methods, which should have been "
14138          "handled in the block above.");
14139
14140   // Verify and clean out per-function state.
14141   if (Body && (!FD || !FD->isDefaulted())) {
14142     // C++ constructors that have function-try-blocks can't have return
14143     // statements in the handlers of that block. (C++ [except.handle]p14)
14144     // Verify this.
14145     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14146       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14147
14148     // Verify that gotos and switch cases don't jump into scopes illegally.
14149     if (getCurFunction()->NeedsScopeChecking() &&
14150         !PP.isCodeCompletionEnabled())
14151       DiagnoseInvalidJumps(Body);
14152
14153     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14154       if (!Destructor->getParent()->isDependentType())
14155         CheckDestructor(Destructor);
14156
14157       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14158                                              Destructor->getParent());
14159     }
14160
14161     // If any errors have occurred, clear out any temporaries that may have
14162     // been leftover. This ensures that these temporaries won't be picked up for
14163     // deletion in some later function.
14164     if (getDiagnostics().hasErrorOccurred() ||
14165         getDiagnostics().getSuppressAllDiagnostics()) {
14166       DiscardCleanupsInEvaluationContext();
14167     }
14168     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14169         !isa<FunctionTemplateDecl>(dcl)) {
14170       // Since the body is valid, issue any analysis-based warnings that are
14171       // enabled.
14172       ActivePolicy = &WP;
14173     }
14174
14175     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14176         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14177       FD->setInvalidDecl();
14178
14179     if (FD && FD->hasAttr<NakedAttr>()) {
14180       for (const Stmt *S : Body->children()) {
14181         // Allow local register variables without initializer as they don't
14182         // require prologue.
14183         bool RegisterVariables = false;
14184         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14185           for (const auto *Decl : DS->decls()) {
14186             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14187               RegisterVariables =
14188                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14189               if (!RegisterVariables)
14190                 break;
14191             }
14192           }
14193         }
14194         if (RegisterVariables)
14195           continue;
14196         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14197           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14198           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14199           FD->setInvalidDecl();
14200           break;
14201         }
14202       }
14203     }
14204
14205     assert(ExprCleanupObjects.size() ==
14206                ExprEvalContexts.back().NumCleanupObjects &&
14207            "Leftover temporaries in function");
14208     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14209     assert(MaybeODRUseExprs.empty() &&
14210            "Leftover expressions for odr-use checking");
14211   }
14212
14213   if (!IsInstantiation)
14214     PopDeclContext();
14215
14216   PopFunctionScopeInfo(ActivePolicy, dcl);
14217   // If any errors have occurred, clear out any temporaries that may have
14218   // been leftover. This ensures that these temporaries won't be picked up for
14219   // deletion in some later function.
14220   if (getDiagnostics().hasErrorOccurred()) {
14221     DiscardCleanupsInEvaluationContext();
14222   }
14223
14224   return dcl;
14225 }
14226
14227 /// When we finish delayed parsing of an attribute, we must attach it to the
14228 /// relevant Decl.
14229 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14230                                        ParsedAttributes &Attrs) {
14231   // Always attach attributes to the underlying decl.
14232   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14233     D = TD->getTemplatedDecl();
14234   ProcessDeclAttributeList(S, D, Attrs);
14235
14236   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14237     if (Method->isStatic())
14238       checkThisInStaticMemberFunctionAttributes(Method);
14239 }
14240
14241 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14242 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14243 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14244                                           IdentifierInfo &II, Scope *S) {
14245   // Find the scope in which the identifier is injected and the corresponding
14246   // DeclContext.
14247   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14248   // In that case, we inject the declaration into the translation unit scope
14249   // instead.
14250   Scope *BlockScope = S;
14251   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14252     BlockScope = BlockScope->getParent();
14253
14254   Scope *ContextScope = BlockScope;
14255   while (!ContextScope->getEntity())
14256     ContextScope = ContextScope->getParent();
14257   ContextRAII SavedContext(*this, ContextScope->getEntity());
14258
14259   // Before we produce a declaration for an implicitly defined
14260   // function, see whether there was a locally-scoped declaration of
14261   // this name as a function or variable. If so, use that
14262   // (non-visible) declaration, and complain about it.
14263   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14264   if (ExternCPrev) {
14265     // We still need to inject the function into the enclosing block scope so
14266     // that later (non-call) uses can see it.
14267     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14268
14269     // C89 footnote 38:
14270     //   If in fact it is not defined as having type "function returning int",
14271     //   the behavior is undefined.
14272     if (!isa<FunctionDecl>(ExternCPrev) ||
14273         !Context.typesAreCompatible(
14274             cast<FunctionDecl>(ExternCPrev)->getType(),
14275             Context.getFunctionNoProtoType(Context.IntTy))) {
14276       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14277           << ExternCPrev << !getLangOpts().C99;
14278       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14279       return ExternCPrev;
14280     }
14281   }
14282
14283   // Extension in C99.  Legal in C90, but warn about it.
14284   unsigned diag_id;
14285   if (II.getName().startswith("__builtin_"))
14286     diag_id = diag::warn_builtin_unknown;
14287   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14288   else if (getLangOpts().OpenCL)
14289     diag_id = diag::err_opencl_implicit_function_decl;
14290   else if (getLangOpts().C99)
14291     diag_id = diag::ext_implicit_function_decl;
14292   else
14293     diag_id = diag::warn_implicit_function_decl;
14294   Diag(Loc, diag_id) << &II;
14295
14296   // If we found a prior declaration of this function, don't bother building
14297   // another one. We've already pushed that one into scope, so there's nothing
14298   // more to do.
14299   if (ExternCPrev)
14300     return ExternCPrev;
14301
14302   // Because typo correction is expensive, only do it if the implicit
14303   // function declaration is going to be treated as an error.
14304   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14305     TypoCorrection Corrected;
14306     DeclFilterCCC<FunctionDecl> CCC{};
14307     if (S && (Corrected =
14308                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14309                               S, nullptr, CCC, CTK_NonError)))
14310       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14311                    /*ErrorRecovery*/false);
14312   }
14313
14314   // Set a Declarator for the implicit definition: int foo();
14315   const char *Dummy;
14316   AttributeFactory attrFactory;
14317   DeclSpec DS(attrFactory);
14318   unsigned DiagID;
14319   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14320                                   Context.getPrintingPolicy());
14321   (void)Error; // Silence warning.
14322   assert(!Error && "Error setting up implicit decl!");
14323   SourceLocation NoLoc;
14324   Declarator D(DS, DeclaratorContext::BlockContext);
14325   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14326                                              /*IsAmbiguous=*/false,
14327                                              /*LParenLoc=*/NoLoc,
14328                                              /*Params=*/nullptr,
14329                                              /*NumParams=*/0,
14330                                              /*EllipsisLoc=*/NoLoc,
14331                                              /*RParenLoc=*/NoLoc,
14332                                              /*RefQualifierIsLvalueRef=*/true,
14333                                              /*RefQualifierLoc=*/NoLoc,
14334                                              /*MutableLoc=*/NoLoc, EST_None,
14335                                              /*ESpecRange=*/SourceRange(),
14336                                              /*Exceptions=*/nullptr,
14337                                              /*ExceptionRanges=*/nullptr,
14338                                              /*NumExceptions=*/0,
14339                                              /*NoexceptExpr=*/nullptr,
14340                                              /*ExceptionSpecTokens=*/nullptr,
14341                                              /*DeclsInPrototype=*/None, Loc,
14342                                              Loc, D),
14343                 std::move(DS.getAttributes()), SourceLocation());
14344   D.SetIdentifier(&II, Loc);
14345
14346   // Insert this function into the enclosing block scope.
14347   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14348   FD->setImplicit();
14349
14350   AddKnownFunctionAttributes(FD);
14351
14352   return FD;
14353 }
14354
14355 /// Adds any function attributes that we know a priori based on
14356 /// the declaration of this function.
14357 ///
14358 /// These attributes can apply both to implicitly-declared builtins
14359 /// (like __builtin___printf_chk) or to library-declared functions
14360 /// like NSLog or printf.
14361 ///
14362 /// We need to check for duplicate attributes both here and where user-written
14363 /// attributes are applied to declarations.
14364 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14365   if (FD->isInvalidDecl())
14366     return;
14367
14368   // If this is a built-in function, map its builtin attributes to
14369   // actual attributes.
14370   if (unsigned BuiltinID = FD->getBuiltinID()) {
14371     // Handle printf-formatting attributes.
14372     unsigned FormatIdx;
14373     bool HasVAListArg;
14374     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14375       if (!FD->hasAttr<FormatAttr>()) {
14376         const char *fmt = "printf";
14377         unsigned int NumParams = FD->getNumParams();
14378         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14379             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14380           fmt = "NSString";
14381         FD->addAttr(FormatAttr::CreateImplicit(Context,
14382                                                &Context.Idents.get(fmt),
14383                                                FormatIdx+1,
14384                                                HasVAListArg ? 0 : FormatIdx+2,
14385                                                FD->getLocation()));
14386       }
14387     }
14388     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14389                                              HasVAListArg)) {
14390      if (!FD->hasAttr<FormatAttr>())
14391        FD->addAttr(FormatAttr::CreateImplicit(Context,
14392                                               &Context.Idents.get("scanf"),
14393                                               FormatIdx+1,
14394                                               HasVAListArg ? 0 : FormatIdx+2,
14395                                               FD->getLocation()));
14396     }
14397
14398     // Handle automatically recognized callbacks.
14399     SmallVector<int, 4> Encoding;
14400     if (!FD->hasAttr<CallbackAttr>() &&
14401         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14402       FD->addAttr(CallbackAttr::CreateImplicit(
14403           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14404
14405     // Mark const if we don't care about errno and that is the only thing
14406     // preventing the function from being const. This allows IRgen to use LLVM
14407     // intrinsics for such functions.
14408     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14409         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14410       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14411
14412     // We make "fma" on some platforms const because we know it does not set
14413     // errno in those environments even though it could set errno based on the
14414     // C standard.
14415     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14416     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14417         !FD->hasAttr<ConstAttr>()) {
14418       switch (BuiltinID) {
14419       case Builtin::BI__builtin_fma:
14420       case Builtin::BI__builtin_fmaf:
14421       case Builtin::BI__builtin_fmal:
14422       case Builtin::BIfma:
14423       case Builtin::BIfmaf:
14424       case Builtin::BIfmal:
14425         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14426         break;
14427       default:
14428         break;
14429       }
14430     }
14431
14432     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14433         !FD->hasAttr<ReturnsTwiceAttr>())
14434       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14435                                          FD->getLocation()));
14436     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14437       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14438     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14439       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14440     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14441       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14442     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14443         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14444       // Add the appropriate attribute, depending on the CUDA compilation mode
14445       // and which target the builtin belongs to. For example, during host
14446       // compilation, aux builtins are __device__, while the rest are __host__.
14447       if (getLangOpts().CUDAIsDevice !=
14448           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14449         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14450       else
14451         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14452     }
14453   }
14454
14455   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14456   // throw, add an implicit nothrow attribute to any extern "C" function we come
14457   // across.
14458   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14459       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14460     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14461     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14462       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14463   }
14464
14465   IdentifierInfo *Name = FD->getIdentifier();
14466   if (!Name)
14467     return;
14468   if ((!getLangOpts().CPlusPlus &&
14469        FD->getDeclContext()->isTranslationUnit()) ||
14470       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14471        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14472        LinkageSpecDecl::lang_c)) {
14473     // Okay: this could be a libc/libm/Objective-C function we know
14474     // about.
14475   } else
14476     return;
14477
14478   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14479     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14480     // target-specific builtins, perhaps?
14481     if (!FD->hasAttr<FormatAttr>())
14482       FD->addAttr(FormatAttr::CreateImplicit(Context,
14483                                              &Context.Idents.get("printf"), 2,
14484                                              Name->isStr("vasprintf") ? 0 : 3,
14485                                              FD->getLocation()));
14486   }
14487
14488   if (Name->isStr("__CFStringMakeConstantString")) {
14489     // We already have a __builtin___CFStringMakeConstantString,
14490     // but builds that use -fno-constant-cfstrings don't go through that.
14491     if (!FD->hasAttr<FormatArgAttr>())
14492       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14493                                                 FD->getLocation()));
14494   }
14495 }
14496
14497 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14498                                     TypeSourceInfo *TInfo) {
14499   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14500   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14501
14502   if (!TInfo) {
14503     assert(D.isInvalidType() && "no declarator info for valid type");
14504     TInfo = Context.getTrivialTypeSourceInfo(T);
14505   }
14506
14507   // Scope manipulation handled by caller.
14508   TypedefDecl *NewTD =
14509       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14510                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14511
14512   // Bail out immediately if we have an invalid declaration.
14513   if (D.isInvalidType()) {
14514     NewTD->setInvalidDecl();
14515     return NewTD;
14516   }
14517
14518   if (D.getDeclSpec().isModulePrivateSpecified()) {
14519     if (CurContext->isFunctionOrMethod())
14520       Diag(NewTD->getLocation(), diag::err_module_private_local)
14521         << 2 << NewTD->getDeclName()
14522         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14523         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14524     else
14525       NewTD->setModulePrivate();
14526   }
14527
14528   // C++ [dcl.typedef]p8:
14529   //   If the typedef declaration defines an unnamed class (or
14530   //   enum), the first typedef-name declared by the declaration
14531   //   to be that class type (or enum type) is used to denote the
14532   //   class type (or enum type) for linkage purposes only.
14533   // We need to check whether the type was declared in the declaration.
14534   switch (D.getDeclSpec().getTypeSpecType()) {
14535   case TST_enum:
14536   case TST_struct:
14537   case TST_interface:
14538   case TST_union:
14539   case TST_class: {
14540     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14541     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14542     break;
14543   }
14544
14545   default:
14546     break;
14547   }
14548
14549   return NewTD;
14550 }
14551
14552 /// Check that this is a valid underlying type for an enum declaration.
14553 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14554   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14555   QualType T = TI->getType();
14556
14557   if (T->isDependentType())
14558     return false;
14559
14560   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14561     if (BT->isInteger())
14562       return false;
14563
14564   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14565   return true;
14566 }
14567
14568 /// Check whether this is a valid redeclaration of a previous enumeration.
14569 /// \return true if the redeclaration was invalid.
14570 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14571                                   QualType EnumUnderlyingTy, bool IsFixed,
14572                                   const EnumDecl *Prev) {
14573   if (IsScoped != Prev->isScoped()) {
14574     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14575       << Prev->isScoped();
14576     Diag(Prev->getLocation(), diag::note_previous_declaration);
14577     return true;
14578   }
14579
14580   if (IsFixed && Prev->isFixed()) {
14581     if (!EnumUnderlyingTy->isDependentType() &&
14582         !Prev->getIntegerType()->isDependentType() &&
14583         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14584                                         Prev->getIntegerType())) {
14585       // TODO: Highlight the underlying type of the redeclaration.
14586       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14587         << EnumUnderlyingTy << Prev->getIntegerType();
14588       Diag(Prev->getLocation(), diag::note_previous_declaration)
14589           << Prev->getIntegerTypeRange();
14590       return true;
14591     }
14592   } else if (IsFixed != Prev->isFixed()) {
14593     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14594       << Prev->isFixed();
14595     Diag(Prev->getLocation(), diag::note_previous_declaration);
14596     return true;
14597   }
14598
14599   return false;
14600 }
14601
14602 /// Get diagnostic %select index for tag kind for
14603 /// redeclaration diagnostic message.
14604 /// WARNING: Indexes apply to particular diagnostics only!
14605 ///
14606 /// \returns diagnostic %select index.
14607 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14608   switch (Tag) {
14609   case TTK_Struct: return 0;
14610   case TTK_Interface: return 1;
14611   case TTK_Class:  return 2;
14612   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14613   }
14614 }
14615
14616 /// Determine if tag kind is a class-key compatible with
14617 /// class for redeclaration (class, struct, or __interface).
14618 ///
14619 /// \returns true iff the tag kind is compatible.
14620 static bool isClassCompatTagKind(TagTypeKind Tag)
14621 {
14622   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14623 }
14624
14625 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14626                                              TagTypeKind TTK) {
14627   if (isa<TypedefDecl>(PrevDecl))
14628     return NTK_Typedef;
14629   else if (isa<TypeAliasDecl>(PrevDecl))
14630     return NTK_TypeAlias;
14631   else if (isa<ClassTemplateDecl>(PrevDecl))
14632     return NTK_Template;
14633   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14634     return NTK_TypeAliasTemplate;
14635   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14636     return NTK_TemplateTemplateArgument;
14637   switch (TTK) {
14638   case TTK_Struct:
14639   case TTK_Interface:
14640   case TTK_Class:
14641     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14642   case TTK_Union:
14643     return NTK_NonUnion;
14644   case TTK_Enum:
14645     return NTK_NonEnum;
14646   }
14647   llvm_unreachable("invalid TTK");
14648 }
14649
14650 /// Determine whether a tag with a given kind is acceptable
14651 /// as a redeclaration of the given tag declaration.
14652 ///
14653 /// \returns true if the new tag kind is acceptable, false otherwise.
14654 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14655                                         TagTypeKind NewTag, bool isDefinition,
14656                                         SourceLocation NewTagLoc,
14657                                         const IdentifierInfo *Name) {
14658   // C++ [dcl.type.elab]p3:
14659   //   The class-key or enum keyword present in the
14660   //   elaborated-type-specifier shall agree in kind with the
14661   //   declaration to which the name in the elaborated-type-specifier
14662   //   refers. This rule also applies to the form of
14663   //   elaborated-type-specifier that declares a class-name or
14664   //   friend class since it can be construed as referring to the
14665   //   definition of the class. Thus, in any
14666   //   elaborated-type-specifier, the enum keyword shall be used to
14667   //   refer to an enumeration (7.2), the union class-key shall be
14668   //   used to refer to a union (clause 9), and either the class or
14669   //   struct class-key shall be used to refer to a class (clause 9)
14670   //   declared using the class or struct class-key.
14671   TagTypeKind OldTag = Previous->getTagKind();
14672   if (OldTag != NewTag &&
14673       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14674     return false;
14675
14676   // Tags are compatible, but we might still want to warn on mismatched tags.
14677   // Non-class tags can't be mismatched at this point.
14678   if (!isClassCompatTagKind(NewTag))
14679     return true;
14680
14681   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14682   // by our warning analysis. We don't want to warn about mismatches with (eg)
14683   // declarations in system headers that are designed to be specialized, but if
14684   // a user asks us to warn, we should warn if their code contains mismatched
14685   // declarations.
14686   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14687     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14688                                       Loc);
14689   };
14690   if (IsIgnoredLoc(NewTagLoc))
14691     return true;
14692
14693   auto IsIgnored = [&](const TagDecl *Tag) {
14694     return IsIgnoredLoc(Tag->getLocation());
14695   };
14696   while (IsIgnored(Previous)) {
14697     Previous = Previous->getPreviousDecl();
14698     if (!Previous)
14699       return true;
14700     OldTag = Previous->getTagKind();
14701   }
14702
14703   bool isTemplate = false;
14704   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14705     isTemplate = Record->getDescribedClassTemplate();
14706
14707   if (inTemplateInstantiation()) {
14708     if (OldTag != NewTag) {
14709       // In a template instantiation, do not offer fix-its for tag mismatches
14710       // since they usually mess up the template instead of fixing the problem.
14711       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14712         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14713         << getRedeclDiagFromTagKind(OldTag);
14714       // FIXME: Note previous location?
14715     }
14716     return true;
14717   }
14718
14719   if (isDefinition) {
14720     // On definitions, check all previous tags and issue a fix-it for each
14721     // one that doesn't match the current tag.
14722     if (Previous->getDefinition()) {
14723       // Don't suggest fix-its for redefinitions.
14724       return true;
14725     }
14726
14727     bool previousMismatch = false;
14728     for (const TagDecl *I : Previous->redecls()) {
14729       if (I->getTagKind() != NewTag) {
14730         // Ignore previous declarations for which the warning was disabled.
14731         if (IsIgnored(I))
14732           continue;
14733
14734         if (!previousMismatch) {
14735           previousMismatch = true;
14736           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14737             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14738             << getRedeclDiagFromTagKind(I->getTagKind());
14739         }
14740         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14741           << getRedeclDiagFromTagKind(NewTag)
14742           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14743                TypeWithKeyword::getTagTypeKindName(NewTag));
14744       }
14745     }
14746     return true;
14747   }
14748
14749   // Identify the prevailing tag kind: this is the kind of the definition (if
14750   // there is a non-ignored definition), or otherwise the kind of the prior
14751   // (non-ignored) declaration.
14752   const TagDecl *PrevDef = Previous->getDefinition();
14753   if (PrevDef && IsIgnored(PrevDef))
14754     PrevDef = nullptr;
14755   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14756   if (Redecl->getTagKind() != NewTag) {
14757     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14758       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14759       << getRedeclDiagFromTagKind(OldTag);
14760     Diag(Redecl->getLocation(), diag::note_previous_use);
14761
14762     // If there is a previous definition, suggest a fix-it.
14763     if (PrevDef) {
14764       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14765         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14766         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14767              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14768     }
14769   }
14770
14771   return true;
14772 }
14773
14774 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14775 /// from an outer enclosing namespace or file scope inside a friend declaration.
14776 /// This should provide the commented out code in the following snippet:
14777 ///   namespace N {
14778 ///     struct X;
14779 ///     namespace M {
14780 ///       struct Y { friend struct /*N::*/ X; };
14781 ///     }
14782 ///   }
14783 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14784                                          SourceLocation NameLoc) {
14785   // While the decl is in a namespace, do repeated lookup of that name and see
14786   // if we get the same namespace back.  If we do not, continue until
14787   // translation unit scope, at which point we have a fully qualified NNS.
14788   SmallVector<IdentifierInfo *, 4> Namespaces;
14789   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14790   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14791     // This tag should be declared in a namespace, which can only be enclosed by
14792     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14793     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14794     if (!Namespace || Namespace->isAnonymousNamespace())
14795       return FixItHint();
14796     IdentifierInfo *II = Namespace->getIdentifier();
14797     Namespaces.push_back(II);
14798     NamedDecl *Lookup = SemaRef.LookupSingleName(
14799         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14800     if (Lookup == Namespace)
14801       break;
14802   }
14803
14804   // Once we have all the namespaces, reverse them to go outermost first, and
14805   // build an NNS.
14806   SmallString<64> Insertion;
14807   llvm::raw_svector_ostream OS(Insertion);
14808   if (DC->isTranslationUnit())
14809     OS << "::";
14810   std::reverse(Namespaces.begin(), Namespaces.end());
14811   for (auto *II : Namespaces)
14812     OS << II->getName() << "::";
14813   return FixItHint::CreateInsertion(NameLoc, Insertion);
14814 }
14815
14816 /// Determine whether a tag originally declared in context \p OldDC can
14817 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14818 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14819 /// using-declaration).
14820 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14821                                          DeclContext *NewDC) {
14822   OldDC = OldDC->getRedeclContext();
14823   NewDC = NewDC->getRedeclContext();
14824
14825   if (OldDC->Equals(NewDC))
14826     return true;
14827
14828   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14829   // encloses the other).
14830   if (S.getLangOpts().MSVCCompat &&
14831       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14832     return true;
14833
14834   return false;
14835 }
14836
14837 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14838 /// former case, Name will be non-null.  In the later case, Name will be null.
14839 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14840 /// reference/declaration/definition of a tag.
14841 ///
14842 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14843 /// trailing-type-specifier) other than one in an alias-declaration.
14844 ///
14845 /// \param SkipBody If non-null, will be set to indicate if the caller should
14846 /// skip the definition of this tag and treat it as if it were a declaration.
14847 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14848                      SourceLocation KWLoc, CXXScopeSpec &SS,
14849                      IdentifierInfo *Name, SourceLocation NameLoc,
14850                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14851                      SourceLocation ModulePrivateLoc,
14852                      MultiTemplateParamsArg TemplateParameterLists,
14853                      bool &OwnedDecl, bool &IsDependent,
14854                      SourceLocation ScopedEnumKWLoc,
14855                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14856                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14857                      SkipBodyInfo *SkipBody) {
14858   // If this is not a definition, it must have a name.
14859   IdentifierInfo *OrigName = Name;
14860   assert((Name != nullptr || TUK == TUK_Definition) &&
14861          "Nameless record must be a definition!");
14862   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14863
14864   OwnedDecl = false;
14865   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14866   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14867
14868   // FIXME: Check member specializations more carefully.
14869   bool isMemberSpecialization = false;
14870   bool Invalid = false;
14871
14872   // We only need to do this matching if we have template parameters
14873   // or a scope specifier, which also conveniently avoids this work
14874   // for non-C++ cases.
14875   if (TemplateParameterLists.size() > 0 ||
14876       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14877     if (TemplateParameterList *TemplateParams =
14878             MatchTemplateParametersToScopeSpecifier(
14879                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14880                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14881       if (Kind == TTK_Enum) {
14882         Diag(KWLoc, diag::err_enum_template);
14883         return nullptr;
14884       }
14885
14886       if (TemplateParams->size() > 0) {
14887         // This is a declaration or definition of a class template (which may
14888         // be a member of another template).
14889
14890         if (Invalid)
14891           return nullptr;
14892
14893         OwnedDecl = false;
14894         DeclResult Result = CheckClassTemplate(
14895             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14896             AS, ModulePrivateLoc,
14897             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14898             TemplateParameterLists.data(), SkipBody);
14899         return Result.get();
14900       } else {
14901         // The "template<>" header is extraneous.
14902         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14903           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14904         isMemberSpecialization = true;
14905       }
14906     }
14907   }
14908
14909   // Figure out the underlying type if this a enum declaration. We need to do
14910   // this early, because it's needed to detect if this is an incompatible
14911   // redeclaration.
14912   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14913   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14914
14915   if (Kind == TTK_Enum) {
14916     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14917       // No underlying type explicitly specified, or we failed to parse the
14918       // type, default to int.
14919       EnumUnderlying = Context.IntTy.getTypePtr();
14920     } else if (UnderlyingType.get()) {
14921       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14922       // integral type; any cv-qualification is ignored.
14923       TypeSourceInfo *TI = nullptr;
14924       GetTypeFromParser(UnderlyingType.get(), &TI);
14925       EnumUnderlying = TI;
14926
14927       if (CheckEnumUnderlyingType(TI))
14928         // Recover by falling back to int.
14929         EnumUnderlying = Context.IntTy.getTypePtr();
14930
14931       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14932                                           UPPC_FixedUnderlyingType))
14933         EnumUnderlying = Context.IntTy.getTypePtr();
14934
14935     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14936       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14937       // of 'int'. However, if this is an unfixed forward declaration, don't set
14938       // the underlying type unless the user enables -fms-compatibility. This
14939       // makes unfixed forward declared enums incomplete and is more conforming.
14940       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14941         EnumUnderlying = Context.IntTy.getTypePtr();
14942     }
14943   }
14944
14945   DeclContext *SearchDC = CurContext;
14946   DeclContext *DC = CurContext;
14947   bool isStdBadAlloc = false;
14948   bool isStdAlignValT = false;
14949
14950   RedeclarationKind Redecl = forRedeclarationInCurContext();
14951   if (TUK == TUK_Friend || TUK == TUK_Reference)
14952     Redecl = NotForRedeclaration;
14953
14954   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14955   /// implemented asks for structural equivalence checking, the returned decl
14956   /// here is passed back to the parser, allowing the tag body to be parsed.
14957   auto createTagFromNewDecl = [&]() -> TagDecl * {
14958     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14959     // If there is an identifier, use the location of the identifier as the
14960     // location of the decl, otherwise use the location of the struct/union
14961     // keyword.
14962     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14963     TagDecl *New = nullptr;
14964
14965     if (Kind == TTK_Enum) {
14966       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14967                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14968       // If this is an undefined enum, bail.
14969       if (TUK != TUK_Definition && !Invalid)
14970         return nullptr;
14971       if (EnumUnderlying) {
14972         EnumDecl *ED = cast<EnumDecl>(New);
14973         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14974           ED->setIntegerTypeSourceInfo(TI);
14975         else
14976           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14977         ED->setPromotionType(ED->getIntegerType());
14978       }
14979     } else { // struct/union
14980       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14981                                nullptr);
14982     }
14983
14984     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14985       // Add alignment attributes if necessary; these attributes are checked
14986       // when the ASTContext lays out the structure.
14987       //
14988       // It is important for implementing the correct semantics that this
14989       // happen here (in ActOnTag). The #pragma pack stack is
14990       // maintained as a result of parser callbacks which can occur at
14991       // many points during the parsing of a struct declaration (because
14992       // the #pragma tokens are effectively skipped over during the
14993       // parsing of the struct).
14994       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14995         AddAlignmentAttributesForRecord(RD);
14996         AddMsStructLayoutForRecord(RD);
14997       }
14998     }
14999     New->setLexicalDeclContext(CurContext);
15000     return New;
15001   };
15002
15003   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15004   if (Name && SS.isNotEmpty()) {
15005     // We have a nested-name tag ('struct foo::bar').
15006
15007     // Check for invalid 'foo::'.
15008     if (SS.isInvalid()) {
15009       Name = nullptr;
15010       goto CreateNewDecl;
15011     }
15012
15013     // If this is a friend or a reference to a class in a dependent
15014     // context, don't try to make a decl for it.
15015     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15016       DC = computeDeclContext(SS, false);
15017       if (!DC) {
15018         IsDependent = true;
15019         return nullptr;
15020       }
15021     } else {
15022       DC = computeDeclContext(SS, true);
15023       if (!DC) {
15024         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15025           << SS.getRange();
15026         return nullptr;
15027       }
15028     }
15029
15030     if (RequireCompleteDeclContext(SS, DC))
15031       return nullptr;
15032
15033     SearchDC = DC;
15034     // Look-up name inside 'foo::'.
15035     LookupQualifiedName(Previous, DC);
15036
15037     if (Previous.isAmbiguous())
15038       return nullptr;
15039
15040     if (Previous.empty()) {
15041       // Name lookup did not find anything. However, if the
15042       // nested-name-specifier refers to the current instantiation,
15043       // and that current instantiation has any dependent base
15044       // classes, we might find something at instantiation time: treat
15045       // this as a dependent elaborated-type-specifier.
15046       // But this only makes any sense for reference-like lookups.
15047       if (Previous.wasNotFoundInCurrentInstantiation() &&
15048           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15049         IsDependent = true;
15050         return nullptr;
15051       }
15052
15053       // A tag 'foo::bar' must already exist.
15054       Diag(NameLoc, diag::err_not_tag_in_scope)
15055         << Kind << Name << DC << SS.getRange();
15056       Name = nullptr;
15057       Invalid = true;
15058       goto CreateNewDecl;
15059     }
15060   } else if (Name) {
15061     // C++14 [class.mem]p14:
15062     //   If T is the name of a class, then each of the following shall have a
15063     //   name different from T:
15064     //    -- every member of class T that is itself a type
15065     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15066         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15067       return nullptr;
15068
15069     // If this is a named struct, check to see if there was a previous forward
15070     // declaration or definition.
15071     // FIXME: We're looking into outer scopes here, even when we
15072     // shouldn't be. Doing so can result in ambiguities that we
15073     // shouldn't be diagnosing.
15074     LookupName(Previous, S);
15075
15076     // When declaring or defining a tag, ignore ambiguities introduced
15077     // by types using'ed into this scope.
15078     if (Previous.isAmbiguous() &&
15079         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15080       LookupResult::Filter F = Previous.makeFilter();
15081       while (F.hasNext()) {
15082         NamedDecl *ND = F.next();
15083         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15084                 SearchDC->getRedeclContext()))
15085           F.erase();
15086       }
15087       F.done();
15088     }
15089
15090     // C++11 [namespace.memdef]p3:
15091     //   If the name in a friend declaration is neither qualified nor
15092     //   a template-id and the declaration is a function or an
15093     //   elaborated-type-specifier, the lookup to determine whether
15094     //   the entity has been previously declared shall not consider
15095     //   any scopes outside the innermost enclosing namespace.
15096     //
15097     // MSVC doesn't implement the above rule for types, so a friend tag
15098     // declaration may be a redeclaration of a type declared in an enclosing
15099     // scope.  They do implement this rule for friend functions.
15100     //
15101     // Does it matter that this should be by scope instead of by
15102     // semantic context?
15103     if (!Previous.empty() && TUK == TUK_Friend) {
15104       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15105       LookupResult::Filter F = Previous.makeFilter();
15106       bool FriendSawTagOutsideEnclosingNamespace = false;
15107       while (F.hasNext()) {
15108         NamedDecl *ND = F.next();
15109         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15110         if (DC->isFileContext() &&
15111             !EnclosingNS->Encloses(ND->getDeclContext())) {
15112           if (getLangOpts().MSVCCompat)
15113             FriendSawTagOutsideEnclosingNamespace = true;
15114           else
15115             F.erase();
15116         }
15117       }
15118       F.done();
15119
15120       // Diagnose this MSVC extension in the easy case where lookup would have
15121       // unambiguously found something outside the enclosing namespace.
15122       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15123         NamedDecl *ND = Previous.getFoundDecl();
15124         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15125             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15126       }
15127     }
15128
15129     // Note:  there used to be some attempt at recovery here.
15130     if (Previous.isAmbiguous())
15131       return nullptr;
15132
15133     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15134       // FIXME: This makes sure that we ignore the contexts associated
15135       // with C structs, unions, and enums when looking for a matching
15136       // tag declaration or definition. See the similar lookup tweak
15137       // in Sema::LookupName; is there a better way to deal with this?
15138       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15139         SearchDC = SearchDC->getParent();
15140     }
15141   }
15142
15143   if (Previous.isSingleResult() &&
15144       Previous.getFoundDecl()->isTemplateParameter()) {
15145     // Maybe we will complain about the shadowed template parameter.
15146     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15147     // Just pretend that we didn't see the previous declaration.
15148     Previous.clear();
15149   }
15150
15151   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15152       DC->Equals(getStdNamespace())) {
15153     if (Name->isStr("bad_alloc")) {
15154       // This is a declaration of or a reference to "std::bad_alloc".
15155       isStdBadAlloc = true;
15156
15157       // If std::bad_alloc has been implicitly declared (but made invisible to
15158       // name lookup), fill in this implicit declaration as the previous
15159       // declaration, so that the declarations get chained appropriately.
15160       if (Previous.empty() && StdBadAlloc)
15161         Previous.addDecl(getStdBadAlloc());
15162     } else if (Name->isStr("align_val_t")) {
15163       isStdAlignValT = true;
15164       if (Previous.empty() && StdAlignValT)
15165         Previous.addDecl(getStdAlignValT());
15166     }
15167   }
15168
15169   // If we didn't find a previous declaration, and this is a reference
15170   // (or friend reference), move to the correct scope.  In C++, we
15171   // also need to do a redeclaration lookup there, just in case
15172   // there's a shadow friend decl.
15173   if (Name && Previous.empty() &&
15174       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15175     if (Invalid) goto CreateNewDecl;
15176     assert(SS.isEmpty());
15177
15178     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15179       // C++ [basic.scope.pdecl]p5:
15180       //   -- for an elaborated-type-specifier of the form
15181       //
15182       //          class-key identifier
15183       //
15184       //      if the elaborated-type-specifier is used in the
15185       //      decl-specifier-seq or parameter-declaration-clause of a
15186       //      function defined in namespace scope, the identifier is
15187       //      declared as a class-name in the namespace that contains
15188       //      the declaration; otherwise, except as a friend
15189       //      declaration, the identifier is declared in the smallest
15190       //      non-class, non-function-prototype scope that contains the
15191       //      declaration.
15192       //
15193       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15194       // C structs and unions.
15195       //
15196       // It is an error in C++ to declare (rather than define) an enum
15197       // type, including via an elaborated type specifier.  We'll
15198       // diagnose that later; for now, declare the enum in the same
15199       // scope as we would have picked for any other tag type.
15200       //
15201       // GNU C also supports this behavior as part of its incomplete
15202       // enum types extension, while GNU C++ does not.
15203       //
15204       // Find the context where we'll be declaring the tag.
15205       // FIXME: We would like to maintain the current DeclContext as the
15206       // lexical context,
15207       SearchDC = getTagInjectionContext(SearchDC);
15208
15209       // Find the scope where we'll be declaring the tag.
15210       S = getTagInjectionScope(S, getLangOpts());
15211     } else {
15212       assert(TUK == TUK_Friend);
15213       // C++ [namespace.memdef]p3:
15214       //   If a friend declaration in a non-local class first declares a
15215       //   class or function, the friend class or function is a member of
15216       //   the innermost enclosing namespace.
15217       SearchDC = SearchDC->getEnclosingNamespaceContext();
15218     }
15219
15220     // In C++, we need to do a redeclaration lookup to properly
15221     // diagnose some problems.
15222     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15223     // hidden declaration so that we don't get ambiguity errors when using a
15224     // type declared by an elaborated-type-specifier.  In C that is not correct
15225     // and we should instead merge compatible types found by lookup.
15226     if (getLangOpts().CPlusPlus) {
15227       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15228       LookupQualifiedName(Previous, SearchDC);
15229     } else {
15230       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15231       LookupName(Previous, S);
15232     }
15233   }
15234
15235   // If we have a known previous declaration to use, then use it.
15236   if (Previous.empty() && SkipBody && SkipBody->Previous)
15237     Previous.addDecl(SkipBody->Previous);
15238
15239   if (!Previous.empty()) {
15240     NamedDecl *PrevDecl = Previous.getFoundDecl();
15241     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15242
15243     // It's okay to have a tag decl in the same scope as a typedef
15244     // which hides a tag decl in the same scope.  Finding this
15245     // insanity with a redeclaration lookup can only actually happen
15246     // in C++.
15247     //
15248     // This is also okay for elaborated-type-specifiers, which is
15249     // technically forbidden by the current standard but which is
15250     // okay according to the likely resolution of an open issue;
15251     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15252     if (getLangOpts().CPlusPlus) {
15253       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15254         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15255           TagDecl *Tag = TT->getDecl();
15256           if (Tag->getDeclName() == Name &&
15257               Tag->getDeclContext()->getRedeclContext()
15258                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15259             PrevDecl = Tag;
15260             Previous.clear();
15261             Previous.addDecl(Tag);
15262             Previous.resolveKind();
15263           }
15264         }
15265       }
15266     }
15267
15268     // If this is a redeclaration of a using shadow declaration, it must
15269     // declare a tag in the same context. In MSVC mode, we allow a
15270     // redefinition if either context is within the other.
15271     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15272       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15273       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15274           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15275           !(OldTag && isAcceptableTagRedeclContext(
15276                           *this, OldTag->getDeclContext(), SearchDC))) {
15277         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15278         Diag(Shadow->getTargetDecl()->getLocation(),
15279              diag::note_using_decl_target);
15280         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15281             << 0;
15282         // Recover by ignoring the old declaration.
15283         Previous.clear();
15284         goto CreateNewDecl;
15285       }
15286     }
15287
15288     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15289       // If this is a use of a previous tag, or if the tag is already declared
15290       // in the same scope (so that the definition/declaration completes or
15291       // rementions the tag), reuse the decl.
15292       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15293           isDeclInScope(DirectPrevDecl, SearchDC, S,
15294                         SS.isNotEmpty() || isMemberSpecialization)) {
15295         // Make sure that this wasn't declared as an enum and now used as a
15296         // struct or something similar.
15297         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15298                                           TUK == TUK_Definition, KWLoc,
15299                                           Name)) {
15300           bool SafeToContinue
15301             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15302                Kind != TTK_Enum);
15303           if (SafeToContinue)
15304             Diag(KWLoc, diag::err_use_with_wrong_tag)
15305               << Name
15306               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15307                                               PrevTagDecl->getKindName());
15308           else
15309             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15310           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15311
15312           if (SafeToContinue)
15313             Kind = PrevTagDecl->getTagKind();
15314           else {
15315             // Recover by making this an anonymous redefinition.
15316             Name = nullptr;
15317             Previous.clear();
15318             Invalid = true;
15319           }
15320         }
15321
15322         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15323           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15324
15325           // If this is an elaborated-type-specifier for a scoped enumeration,
15326           // the 'class' keyword is not necessary and not permitted.
15327           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15328             if (ScopedEnum)
15329               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15330                 << PrevEnum->isScoped()
15331                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15332             return PrevTagDecl;
15333           }
15334
15335           QualType EnumUnderlyingTy;
15336           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15337             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15338           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15339             EnumUnderlyingTy = QualType(T, 0);
15340
15341           // All conflicts with previous declarations are recovered by
15342           // returning the previous declaration, unless this is a definition,
15343           // in which case we want the caller to bail out.
15344           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15345                                      ScopedEnum, EnumUnderlyingTy,
15346                                      IsFixed, PrevEnum))
15347             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15348         }
15349
15350         // C++11 [class.mem]p1:
15351         //   A member shall not be declared twice in the member-specification,
15352         //   except that a nested class or member class template can be declared
15353         //   and then later defined.
15354         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15355             S->isDeclScope(PrevDecl)) {
15356           Diag(NameLoc, diag::ext_member_redeclared);
15357           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15358         }
15359
15360         if (!Invalid) {
15361           // If this is a use, just return the declaration we found, unless
15362           // we have attributes.
15363           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15364             if (!Attrs.empty()) {
15365               // FIXME: Diagnose these attributes. For now, we create a new
15366               // declaration to hold them.
15367             } else if (TUK == TUK_Reference &&
15368                        (PrevTagDecl->getFriendObjectKind() ==
15369                             Decl::FOK_Undeclared ||
15370                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15371                        SS.isEmpty()) {
15372               // This declaration is a reference to an existing entity, but
15373               // has different visibility from that entity: it either makes
15374               // a friend visible or it makes a type visible in a new module.
15375               // In either case, create a new declaration. We only do this if
15376               // the declaration would have meant the same thing if no prior
15377               // declaration were found, that is, if it was found in the same
15378               // scope where we would have injected a declaration.
15379               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15380                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15381                 return PrevTagDecl;
15382               // This is in the injected scope, create a new declaration in
15383               // that scope.
15384               S = getTagInjectionScope(S, getLangOpts());
15385             } else {
15386               return PrevTagDecl;
15387             }
15388           }
15389
15390           // Diagnose attempts to redefine a tag.
15391           if (TUK == TUK_Definition) {
15392             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15393               // If we're defining a specialization and the previous definition
15394               // is from an implicit instantiation, don't emit an error
15395               // here; we'll catch this in the general case below.
15396               bool IsExplicitSpecializationAfterInstantiation = false;
15397               if (isMemberSpecialization) {
15398                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15399                   IsExplicitSpecializationAfterInstantiation =
15400                     RD->getTemplateSpecializationKind() !=
15401                     TSK_ExplicitSpecialization;
15402                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15403                   IsExplicitSpecializationAfterInstantiation =
15404                     ED->getTemplateSpecializationKind() !=
15405                     TSK_ExplicitSpecialization;
15406               }
15407
15408               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15409               // not keep more that one definition around (merge them). However,
15410               // ensure the decl passes the structural compatibility check in
15411               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15412               NamedDecl *Hidden = nullptr;
15413               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15414                 // There is a definition of this tag, but it is not visible. We
15415                 // explicitly make use of C++'s one definition rule here, and
15416                 // assume that this definition is identical to the hidden one
15417                 // we already have. Make the existing definition visible and
15418                 // use it in place of this one.
15419                 if (!getLangOpts().CPlusPlus) {
15420                   // Postpone making the old definition visible until after we
15421                   // complete parsing the new one and do the structural
15422                   // comparison.
15423                   SkipBody->CheckSameAsPrevious = true;
15424                   SkipBody->New = createTagFromNewDecl();
15425                   SkipBody->Previous = Def;
15426                   return Def;
15427                 } else {
15428                   SkipBody->ShouldSkip = true;
15429                   SkipBody->Previous = Def;
15430                   makeMergedDefinitionVisible(Hidden);
15431                   // Carry on and handle it like a normal definition. We'll
15432                   // skip starting the definitiion later.
15433                 }
15434               } else if (!IsExplicitSpecializationAfterInstantiation) {
15435                 // A redeclaration in function prototype scope in C isn't
15436                 // visible elsewhere, so merely issue a warning.
15437                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15438                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15439                 else
15440                   Diag(NameLoc, diag::err_redefinition) << Name;
15441                 notePreviousDefinition(Def,
15442                                        NameLoc.isValid() ? NameLoc : KWLoc);
15443                 // If this is a redefinition, recover by making this
15444                 // struct be anonymous, which will make any later
15445                 // references get the previous definition.
15446                 Name = nullptr;
15447                 Previous.clear();
15448                 Invalid = true;
15449               }
15450             } else {
15451               // If the type is currently being defined, complain
15452               // about a nested redefinition.
15453               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15454               if (TD->isBeingDefined()) {
15455                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15456                 Diag(PrevTagDecl->getLocation(),
15457                      diag::note_previous_definition);
15458                 Name = nullptr;
15459                 Previous.clear();
15460                 Invalid = true;
15461               }
15462             }
15463
15464             // Okay, this is definition of a previously declared or referenced
15465             // tag. We're going to create a new Decl for it.
15466           }
15467
15468           // Okay, we're going to make a redeclaration.  If this is some kind
15469           // of reference, make sure we build the redeclaration in the same DC
15470           // as the original, and ignore the current access specifier.
15471           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15472             SearchDC = PrevTagDecl->getDeclContext();
15473             AS = AS_none;
15474           }
15475         }
15476         // If we get here we have (another) forward declaration or we
15477         // have a definition.  Just create a new decl.
15478
15479       } else {
15480         // If we get here, this is a definition of a new tag type in a nested
15481         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15482         // new decl/type.  We set PrevDecl to NULL so that the entities
15483         // have distinct types.
15484         Previous.clear();
15485       }
15486       // If we get here, we're going to create a new Decl. If PrevDecl
15487       // is non-NULL, it's a definition of the tag declared by
15488       // PrevDecl. If it's NULL, we have a new definition.
15489
15490     // Otherwise, PrevDecl is not a tag, but was found with tag
15491     // lookup.  This is only actually possible in C++, where a few
15492     // things like templates still live in the tag namespace.
15493     } else {
15494       // Use a better diagnostic if an elaborated-type-specifier
15495       // found the wrong kind of type on the first
15496       // (non-redeclaration) lookup.
15497       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15498           !Previous.isForRedeclaration()) {
15499         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15500         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15501                                                        << Kind;
15502         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15503         Invalid = true;
15504
15505       // Otherwise, only diagnose if the declaration is in scope.
15506       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15507                                 SS.isNotEmpty() || isMemberSpecialization)) {
15508         // do nothing
15509
15510       // Diagnose implicit declarations introduced by elaborated types.
15511       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15512         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15513         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15514         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15515         Invalid = true;
15516
15517       // Otherwise it's a declaration.  Call out a particularly common
15518       // case here.
15519       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15520         unsigned Kind = 0;
15521         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15522         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15523           << Name << Kind << TND->getUnderlyingType();
15524         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15525         Invalid = true;
15526
15527       // Otherwise, diagnose.
15528       } else {
15529         // The tag name clashes with something else in the target scope,
15530         // issue an error and recover by making this tag be anonymous.
15531         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15532         notePreviousDefinition(PrevDecl, NameLoc);
15533         Name = nullptr;
15534         Invalid = true;
15535       }
15536
15537       // The existing declaration isn't relevant to us; we're in a
15538       // new scope, so clear out the previous declaration.
15539       Previous.clear();
15540     }
15541   }
15542
15543 CreateNewDecl:
15544
15545   TagDecl *PrevDecl = nullptr;
15546   if (Previous.isSingleResult())
15547     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15548
15549   // If there is an identifier, use the location of the identifier as the
15550   // location of the decl, otherwise use the location of the struct/union
15551   // keyword.
15552   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15553
15554   // Otherwise, create a new declaration. If there is a previous
15555   // declaration of the same entity, the two will be linked via
15556   // PrevDecl.
15557   TagDecl *New;
15558
15559   if (Kind == TTK_Enum) {
15560     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15561     // enum X { A, B, C } D;    D should chain to X.
15562     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15563                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15564                            ScopedEnumUsesClassTag, IsFixed);
15565
15566     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15567       StdAlignValT = cast<EnumDecl>(New);
15568
15569     // If this is an undefined enum, warn.
15570     if (TUK != TUK_Definition && !Invalid) {
15571       TagDecl *Def;
15572       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15573         // C++0x: 7.2p2: opaque-enum-declaration.
15574         // Conflicts are diagnosed above. Do nothing.
15575       }
15576       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15577         Diag(Loc, diag::ext_forward_ref_enum_def)
15578           << New;
15579         Diag(Def->getLocation(), diag::note_previous_definition);
15580       } else {
15581         unsigned DiagID = diag::ext_forward_ref_enum;
15582         if (getLangOpts().MSVCCompat)
15583           DiagID = diag::ext_ms_forward_ref_enum;
15584         else if (getLangOpts().CPlusPlus)
15585           DiagID = diag::err_forward_ref_enum;
15586         Diag(Loc, DiagID);
15587       }
15588     }
15589
15590     if (EnumUnderlying) {
15591       EnumDecl *ED = cast<EnumDecl>(New);
15592       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15593         ED->setIntegerTypeSourceInfo(TI);
15594       else
15595         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15596       ED->setPromotionType(ED->getIntegerType());
15597       assert(ED->isComplete() && "enum with type should be complete");
15598     }
15599   } else {
15600     // struct/union/class
15601
15602     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15603     // struct X { int A; } D;    D should chain to X.
15604     if (getLangOpts().CPlusPlus) {
15605       // FIXME: Look for a way to use RecordDecl for simple structs.
15606       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15607                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15608
15609       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15610         StdBadAlloc = cast<CXXRecordDecl>(New);
15611     } else
15612       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15613                                cast_or_null<RecordDecl>(PrevDecl));
15614   }
15615
15616   // C++11 [dcl.type]p3:
15617   //   A type-specifier-seq shall not define a class or enumeration [...].
15618   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15619       TUK == TUK_Definition) {
15620     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15621       << Context.getTagDeclType(New);
15622     Invalid = true;
15623   }
15624
15625   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15626       DC->getDeclKind() == Decl::Enum) {
15627     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15628       << Context.getTagDeclType(New);
15629     Invalid = true;
15630   }
15631
15632   // Maybe add qualifier info.
15633   if (SS.isNotEmpty()) {
15634     if (SS.isSet()) {
15635       // If this is either a declaration or a definition, check the
15636       // nested-name-specifier against the current context.
15637       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15638           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15639                                        isMemberSpecialization))
15640         Invalid = true;
15641
15642       New->setQualifierInfo(SS.getWithLocInContext(Context));
15643       if (TemplateParameterLists.size() > 0) {
15644         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15645       }
15646     }
15647     else
15648       Invalid = true;
15649   }
15650
15651   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15652     // Add alignment attributes if necessary; these attributes are checked when
15653     // the ASTContext lays out the structure.
15654     //
15655     // It is important for implementing the correct semantics that this
15656     // happen here (in ActOnTag). The #pragma pack stack is
15657     // maintained as a result of parser callbacks which can occur at
15658     // many points during the parsing of a struct declaration (because
15659     // the #pragma tokens are effectively skipped over during the
15660     // parsing of the struct).
15661     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15662       AddAlignmentAttributesForRecord(RD);
15663       AddMsStructLayoutForRecord(RD);
15664     }
15665   }
15666
15667   if (ModulePrivateLoc.isValid()) {
15668     if (isMemberSpecialization)
15669       Diag(New->getLocation(), diag::err_module_private_specialization)
15670         << 2
15671         << FixItHint::CreateRemoval(ModulePrivateLoc);
15672     // __module_private__ does not apply to local classes. However, we only
15673     // diagnose this as an error when the declaration specifiers are
15674     // freestanding. Here, we just ignore the __module_private__.
15675     else if (!SearchDC->isFunctionOrMethod())
15676       New->setModulePrivate();
15677   }
15678
15679   // If this is a specialization of a member class (of a class template),
15680   // check the specialization.
15681   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15682     Invalid = true;
15683
15684   // If we're declaring or defining a tag in function prototype scope in C,
15685   // note that this type can only be used within the function and add it to
15686   // the list of decls to inject into the function definition scope.
15687   if ((Name || Kind == TTK_Enum) &&
15688       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15689     if (getLangOpts().CPlusPlus) {
15690       // C++ [dcl.fct]p6:
15691       //   Types shall not be defined in return or parameter types.
15692       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15693         Diag(Loc, diag::err_type_defined_in_param_type)
15694             << Name;
15695         Invalid = true;
15696       }
15697     } else if (!PrevDecl) {
15698       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15699     }
15700   }
15701
15702   if (Invalid)
15703     New->setInvalidDecl();
15704
15705   // Set the lexical context. If the tag has a C++ scope specifier, the
15706   // lexical context will be different from the semantic context.
15707   New->setLexicalDeclContext(CurContext);
15708
15709   // Mark this as a friend decl if applicable.
15710   // In Microsoft mode, a friend declaration also acts as a forward
15711   // declaration so we always pass true to setObjectOfFriendDecl to make
15712   // the tag name visible.
15713   if (TUK == TUK_Friend)
15714     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15715
15716   // Set the access specifier.
15717   if (!Invalid && SearchDC->isRecord())
15718     SetMemberAccessSpecifier(New, PrevDecl, AS);
15719
15720   if (PrevDecl)
15721     CheckRedeclarationModuleOwnership(New, PrevDecl);
15722
15723   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15724     New->startDefinition();
15725
15726   ProcessDeclAttributeList(S, New, Attrs);
15727   AddPragmaAttributes(S, New);
15728
15729   // If this has an identifier, add it to the scope stack.
15730   if (TUK == TUK_Friend) {
15731     // We might be replacing an existing declaration in the lookup tables;
15732     // if so, borrow its access specifier.
15733     if (PrevDecl)
15734       New->setAccess(PrevDecl->getAccess());
15735
15736     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15737     DC->makeDeclVisibleInContext(New);
15738     if (Name) // can be null along some error paths
15739       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15740         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15741   } else if (Name) {
15742     S = getNonFieldDeclScope(S);
15743     PushOnScopeChains(New, S, true);
15744   } else {
15745     CurContext->addDecl(New);
15746   }
15747
15748   // If this is the C FILE type, notify the AST context.
15749   if (IdentifierInfo *II = New->getIdentifier())
15750     if (!New->isInvalidDecl() &&
15751         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15752         II->isStr("FILE"))
15753       Context.setFILEDecl(New);
15754
15755   if (PrevDecl)
15756     mergeDeclAttributes(New, PrevDecl);
15757
15758   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15759     inferGslOwnerPointerAttribute(CXXRD);
15760
15761   // If there's a #pragma GCC visibility in scope, set the visibility of this
15762   // record.
15763   AddPushedVisibilityAttribute(New);
15764
15765   if (isMemberSpecialization && !New->isInvalidDecl())
15766     CompleteMemberSpecialization(New, Previous);
15767
15768   OwnedDecl = true;
15769   // In C++, don't return an invalid declaration. We can't recover well from
15770   // the cases where we make the type anonymous.
15771   if (Invalid && getLangOpts().CPlusPlus) {
15772     if (New->isBeingDefined())
15773       if (auto RD = dyn_cast<RecordDecl>(New))
15774         RD->completeDefinition();
15775     return nullptr;
15776   } else if (SkipBody && SkipBody->ShouldSkip) {
15777     return SkipBody->Previous;
15778   } else {
15779     return New;
15780   }
15781 }
15782
15783 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15784   AdjustDeclIfTemplate(TagD);
15785   TagDecl *Tag = cast<TagDecl>(TagD);
15786
15787   // Enter the tag context.
15788   PushDeclContext(S, Tag);
15789
15790   ActOnDocumentableDecl(TagD);
15791
15792   // If there's a #pragma GCC visibility in scope, set the visibility of this
15793   // record.
15794   AddPushedVisibilityAttribute(Tag);
15795 }
15796
15797 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15798                                     SkipBodyInfo &SkipBody) {
15799   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15800     return false;
15801
15802   // Make the previous decl visible.
15803   makeMergedDefinitionVisible(SkipBody.Previous);
15804   return true;
15805 }
15806
15807 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15808   assert(isa<ObjCContainerDecl>(IDecl) &&
15809          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15810   DeclContext *OCD = cast<DeclContext>(IDecl);
15811   assert(getContainingDC(OCD) == CurContext &&
15812       "The next DeclContext should be lexically contained in the current one.");
15813   CurContext = OCD;
15814   return IDecl;
15815 }
15816
15817 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15818                                            SourceLocation FinalLoc,
15819                                            bool IsFinalSpelledSealed,
15820                                            SourceLocation LBraceLoc) {
15821   AdjustDeclIfTemplate(TagD);
15822   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15823
15824   FieldCollector->StartClass();
15825
15826   if (!Record->getIdentifier())
15827     return;
15828
15829   if (FinalLoc.isValid())
15830     Record->addAttr(FinalAttr::Create(
15831         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15832         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15833
15834   // C++ [class]p2:
15835   //   [...] The class-name is also inserted into the scope of the
15836   //   class itself; this is known as the injected-class-name. For
15837   //   purposes of access checking, the injected-class-name is treated
15838   //   as if it were a public member name.
15839   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15840       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15841       Record->getLocation(), Record->getIdentifier(),
15842       /*PrevDecl=*/nullptr,
15843       /*DelayTypeCreation=*/true);
15844   Context.getTypeDeclType(InjectedClassName, Record);
15845   InjectedClassName->setImplicit();
15846   InjectedClassName->setAccess(AS_public);
15847   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15848       InjectedClassName->setDescribedClassTemplate(Template);
15849   PushOnScopeChains(InjectedClassName, S);
15850   assert(InjectedClassName->isInjectedClassName() &&
15851          "Broken injected-class-name");
15852 }
15853
15854 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15855                                     SourceRange BraceRange) {
15856   AdjustDeclIfTemplate(TagD);
15857   TagDecl *Tag = cast<TagDecl>(TagD);
15858   Tag->setBraceRange(BraceRange);
15859
15860   // Make sure we "complete" the definition even it is invalid.
15861   if (Tag->isBeingDefined()) {
15862     assert(Tag->isInvalidDecl() && "We should already have completed it");
15863     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15864       RD->completeDefinition();
15865   }
15866
15867   if (isa<CXXRecordDecl>(Tag)) {
15868     FieldCollector->FinishClass();
15869   }
15870
15871   // Exit this scope of this tag's definition.
15872   PopDeclContext();
15873
15874   if (getCurLexicalContext()->isObjCContainer() &&
15875       Tag->getDeclContext()->isFileContext())
15876     Tag->setTopLevelDeclInObjCContainer();
15877
15878   // Notify the consumer that we've defined a tag.
15879   if (!Tag->isInvalidDecl())
15880     Consumer.HandleTagDeclDefinition(Tag);
15881 }
15882
15883 void Sema::ActOnObjCContainerFinishDefinition() {
15884   // Exit this scope of this interface definition.
15885   PopDeclContext();
15886 }
15887
15888 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15889   assert(DC == CurContext && "Mismatch of container contexts");
15890   OriginalLexicalContext = DC;
15891   ActOnObjCContainerFinishDefinition();
15892 }
15893
15894 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15895   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15896   OriginalLexicalContext = nullptr;
15897 }
15898
15899 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15900   AdjustDeclIfTemplate(TagD);
15901   TagDecl *Tag = cast<TagDecl>(TagD);
15902   Tag->setInvalidDecl();
15903
15904   // Make sure we "complete" the definition even it is invalid.
15905   if (Tag->isBeingDefined()) {
15906     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15907       RD->completeDefinition();
15908   }
15909
15910   // We're undoing ActOnTagStartDefinition here, not
15911   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15912   // the FieldCollector.
15913
15914   PopDeclContext();
15915 }
15916
15917 // Note that FieldName may be null for anonymous bitfields.
15918 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15919                                 IdentifierInfo *FieldName,
15920                                 QualType FieldTy, bool IsMsStruct,
15921                                 Expr *BitWidth, bool *ZeroWidth) {
15922   // Default to true; that shouldn't confuse checks for emptiness
15923   if (ZeroWidth)
15924     *ZeroWidth = true;
15925
15926   // C99 6.7.2.1p4 - verify the field type.
15927   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15928   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15929     // Handle incomplete types with specific error.
15930     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15931       return ExprError();
15932     if (FieldName)
15933       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15934         << FieldName << FieldTy << BitWidth->getSourceRange();
15935     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15936       << FieldTy << BitWidth->getSourceRange();
15937   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15938                                              UPPC_BitFieldWidth))
15939     return ExprError();
15940
15941   // If the bit-width is type- or value-dependent, don't try to check
15942   // it now.
15943   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15944     return BitWidth;
15945
15946   llvm::APSInt Value;
15947   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15948   if (ICE.isInvalid())
15949     return ICE;
15950   BitWidth = ICE.get();
15951
15952   if (Value != 0 && ZeroWidth)
15953     *ZeroWidth = false;
15954
15955   // Zero-width bitfield is ok for anonymous field.
15956   if (Value == 0 && FieldName)
15957     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15958
15959   if (Value.isSigned() && Value.isNegative()) {
15960     if (FieldName)
15961       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15962                << FieldName << Value.toString(10);
15963     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15964       << Value.toString(10);
15965   }
15966
15967   if (!FieldTy->isDependentType()) {
15968     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15969     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15970     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15971
15972     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15973     // ABI.
15974     bool CStdConstraintViolation =
15975         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15976     bool MSBitfieldViolation =
15977         Value.ugt(TypeStorageSize) &&
15978         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15979     if (CStdConstraintViolation || MSBitfieldViolation) {
15980       unsigned DiagWidth =
15981           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15982       if (FieldName)
15983         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15984                << FieldName << (unsigned)Value.getZExtValue()
15985                << !CStdConstraintViolation << DiagWidth;
15986
15987       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15988              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15989              << DiagWidth;
15990     }
15991
15992     // Warn on types where the user might conceivably expect to get all
15993     // specified bits as value bits: that's all integral types other than
15994     // 'bool'.
15995     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15996       if (FieldName)
15997         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15998             << FieldName << (unsigned)Value.getZExtValue()
15999             << (unsigned)TypeWidth;
16000       else
16001         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16002             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16003     }
16004   }
16005
16006   return BitWidth;
16007 }
16008
16009 /// ActOnField - Each field of a C struct/union is passed into this in order
16010 /// to create a FieldDecl object for it.
16011 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16012                        Declarator &D, Expr *BitfieldWidth) {
16013   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16014                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16015                                /*InitStyle=*/ICIS_NoInit, AS_public);
16016   return Res;
16017 }
16018
16019 /// HandleField - Analyze a field of a C struct or a C++ data member.
16020 ///
16021 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16022                              SourceLocation DeclStart,
16023                              Declarator &D, Expr *BitWidth,
16024                              InClassInitStyle InitStyle,
16025                              AccessSpecifier AS) {
16026   if (D.isDecompositionDeclarator()) {
16027     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16028     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16029       << Decomp.getSourceRange();
16030     return nullptr;
16031   }
16032
16033   IdentifierInfo *II = D.getIdentifier();
16034   SourceLocation Loc = DeclStart;
16035   if (II) Loc = D.getIdentifierLoc();
16036
16037   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16038   QualType T = TInfo->getType();
16039   if (getLangOpts().CPlusPlus) {
16040     CheckExtraCXXDefaultArguments(D);
16041
16042     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16043                                         UPPC_DataMemberType)) {
16044       D.setInvalidType();
16045       T = Context.IntTy;
16046       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16047     }
16048   }
16049
16050   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16051
16052   if (D.getDeclSpec().isInlineSpecified())
16053     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16054         << getLangOpts().CPlusPlus17;
16055   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16056     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16057          diag::err_invalid_thread)
16058       << DeclSpec::getSpecifierName(TSCS);
16059
16060   // Check to see if this name was declared as a member previously
16061   NamedDecl *PrevDecl = nullptr;
16062   LookupResult Previous(*this, II, Loc, LookupMemberName,
16063                         ForVisibleRedeclaration);
16064   LookupName(Previous, S);
16065   switch (Previous.getResultKind()) {
16066     case LookupResult::Found:
16067     case LookupResult::FoundUnresolvedValue:
16068       PrevDecl = Previous.getAsSingle<NamedDecl>();
16069       break;
16070
16071     case LookupResult::FoundOverloaded:
16072       PrevDecl = Previous.getRepresentativeDecl();
16073       break;
16074
16075     case LookupResult::NotFound:
16076     case LookupResult::NotFoundInCurrentInstantiation:
16077     case LookupResult::Ambiguous:
16078       break;
16079   }
16080   Previous.suppressDiagnostics();
16081
16082   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16083     // Maybe we will complain about the shadowed template parameter.
16084     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16085     // Just pretend that we didn't see the previous declaration.
16086     PrevDecl = nullptr;
16087   }
16088
16089   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16090     PrevDecl = nullptr;
16091
16092   bool Mutable
16093     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16094   SourceLocation TSSL = D.getBeginLoc();
16095   FieldDecl *NewFD
16096     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16097                      TSSL, AS, PrevDecl, &D);
16098
16099   if (NewFD->isInvalidDecl())
16100     Record->setInvalidDecl();
16101
16102   if (D.getDeclSpec().isModulePrivateSpecified())
16103     NewFD->setModulePrivate();
16104
16105   if (NewFD->isInvalidDecl() && PrevDecl) {
16106     // Don't introduce NewFD into scope; there's already something
16107     // with the same name in the same scope.
16108   } else if (II) {
16109     PushOnScopeChains(NewFD, S);
16110   } else
16111     Record->addDecl(NewFD);
16112
16113   return NewFD;
16114 }
16115
16116 /// Build a new FieldDecl and check its well-formedness.
16117 ///
16118 /// This routine builds a new FieldDecl given the fields name, type,
16119 /// record, etc. \p PrevDecl should refer to any previous declaration
16120 /// with the same name and in the same scope as the field to be
16121 /// created.
16122 ///
16123 /// \returns a new FieldDecl.
16124 ///
16125 /// \todo The Declarator argument is a hack. It will be removed once
16126 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16127                                 TypeSourceInfo *TInfo,
16128                                 RecordDecl *Record, SourceLocation Loc,
16129                                 bool Mutable, Expr *BitWidth,
16130                                 InClassInitStyle InitStyle,
16131                                 SourceLocation TSSL,
16132                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16133                                 Declarator *D) {
16134   IdentifierInfo *II = Name.getAsIdentifierInfo();
16135   bool InvalidDecl = false;
16136   if (D) InvalidDecl = D->isInvalidType();
16137
16138   // If we receive a broken type, recover by assuming 'int' and
16139   // marking this declaration as invalid.
16140   if (T.isNull()) {
16141     InvalidDecl = true;
16142     T = Context.IntTy;
16143   }
16144
16145   QualType EltTy = Context.getBaseElementType(T);
16146   if (!EltTy->isDependentType()) {
16147     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16148       // Fields of incomplete type force their record to be invalid.
16149       Record->setInvalidDecl();
16150       InvalidDecl = true;
16151     } else {
16152       NamedDecl *Def;
16153       EltTy->isIncompleteType(&Def);
16154       if (Def && Def->isInvalidDecl()) {
16155         Record->setInvalidDecl();
16156         InvalidDecl = true;
16157       }
16158     }
16159   }
16160
16161   // TR 18037 does not allow fields to be declared with address space
16162   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16163       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16164     Diag(Loc, diag::err_field_with_address_space);
16165     Record->setInvalidDecl();
16166     InvalidDecl = true;
16167   }
16168
16169   if (LangOpts.OpenCL) {
16170     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16171     // used as structure or union field: image, sampler, event or block types.
16172     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16173         T->isBlockPointerType()) {
16174       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16175       Record->setInvalidDecl();
16176       InvalidDecl = true;
16177     }
16178     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16179     if (BitWidth) {
16180       Diag(Loc, diag::err_opencl_bitfields);
16181       InvalidDecl = true;
16182     }
16183   }
16184
16185   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16186   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16187       T.hasQualifiers()) {
16188     InvalidDecl = true;
16189     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16190   }
16191
16192   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16193   // than a variably modified type.
16194   if (!InvalidDecl && T->isVariablyModifiedType()) {
16195     bool SizeIsNegative;
16196     llvm::APSInt Oversized;
16197
16198     TypeSourceInfo *FixedTInfo =
16199       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16200                                                     SizeIsNegative,
16201                                                     Oversized);
16202     if (FixedTInfo) {
16203       Diag(Loc, diag::warn_illegal_constant_array_size);
16204       TInfo = FixedTInfo;
16205       T = FixedTInfo->getType();
16206     } else {
16207       if (SizeIsNegative)
16208         Diag(Loc, diag::err_typecheck_negative_array_size);
16209       else if (Oversized.getBoolValue())
16210         Diag(Loc, diag::err_array_too_large)
16211           << Oversized.toString(10);
16212       else
16213         Diag(Loc, diag::err_typecheck_field_variable_size);
16214       InvalidDecl = true;
16215     }
16216   }
16217
16218   // Fields can not have abstract class types
16219   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16220                                              diag::err_abstract_type_in_decl,
16221                                              AbstractFieldType))
16222     InvalidDecl = true;
16223
16224   bool ZeroWidth = false;
16225   if (InvalidDecl)
16226     BitWidth = nullptr;
16227   // If this is declared as a bit-field, check the bit-field.
16228   if (BitWidth) {
16229     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16230                               &ZeroWidth).get();
16231     if (!BitWidth) {
16232       InvalidDecl = true;
16233       BitWidth = nullptr;
16234       ZeroWidth = false;
16235     }
16236   }
16237
16238   // Check that 'mutable' is consistent with the type of the declaration.
16239   if (!InvalidDecl && Mutable) {
16240     unsigned DiagID = 0;
16241     if (T->isReferenceType())
16242       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16243                                         : diag::err_mutable_reference;
16244     else if (T.isConstQualified())
16245       DiagID = diag::err_mutable_const;
16246
16247     if (DiagID) {
16248       SourceLocation ErrLoc = Loc;
16249       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16250         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16251       Diag(ErrLoc, DiagID);
16252       if (DiagID != diag::ext_mutable_reference) {
16253         Mutable = false;
16254         InvalidDecl = true;
16255       }
16256     }
16257   }
16258
16259   // C++11 [class.union]p8 (DR1460):
16260   //   At most one variant member of a union may have a
16261   //   brace-or-equal-initializer.
16262   if (InitStyle != ICIS_NoInit)
16263     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16264
16265   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16266                                        BitWidth, Mutable, InitStyle);
16267   if (InvalidDecl)
16268     NewFD->setInvalidDecl();
16269
16270   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16271     Diag(Loc, diag::err_duplicate_member) << II;
16272     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16273     NewFD->setInvalidDecl();
16274   }
16275
16276   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16277     if (Record->isUnion()) {
16278       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16279         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16280         if (RDecl->getDefinition()) {
16281           // C++ [class.union]p1: An object of a class with a non-trivial
16282           // constructor, a non-trivial copy constructor, a non-trivial
16283           // destructor, or a non-trivial copy assignment operator
16284           // cannot be a member of a union, nor can an array of such
16285           // objects.
16286           if (CheckNontrivialField(NewFD))
16287             NewFD->setInvalidDecl();
16288         }
16289       }
16290
16291       // C++ [class.union]p1: If a union contains a member of reference type,
16292       // the program is ill-formed, except when compiling with MSVC extensions
16293       // enabled.
16294       if (EltTy->isReferenceType()) {
16295         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16296                                     diag::ext_union_member_of_reference_type :
16297                                     diag::err_union_member_of_reference_type)
16298           << NewFD->getDeclName() << EltTy;
16299         if (!getLangOpts().MicrosoftExt)
16300           NewFD->setInvalidDecl();
16301       }
16302     }
16303   }
16304
16305   // FIXME: We need to pass in the attributes given an AST
16306   // representation, not a parser representation.
16307   if (D) {
16308     // FIXME: The current scope is almost... but not entirely... correct here.
16309     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16310
16311     if (NewFD->hasAttrs())
16312       CheckAlignasUnderalignment(NewFD);
16313   }
16314
16315   // In auto-retain/release, infer strong retension for fields of
16316   // retainable type.
16317   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16318     NewFD->setInvalidDecl();
16319
16320   if (T.isObjCGCWeak())
16321     Diag(Loc, diag::warn_attribute_weak_on_field);
16322
16323   NewFD->setAccess(AS);
16324   return NewFD;
16325 }
16326
16327 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16328   assert(FD);
16329   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16330
16331   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16332     return false;
16333
16334   QualType EltTy = Context.getBaseElementType(FD->getType());
16335   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16336     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16337     if (RDecl->getDefinition()) {
16338       // We check for copy constructors before constructors
16339       // because otherwise we'll never get complaints about
16340       // copy constructors.
16341
16342       CXXSpecialMember member = CXXInvalid;
16343       // We're required to check for any non-trivial constructors. Since the
16344       // implicit default constructor is suppressed if there are any
16345       // user-declared constructors, we just need to check that there is a
16346       // trivial default constructor and a trivial copy constructor. (We don't
16347       // worry about move constructors here, since this is a C++98 check.)
16348       if (RDecl->hasNonTrivialCopyConstructor())
16349         member = CXXCopyConstructor;
16350       else if (!RDecl->hasTrivialDefaultConstructor())
16351         member = CXXDefaultConstructor;
16352       else if (RDecl->hasNonTrivialCopyAssignment())
16353         member = CXXCopyAssignment;
16354       else if (RDecl->hasNonTrivialDestructor())
16355         member = CXXDestructor;
16356
16357       if (member != CXXInvalid) {
16358         if (!getLangOpts().CPlusPlus11 &&
16359             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16360           // Objective-C++ ARC: it is an error to have a non-trivial field of
16361           // a union. However, system headers in Objective-C programs
16362           // occasionally have Objective-C lifetime objects within unions,
16363           // and rather than cause the program to fail, we make those
16364           // members unavailable.
16365           SourceLocation Loc = FD->getLocation();
16366           if (getSourceManager().isInSystemHeader(Loc)) {
16367             if (!FD->hasAttr<UnavailableAttr>())
16368               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16369                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16370             return false;
16371           }
16372         }
16373
16374         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16375                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16376                diag::err_illegal_union_or_anon_struct_member)
16377           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16378         DiagnoseNontrivial(RDecl, member);
16379         return !getLangOpts().CPlusPlus11;
16380       }
16381     }
16382   }
16383
16384   return false;
16385 }
16386
16387 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16388 ///  AST enum value.
16389 static ObjCIvarDecl::AccessControl
16390 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16391   switch (ivarVisibility) {
16392   default: llvm_unreachable("Unknown visitibility kind");
16393   case tok::objc_private: return ObjCIvarDecl::Private;
16394   case tok::objc_public: return ObjCIvarDecl::Public;
16395   case tok::objc_protected: return ObjCIvarDecl::Protected;
16396   case tok::objc_package: return ObjCIvarDecl::Package;
16397   }
16398 }
16399
16400 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16401 /// in order to create an IvarDecl object for it.
16402 Decl *Sema::ActOnIvar(Scope *S,
16403                                 SourceLocation DeclStart,
16404                                 Declarator &D, Expr *BitfieldWidth,
16405                                 tok::ObjCKeywordKind Visibility) {
16406
16407   IdentifierInfo *II = D.getIdentifier();
16408   Expr *BitWidth = (Expr*)BitfieldWidth;
16409   SourceLocation Loc = DeclStart;
16410   if (II) Loc = D.getIdentifierLoc();
16411
16412   // FIXME: Unnamed fields can be handled in various different ways, for
16413   // example, unnamed unions inject all members into the struct namespace!
16414
16415   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16416   QualType T = TInfo->getType();
16417
16418   if (BitWidth) {
16419     // 6.7.2.1p3, 6.7.2.1p4
16420     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16421     if (!BitWidth)
16422       D.setInvalidType();
16423   } else {
16424     // Not a bitfield.
16425
16426     // validate II.
16427
16428   }
16429   if (T->isReferenceType()) {
16430     Diag(Loc, diag::err_ivar_reference_type);
16431     D.setInvalidType();
16432   }
16433   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16434   // than a variably modified type.
16435   else if (T->isVariablyModifiedType()) {
16436     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16437     D.setInvalidType();
16438   }
16439
16440   // Get the visibility (access control) for this ivar.
16441   ObjCIvarDecl::AccessControl ac =
16442     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16443                                         : ObjCIvarDecl::None;
16444   // Must set ivar's DeclContext to its enclosing interface.
16445   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16446   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16447     return nullptr;
16448   ObjCContainerDecl *EnclosingContext;
16449   if (ObjCImplementationDecl *IMPDecl =
16450       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16451     if (LangOpts.ObjCRuntime.isFragile()) {
16452     // Case of ivar declared in an implementation. Context is that of its class.
16453       EnclosingContext = IMPDecl->getClassInterface();
16454       assert(EnclosingContext && "Implementation has no class interface!");
16455     }
16456     else
16457       EnclosingContext = EnclosingDecl;
16458   } else {
16459     if (ObjCCategoryDecl *CDecl =
16460         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16461       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16462         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16463         return nullptr;
16464       }
16465     }
16466     EnclosingContext = EnclosingDecl;
16467   }
16468
16469   // Construct the decl.
16470   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16471                                              DeclStart, Loc, II, T,
16472                                              TInfo, ac, (Expr *)BitfieldWidth);
16473
16474   if (II) {
16475     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16476                                            ForVisibleRedeclaration);
16477     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16478         && !isa<TagDecl>(PrevDecl)) {
16479       Diag(Loc, diag::err_duplicate_member) << II;
16480       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16481       NewID->setInvalidDecl();
16482     }
16483   }
16484
16485   // Process attributes attached to the ivar.
16486   ProcessDeclAttributes(S, NewID, D);
16487
16488   if (D.isInvalidType())
16489     NewID->setInvalidDecl();
16490
16491   // In ARC, infer 'retaining' for ivars of retainable type.
16492   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16493     NewID->setInvalidDecl();
16494
16495   if (D.getDeclSpec().isModulePrivateSpecified())
16496     NewID->setModulePrivate();
16497
16498   if (II) {
16499     // FIXME: When interfaces are DeclContexts, we'll need to add
16500     // these to the interface.
16501     S->AddDecl(NewID);
16502     IdResolver.AddDecl(NewID);
16503   }
16504
16505   if (LangOpts.ObjCRuntime.isNonFragile() &&
16506       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16507     Diag(Loc, diag::warn_ivars_in_interface);
16508
16509   return NewID;
16510 }
16511
16512 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16513 /// class and class extensions. For every class \@interface and class
16514 /// extension \@interface, if the last ivar is a bitfield of any type,
16515 /// then add an implicit `char :0` ivar to the end of that interface.
16516 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16517                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16518   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16519     return;
16520
16521   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16522   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16523
16524   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16525     return;
16526   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16527   if (!ID) {
16528     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16529       if (!CD->IsClassExtension())
16530         return;
16531     }
16532     // No need to add this to end of @implementation.
16533     else
16534       return;
16535   }
16536   // All conditions are met. Add a new bitfield to the tail end of ivars.
16537   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16538   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16539
16540   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16541                               DeclLoc, DeclLoc, nullptr,
16542                               Context.CharTy,
16543                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16544                                                                DeclLoc),
16545                               ObjCIvarDecl::Private, BW,
16546                               true);
16547   AllIvarDecls.push_back(Ivar);
16548 }
16549
16550 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16551                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16552                        SourceLocation RBrac,
16553                        const ParsedAttributesView &Attrs) {
16554   assert(EnclosingDecl && "missing record or interface decl");
16555
16556   // If this is an Objective-C @implementation or category and we have
16557   // new fields here we should reset the layout of the interface since
16558   // it will now change.
16559   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16560     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16561     switch (DC->getKind()) {
16562     default: break;
16563     case Decl::ObjCCategory:
16564       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16565       break;
16566     case Decl::ObjCImplementation:
16567       Context.
16568         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16569       break;
16570     }
16571   }
16572
16573   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16574   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16575
16576   // Start counting up the number of named members; make sure to include
16577   // members of anonymous structs and unions in the total.
16578   unsigned NumNamedMembers = 0;
16579   if (Record) {
16580     for (const auto *I : Record->decls()) {
16581       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16582         if (IFD->getDeclName())
16583           ++NumNamedMembers;
16584     }
16585   }
16586
16587   // Verify that all the fields are okay.
16588   SmallVector<FieldDecl*, 32> RecFields;
16589
16590   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16591        i != end; ++i) {
16592     FieldDecl *FD = cast<FieldDecl>(*i);
16593
16594     // Get the type for the field.
16595     const Type *FDTy = FD->getType().getTypePtr();
16596
16597     if (!FD->isAnonymousStructOrUnion()) {
16598       // Remember all fields written by the user.
16599       RecFields.push_back(FD);
16600     }
16601
16602     // If the field is already invalid for some reason, don't emit more
16603     // diagnostics about it.
16604     if (FD->isInvalidDecl()) {
16605       EnclosingDecl->setInvalidDecl();
16606       continue;
16607     }
16608
16609     // C99 6.7.2.1p2:
16610     //   A structure or union shall not contain a member with
16611     //   incomplete or function type (hence, a structure shall not
16612     //   contain an instance of itself, but may contain a pointer to
16613     //   an instance of itself), except that the last member of a
16614     //   structure with more than one named member may have incomplete
16615     //   array type; such a structure (and any union containing,
16616     //   possibly recursively, a member that is such a structure)
16617     //   shall not be a member of a structure or an element of an
16618     //   array.
16619     bool IsLastField = (i + 1 == Fields.end());
16620     if (FDTy->isFunctionType()) {
16621       // Field declared as a function.
16622       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16623         << FD->getDeclName();
16624       FD->setInvalidDecl();
16625       EnclosingDecl->setInvalidDecl();
16626       continue;
16627     } else if (FDTy->isIncompleteArrayType() &&
16628                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16629       if (Record) {
16630         // Flexible array member.
16631         // Microsoft and g++ is more permissive regarding flexible array.
16632         // It will accept flexible array in union and also
16633         // as the sole element of a struct/class.
16634         unsigned DiagID = 0;
16635         if (!Record->isUnion() && !IsLastField) {
16636           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16637             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16638           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16639           FD->setInvalidDecl();
16640           EnclosingDecl->setInvalidDecl();
16641           continue;
16642         } else if (Record->isUnion())
16643           DiagID = getLangOpts().MicrosoftExt
16644                        ? diag::ext_flexible_array_union_ms
16645                        : getLangOpts().CPlusPlus
16646                              ? diag::ext_flexible_array_union_gnu
16647                              : diag::err_flexible_array_union;
16648         else if (NumNamedMembers < 1)
16649           DiagID = getLangOpts().MicrosoftExt
16650                        ? diag::ext_flexible_array_empty_aggregate_ms
16651                        : getLangOpts().CPlusPlus
16652                              ? diag::ext_flexible_array_empty_aggregate_gnu
16653                              : diag::err_flexible_array_empty_aggregate;
16654
16655         if (DiagID)
16656           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16657                                           << Record->getTagKind();
16658         // While the layout of types that contain virtual bases is not specified
16659         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16660         // virtual bases after the derived members.  This would make a flexible
16661         // array member declared at the end of an object not adjacent to the end
16662         // of the type.
16663         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16664           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16665               << FD->getDeclName() << Record->getTagKind();
16666         if (!getLangOpts().C99)
16667           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16668             << FD->getDeclName() << Record->getTagKind();
16669
16670         // If the element type has a non-trivial destructor, we would not
16671         // implicitly destroy the elements, so disallow it for now.
16672         //
16673         // FIXME: GCC allows this. We should probably either implicitly delete
16674         // the destructor of the containing class, or just allow this.
16675         QualType BaseElem = Context.getBaseElementType(FD->getType());
16676         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16677           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16678             << FD->getDeclName() << FD->getType();
16679           FD->setInvalidDecl();
16680           EnclosingDecl->setInvalidDecl();
16681           continue;
16682         }
16683         // Okay, we have a legal flexible array member at the end of the struct.
16684         Record->setHasFlexibleArrayMember(true);
16685       } else {
16686         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16687         // unless they are followed by another ivar. That check is done
16688         // elsewhere, after synthesized ivars are known.
16689       }
16690     } else if (!FDTy->isDependentType() &&
16691                RequireCompleteType(FD->getLocation(), FD->getType(),
16692                                    diag::err_field_incomplete)) {
16693       // Incomplete type
16694       FD->setInvalidDecl();
16695       EnclosingDecl->setInvalidDecl();
16696       continue;
16697     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16698       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16699         // A type which contains a flexible array member is considered to be a
16700         // flexible array member.
16701         Record->setHasFlexibleArrayMember(true);
16702         if (!Record->isUnion()) {
16703           // If this is a struct/class and this is not the last element, reject
16704           // it.  Note that GCC supports variable sized arrays in the middle of
16705           // structures.
16706           if (!IsLastField)
16707             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16708               << FD->getDeclName() << FD->getType();
16709           else {
16710             // We support flexible arrays at the end of structs in
16711             // other structs as an extension.
16712             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16713               << FD->getDeclName();
16714           }
16715         }
16716       }
16717       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16718           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16719                                  diag::err_abstract_type_in_decl,
16720                                  AbstractIvarType)) {
16721         // Ivars can not have abstract class types
16722         FD->setInvalidDecl();
16723       }
16724       if (Record && FDTTy->getDecl()->hasObjectMember())
16725         Record->setHasObjectMember(true);
16726       if (Record && FDTTy->getDecl()->hasVolatileMember())
16727         Record->setHasVolatileMember(true);
16728     } else if (FDTy->isObjCObjectType()) {
16729       /// A field cannot be an Objective-c object
16730       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16731         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16732       QualType T = Context.getObjCObjectPointerType(FD->getType());
16733       FD->setType(T);
16734     } else if (Record && Record->isUnion() &&
16735                FD->getType().hasNonTrivialObjCLifetime() &&
16736                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16737                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16738                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16739                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16740       // For backward compatibility, fields of C unions declared in system
16741       // headers that have non-trivial ObjC ownership qualifications are marked
16742       // as unavailable unless the qualifier is explicit and __strong. This can
16743       // break ABI compatibility between programs compiled with ARC and MRR, but
16744       // is a better option than rejecting programs using those unions under
16745       // ARC.
16746       FD->addAttr(UnavailableAttr::CreateImplicit(
16747           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16748           FD->getLocation()));
16749     } else if (getLangOpts().ObjC &&
16750                getLangOpts().getGC() != LangOptions::NonGC &&
16751                Record && !Record->hasObjectMember()) {
16752       if (FD->getType()->isObjCObjectPointerType() ||
16753           FD->getType().isObjCGCStrong())
16754         Record->setHasObjectMember(true);
16755       else if (Context.getAsArrayType(FD->getType())) {
16756         QualType BaseType = Context.getBaseElementType(FD->getType());
16757         if (BaseType->isRecordType() &&
16758             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16759           Record->setHasObjectMember(true);
16760         else if (BaseType->isObjCObjectPointerType() ||
16761                  BaseType.isObjCGCStrong())
16762                Record->setHasObjectMember(true);
16763       }
16764     }
16765
16766     if (Record && !getLangOpts().CPlusPlus &&
16767         !shouldIgnoreForRecordTriviality(FD)) {
16768       QualType FT = FD->getType();
16769       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16770         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16771         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16772             Record->isUnion())
16773           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16774       }
16775       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16776       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16777         Record->setNonTrivialToPrimitiveCopy(true);
16778         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16779           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16780       }
16781       if (FT.isDestructedType()) {
16782         Record->setNonTrivialToPrimitiveDestroy(true);
16783         Record->setParamDestroyedInCallee(true);
16784         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16785           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16786       }
16787
16788       if (const auto *RT = FT->getAs<RecordType>()) {
16789         if (RT->getDecl()->getArgPassingRestrictions() ==
16790             RecordDecl::APK_CanNeverPassInRegs)
16791           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16792       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16793         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16794     }
16795
16796     if (Record && FD->getType().isVolatileQualified())
16797       Record->setHasVolatileMember(true);
16798     // Keep track of the number of named members.
16799     if (FD->getIdentifier())
16800       ++NumNamedMembers;
16801   }
16802
16803   // Okay, we successfully defined 'Record'.
16804   if (Record) {
16805     bool Completed = false;
16806     if (CXXRecord) {
16807       if (!CXXRecord->isInvalidDecl()) {
16808         // Set access bits correctly on the directly-declared conversions.
16809         for (CXXRecordDecl::conversion_iterator
16810                I = CXXRecord->conversion_begin(),
16811                E = CXXRecord->conversion_end(); I != E; ++I)
16812           I.setAccess((*I)->getAccess());
16813       }
16814
16815       if (!CXXRecord->isDependentType()) {
16816         // Add any implicitly-declared members to this class.
16817         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16818
16819         if (!CXXRecord->isInvalidDecl()) {
16820           // If we have virtual base classes, we may end up finding multiple
16821           // final overriders for a given virtual function. Check for this
16822           // problem now.
16823           if (CXXRecord->getNumVBases()) {
16824             CXXFinalOverriderMap FinalOverriders;
16825             CXXRecord->getFinalOverriders(FinalOverriders);
16826
16827             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16828                                              MEnd = FinalOverriders.end();
16829                  M != MEnd; ++M) {
16830               for (OverridingMethods::iterator SO = M->second.begin(),
16831                                             SOEnd = M->second.end();
16832                    SO != SOEnd; ++SO) {
16833                 assert(SO->second.size() > 0 &&
16834                        "Virtual function without overriding functions?");
16835                 if (SO->second.size() == 1)
16836                   continue;
16837
16838                 // C++ [class.virtual]p2:
16839                 //   In a derived class, if a virtual member function of a base
16840                 //   class subobject has more than one final overrider the
16841                 //   program is ill-formed.
16842                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16843                   << (const NamedDecl *)M->first << Record;
16844                 Diag(M->first->getLocation(),
16845                      diag::note_overridden_virtual_function);
16846                 for (OverridingMethods::overriding_iterator
16847                           OM = SO->second.begin(),
16848                        OMEnd = SO->second.end();
16849                      OM != OMEnd; ++OM)
16850                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16851                     << (const NamedDecl *)M->first << OM->Method->getParent();
16852
16853                 Record->setInvalidDecl();
16854               }
16855             }
16856             CXXRecord->completeDefinition(&FinalOverriders);
16857             Completed = true;
16858           }
16859         }
16860       }
16861     }
16862
16863     if (!Completed)
16864       Record->completeDefinition();
16865
16866     // Handle attributes before checking the layout.
16867     ProcessDeclAttributeList(S, Record, Attrs);
16868
16869     // We may have deferred checking for a deleted destructor. Check now.
16870     if (CXXRecord) {
16871       auto *Dtor = CXXRecord->getDestructor();
16872       if (Dtor && Dtor->isImplicit() &&
16873           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16874         CXXRecord->setImplicitDestructorIsDeleted();
16875         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16876       }
16877     }
16878
16879     if (Record->hasAttrs()) {
16880       CheckAlignasUnderalignment(Record);
16881
16882       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16883         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16884                                            IA->getRange(), IA->getBestCase(),
16885                                            IA->getInheritanceModel());
16886     }
16887
16888     // Check if the structure/union declaration is a type that can have zero
16889     // size in C. For C this is a language extension, for C++ it may cause
16890     // compatibility problems.
16891     bool CheckForZeroSize;
16892     if (!getLangOpts().CPlusPlus) {
16893       CheckForZeroSize = true;
16894     } else {
16895       // For C++ filter out types that cannot be referenced in C code.
16896       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16897       CheckForZeroSize =
16898           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16899           !CXXRecord->isDependentType() &&
16900           CXXRecord->isCLike();
16901     }
16902     if (CheckForZeroSize) {
16903       bool ZeroSize = true;
16904       bool IsEmpty = true;
16905       unsigned NonBitFields = 0;
16906       for (RecordDecl::field_iterator I = Record->field_begin(),
16907                                       E = Record->field_end();
16908            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16909         IsEmpty = false;
16910         if (I->isUnnamedBitfield()) {
16911           if (!I->isZeroLengthBitField(Context))
16912             ZeroSize = false;
16913         } else {
16914           ++NonBitFields;
16915           QualType FieldType = I->getType();
16916           if (FieldType->isIncompleteType() ||
16917               !Context.getTypeSizeInChars(FieldType).isZero())
16918             ZeroSize = false;
16919         }
16920       }
16921
16922       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16923       // allowed in C++, but warn if its declaration is inside
16924       // extern "C" block.
16925       if (ZeroSize) {
16926         Diag(RecLoc, getLangOpts().CPlusPlus ?
16927                          diag::warn_zero_size_struct_union_in_extern_c :
16928                          diag::warn_zero_size_struct_union_compat)
16929           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16930       }
16931
16932       // Structs without named members are extension in C (C99 6.7.2.1p7),
16933       // but are accepted by GCC.
16934       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16935         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16936                                diag::ext_no_named_members_in_struct_union)
16937           << Record->isUnion();
16938       }
16939     }
16940   } else {
16941     ObjCIvarDecl **ClsFields =
16942       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16943     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16944       ID->setEndOfDefinitionLoc(RBrac);
16945       // Add ivar's to class's DeclContext.
16946       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16947         ClsFields[i]->setLexicalDeclContext(ID);
16948         ID->addDecl(ClsFields[i]);
16949       }
16950       // Must enforce the rule that ivars in the base classes may not be
16951       // duplicates.
16952       if (ID->getSuperClass())
16953         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16954     } else if (ObjCImplementationDecl *IMPDecl =
16955                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16956       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16957       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16958         // Ivar declared in @implementation never belongs to the implementation.
16959         // Only it is in implementation's lexical context.
16960         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16961       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16962       IMPDecl->setIvarLBraceLoc(LBrac);
16963       IMPDecl->setIvarRBraceLoc(RBrac);
16964     } else if (ObjCCategoryDecl *CDecl =
16965                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16966       // case of ivars in class extension; all other cases have been
16967       // reported as errors elsewhere.
16968       // FIXME. Class extension does not have a LocEnd field.
16969       // CDecl->setLocEnd(RBrac);
16970       // Add ivar's to class extension's DeclContext.
16971       // Diagnose redeclaration of private ivars.
16972       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16973       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16974         if (IDecl) {
16975           if (const ObjCIvarDecl *ClsIvar =
16976               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16977             Diag(ClsFields[i]->getLocation(),
16978                  diag::err_duplicate_ivar_declaration);
16979             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16980             continue;
16981           }
16982           for (const auto *Ext : IDecl->known_extensions()) {
16983             if (const ObjCIvarDecl *ClsExtIvar
16984                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16985               Diag(ClsFields[i]->getLocation(),
16986                    diag::err_duplicate_ivar_declaration);
16987               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16988               continue;
16989             }
16990           }
16991         }
16992         ClsFields[i]->setLexicalDeclContext(CDecl);
16993         CDecl->addDecl(ClsFields[i]);
16994       }
16995       CDecl->setIvarLBraceLoc(LBrac);
16996       CDecl->setIvarRBraceLoc(RBrac);
16997     }
16998   }
16999 }
17000
17001 /// Determine whether the given integral value is representable within
17002 /// the given type T.
17003 static bool isRepresentableIntegerValue(ASTContext &Context,
17004                                         llvm::APSInt &Value,
17005                                         QualType T) {
17006   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17007          "Integral type required!");
17008   unsigned BitWidth = Context.getIntWidth(T);
17009
17010   if (Value.isUnsigned() || Value.isNonNegative()) {
17011     if (T->isSignedIntegerOrEnumerationType())
17012       --BitWidth;
17013     return Value.getActiveBits() <= BitWidth;
17014   }
17015   return Value.getMinSignedBits() <= BitWidth;
17016 }
17017
17018 // Given an integral type, return the next larger integral type
17019 // (or a NULL type of no such type exists).
17020 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17021   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17022   // enum checking below.
17023   assert((T->isIntegralType(Context) ||
17024          T->isEnumeralType()) && "Integral type required!");
17025   const unsigned NumTypes = 4;
17026   QualType SignedIntegralTypes[NumTypes] = {
17027     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17028   };
17029   QualType UnsignedIntegralTypes[NumTypes] = {
17030     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17031     Context.UnsignedLongLongTy
17032   };
17033
17034   unsigned BitWidth = Context.getTypeSize(T);
17035   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17036                                                         : UnsignedIntegralTypes;
17037   for (unsigned I = 0; I != NumTypes; ++I)
17038     if (Context.getTypeSize(Types[I]) > BitWidth)
17039       return Types[I];
17040
17041   return QualType();
17042 }
17043
17044 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17045                                           EnumConstantDecl *LastEnumConst,
17046                                           SourceLocation IdLoc,
17047                                           IdentifierInfo *Id,
17048                                           Expr *Val) {
17049   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17050   llvm::APSInt EnumVal(IntWidth);
17051   QualType EltTy;
17052
17053   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17054     Val = nullptr;
17055
17056   if (Val)
17057     Val = DefaultLvalueConversion(Val).get();
17058
17059   if (Val) {
17060     if (Enum->isDependentType() || Val->isTypeDependent())
17061       EltTy = Context.DependentTy;
17062     else {
17063       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17064         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17065         // constant-expression in the enumerator-definition shall be a converted
17066         // constant expression of the underlying type.
17067         EltTy = Enum->getIntegerType();
17068         ExprResult Converted =
17069           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17070                                            CCEK_Enumerator);
17071         if (Converted.isInvalid())
17072           Val = nullptr;
17073         else
17074           Val = Converted.get();
17075       } else if (!Val->isValueDependent() &&
17076                  !(Val = VerifyIntegerConstantExpression(Val,
17077                                                          &EnumVal).get())) {
17078         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17079       } else {
17080         if (Enum->isComplete()) {
17081           EltTy = Enum->getIntegerType();
17082
17083           // In Obj-C and Microsoft mode, require the enumeration value to be
17084           // representable in the underlying type of the enumeration. In C++11,
17085           // we perform a non-narrowing conversion as part of converted constant
17086           // expression checking.
17087           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17088             if (Context.getTargetInfo()
17089                     .getTriple()
17090                     .isWindowsMSVCEnvironment()) {
17091               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17092             } else {
17093               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17094             }
17095           }
17096
17097           // Cast to the underlying type.
17098           Val = ImpCastExprToType(Val, EltTy,
17099                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17100                                                          : CK_IntegralCast)
17101                     .get();
17102         } else if (getLangOpts().CPlusPlus) {
17103           // C++11 [dcl.enum]p5:
17104           //   If the underlying type is not fixed, the type of each enumerator
17105           //   is the type of its initializing value:
17106           //     - If an initializer is specified for an enumerator, the
17107           //       initializing value has the same type as the expression.
17108           EltTy = Val->getType();
17109         } else {
17110           // C99 6.7.2.2p2:
17111           //   The expression that defines the value of an enumeration constant
17112           //   shall be an integer constant expression that has a value
17113           //   representable as an int.
17114
17115           // Complain if the value is not representable in an int.
17116           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17117             Diag(IdLoc, diag::ext_enum_value_not_int)
17118               << EnumVal.toString(10) << Val->getSourceRange()
17119               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17120           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17121             // Force the type of the expression to 'int'.
17122             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17123           }
17124           EltTy = Val->getType();
17125         }
17126       }
17127     }
17128   }
17129
17130   if (!Val) {
17131     if (Enum->isDependentType())
17132       EltTy = Context.DependentTy;
17133     else if (!LastEnumConst) {
17134       // C++0x [dcl.enum]p5:
17135       //   If the underlying type is not fixed, the type of each enumerator
17136       //   is the type of its initializing value:
17137       //     - If no initializer is specified for the first enumerator, the
17138       //       initializing value has an unspecified integral type.
17139       //
17140       // GCC uses 'int' for its unspecified integral type, as does
17141       // C99 6.7.2.2p3.
17142       if (Enum->isFixed()) {
17143         EltTy = Enum->getIntegerType();
17144       }
17145       else {
17146         EltTy = Context.IntTy;
17147       }
17148     } else {
17149       // Assign the last value + 1.
17150       EnumVal = LastEnumConst->getInitVal();
17151       ++EnumVal;
17152       EltTy = LastEnumConst->getType();
17153
17154       // Check for overflow on increment.
17155       if (EnumVal < LastEnumConst->getInitVal()) {
17156         // C++0x [dcl.enum]p5:
17157         //   If the underlying type is not fixed, the type of each enumerator
17158         //   is the type of its initializing value:
17159         //
17160         //     - Otherwise the type of the initializing value is the same as
17161         //       the type of the initializing value of the preceding enumerator
17162         //       unless the incremented value is not representable in that type,
17163         //       in which case the type is an unspecified integral type
17164         //       sufficient to contain the incremented value. If no such type
17165         //       exists, the program is ill-formed.
17166         QualType T = getNextLargerIntegralType(Context, EltTy);
17167         if (T.isNull() || Enum->isFixed()) {
17168           // There is no integral type larger enough to represent this
17169           // value. Complain, then allow the value to wrap around.
17170           EnumVal = LastEnumConst->getInitVal();
17171           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17172           ++EnumVal;
17173           if (Enum->isFixed())
17174             // When the underlying type is fixed, this is ill-formed.
17175             Diag(IdLoc, diag::err_enumerator_wrapped)
17176               << EnumVal.toString(10)
17177               << EltTy;
17178           else
17179             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17180               << EnumVal.toString(10);
17181         } else {
17182           EltTy = T;
17183         }
17184
17185         // Retrieve the last enumerator's value, extent that type to the
17186         // type that is supposed to be large enough to represent the incremented
17187         // value, then increment.
17188         EnumVal = LastEnumConst->getInitVal();
17189         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17190         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17191         ++EnumVal;
17192
17193         // If we're not in C++, diagnose the overflow of enumerator values,
17194         // which in C99 means that the enumerator value is not representable in
17195         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17196         // permits enumerator values that are representable in some larger
17197         // integral type.
17198         if (!getLangOpts().CPlusPlus && !T.isNull())
17199           Diag(IdLoc, diag::warn_enum_value_overflow);
17200       } else if (!getLangOpts().CPlusPlus &&
17201                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17202         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17203         Diag(IdLoc, diag::ext_enum_value_not_int)
17204           << EnumVal.toString(10) << 1;
17205       }
17206     }
17207   }
17208
17209   if (!EltTy->isDependentType()) {
17210     // Make the enumerator value match the signedness and size of the
17211     // enumerator's type.
17212     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17213     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17214   }
17215
17216   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17217                                   Val, EnumVal);
17218 }
17219
17220 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17221                                                 SourceLocation IILoc) {
17222   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17223       !getLangOpts().CPlusPlus)
17224     return SkipBodyInfo();
17225
17226   // We have an anonymous enum definition. Look up the first enumerator to
17227   // determine if we should merge the definition with an existing one and
17228   // skip the body.
17229   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17230                                          forRedeclarationInCurContext());
17231   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17232   if (!PrevECD)
17233     return SkipBodyInfo();
17234
17235   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17236   NamedDecl *Hidden;
17237   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17238     SkipBodyInfo Skip;
17239     Skip.Previous = Hidden;
17240     return Skip;
17241   }
17242
17243   return SkipBodyInfo();
17244 }
17245
17246 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17247                               SourceLocation IdLoc, IdentifierInfo *Id,
17248                               const ParsedAttributesView &Attrs,
17249                               SourceLocation EqualLoc, Expr *Val) {
17250   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17251   EnumConstantDecl *LastEnumConst =
17252     cast_or_null<EnumConstantDecl>(lastEnumConst);
17253
17254   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17255   // we find one that is.
17256   S = getNonFieldDeclScope(S);
17257
17258   // Verify that there isn't already something declared with this name in this
17259   // scope.
17260   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17261   LookupName(R, S);
17262   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17263
17264   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17265     // Maybe we will complain about the shadowed template parameter.
17266     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17267     // Just pretend that we didn't see the previous declaration.
17268     PrevDecl = nullptr;
17269   }
17270
17271   // C++ [class.mem]p15:
17272   // If T is the name of a class, then each of the following shall have a name
17273   // different from T:
17274   // - every enumerator of every member of class T that is an unscoped
17275   // enumerated type
17276   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17277     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17278                             DeclarationNameInfo(Id, IdLoc));
17279
17280   EnumConstantDecl *New =
17281     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17282   if (!New)
17283     return nullptr;
17284
17285   if (PrevDecl) {
17286     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17287       // Check for other kinds of shadowing not already handled.
17288       CheckShadow(New, PrevDecl, R);
17289     }
17290
17291     // When in C++, we may get a TagDecl with the same name; in this case the
17292     // enum constant will 'hide' the tag.
17293     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17294            "Received TagDecl when not in C++!");
17295     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17296       if (isa<EnumConstantDecl>(PrevDecl))
17297         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17298       else
17299         Diag(IdLoc, diag::err_redefinition) << Id;
17300       notePreviousDefinition(PrevDecl, IdLoc);
17301       return nullptr;
17302     }
17303   }
17304
17305   // Process attributes.
17306   ProcessDeclAttributeList(S, New, Attrs);
17307   AddPragmaAttributes(S, New);
17308
17309   // Register this decl in the current scope stack.
17310   New->setAccess(TheEnumDecl->getAccess());
17311   PushOnScopeChains(New, S);
17312
17313   ActOnDocumentableDecl(New);
17314
17315   return New;
17316 }
17317
17318 // Returns true when the enum initial expression does not trigger the
17319 // duplicate enum warning.  A few common cases are exempted as follows:
17320 // Element2 = Element1
17321 // Element2 = Element1 + 1
17322 // Element2 = Element1 - 1
17323 // Where Element2 and Element1 are from the same enum.
17324 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17325   Expr *InitExpr = ECD->getInitExpr();
17326   if (!InitExpr)
17327     return true;
17328   InitExpr = InitExpr->IgnoreImpCasts();
17329
17330   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17331     if (!BO->isAdditiveOp())
17332       return true;
17333     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17334     if (!IL)
17335       return true;
17336     if (IL->getValue() != 1)
17337       return true;
17338
17339     InitExpr = BO->getLHS();
17340   }
17341
17342   // This checks if the elements are from the same enum.
17343   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17344   if (!DRE)
17345     return true;
17346
17347   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17348   if (!EnumConstant)
17349     return true;
17350
17351   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17352       Enum)
17353     return true;
17354
17355   return false;
17356 }
17357
17358 // Emits a warning when an element is implicitly set a value that
17359 // a previous element has already been set to.
17360 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17361                                         EnumDecl *Enum, QualType EnumType) {
17362   // Avoid anonymous enums
17363   if (!Enum->getIdentifier())
17364     return;
17365
17366   // Only check for small enums.
17367   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17368     return;
17369
17370   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17371     return;
17372
17373   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17374   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17375
17376   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17377   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17378
17379   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17380   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17381     llvm::APSInt Val = D->getInitVal();
17382     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17383   };
17384
17385   DuplicatesVector DupVector;
17386   ValueToVectorMap EnumMap;
17387
17388   // Populate the EnumMap with all values represented by enum constants without
17389   // an initializer.
17390   for (auto *Element : Elements) {
17391     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17392
17393     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17394     // this constant.  Skip this enum since it may be ill-formed.
17395     if (!ECD) {
17396       return;
17397     }
17398
17399     // Constants with initalizers are handled in the next loop.
17400     if (ECD->getInitExpr())
17401       continue;
17402
17403     // Duplicate values are handled in the next loop.
17404     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17405   }
17406
17407   if (EnumMap.size() == 0)
17408     return;
17409
17410   // Create vectors for any values that has duplicates.
17411   for (auto *Element : Elements) {
17412     // The last loop returned if any constant was null.
17413     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17414     if (!ValidDuplicateEnum(ECD, Enum))
17415       continue;
17416
17417     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17418     if (Iter == EnumMap.end())
17419       continue;
17420
17421     DeclOrVector& Entry = Iter->second;
17422     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17423       // Ensure constants are different.
17424       if (D == ECD)
17425         continue;
17426
17427       // Create new vector and push values onto it.
17428       auto Vec = std::make_unique<ECDVector>();
17429       Vec->push_back(D);
17430       Vec->push_back(ECD);
17431
17432       // Update entry to point to the duplicates vector.
17433       Entry = Vec.get();
17434
17435       // Store the vector somewhere we can consult later for quick emission of
17436       // diagnostics.
17437       DupVector.emplace_back(std::move(Vec));
17438       continue;
17439     }
17440
17441     ECDVector *Vec = Entry.get<ECDVector*>();
17442     // Make sure constants are not added more than once.
17443     if (*Vec->begin() == ECD)
17444       continue;
17445
17446     Vec->push_back(ECD);
17447   }
17448
17449   // Emit diagnostics.
17450   for (const auto &Vec : DupVector) {
17451     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17452
17453     // Emit warning for one enum constant.
17454     auto *FirstECD = Vec->front();
17455     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17456       << FirstECD << FirstECD->getInitVal().toString(10)
17457       << FirstECD->getSourceRange();
17458
17459     // Emit one note for each of the remaining enum constants with
17460     // the same value.
17461     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17462       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17463         << ECD << ECD->getInitVal().toString(10)
17464         << ECD->getSourceRange();
17465   }
17466 }
17467
17468 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17469                              bool AllowMask) const {
17470   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17471   assert(ED->isCompleteDefinition() && "expected enum definition");
17472
17473   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17474   llvm::APInt &FlagBits = R.first->second;
17475
17476   if (R.second) {
17477     for (auto *E : ED->enumerators()) {
17478       const auto &EVal = E->getInitVal();
17479       // Only single-bit enumerators introduce new flag values.
17480       if (EVal.isPowerOf2())
17481         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17482     }
17483   }
17484
17485   // A value is in a flag enum if either its bits are a subset of the enum's
17486   // flag bits (the first condition) or we are allowing masks and the same is
17487   // true of its complement (the second condition). When masks are allowed, we
17488   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17489   //
17490   // While it's true that any value could be used as a mask, the assumption is
17491   // that a mask will have all of the insignificant bits set. Anything else is
17492   // likely a logic error.
17493   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17494   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17495 }
17496
17497 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17498                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17499                          const ParsedAttributesView &Attrs) {
17500   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17501   QualType EnumType = Context.getTypeDeclType(Enum);
17502
17503   ProcessDeclAttributeList(S, Enum, Attrs);
17504
17505   if (Enum->isDependentType()) {
17506     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17507       EnumConstantDecl *ECD =
17508         cast_or_null<EnumConstantDecl>(Elements[i]);
17509       if (!ECD) continue;
17510
17511       ECD->setType(EnumType);
17512     }
17513
17514     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17515     return;
17516   }
17517
17518   // TODO: If the result value doesn't fit in an int, it must be a long or long
17519   // long value.  ISO C does not support this, but GCC does as an extension,
17520   // emit a warning.
17521   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17522   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17523   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17524
17525   // Verify that all the values are okay, compute the size of the values, and
17526   // reverse the list.
17527   unsigned NumNegativeBits = 0;
17528   unsigned NumPositiveBits = 0;
17529
17530   // Keep track of whether all elements have type int.
17531   bool AllElementsInt = true;
17532
17533   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17534     EnumConstantDecl *ECD =
17535       cast_or_null<EnumConstantDecl>(Elements[i]);
17536     if (!ECD) continue;  // Already issued a diagnostic.
17537
17538     const llvm::APSInt &InitVal = ECD->getInitVal();
17539
17540     // Keep track of the size of positive and negative values.
17541     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17542       NumPositiveBits = std::max(NumPositiveBits,
17543                                  (unsigned)InitVal.getActiveBits());
17544     else
17545       NumNegativeBits = std::max(NumNegativeBits,
17546                                  (unsigned)InitVal.getMinSignedBits());
17547
17548     // Keep track of whether every enum element has type int (very common).
17549     if (AllElementsInt)
17550       AllElementsInt = ECD->getType() == Context.IntTy;
17551   }
17552
17553   // Figure out the type that should be used for this enum.
17554   QualType BestType;
17555   unsigned BestWidth;
17556
17557   // C++0x N3000 [conv.prom]p3:
17558   //   An rvalue of an unscoped enumeration type whose underlying
17559   //   type is not fixed can be converted to an rvalue of the first
17560   //   of the following types that can represent all the values of
17561   //   the enumeration: int, unsigned int, long int, unsigned long
17562   //   int, long long int, or unsigned long long int.
17563   // C99 6.4.4.3p2:
17564   //   An identifier declared as an enumeration constant has type int.
17565   // The C99 rule is modified by a gcc extension
17566   QualType BestPromotionType;
17567
17568   bool Packed = Enum->hasAttr<PackedAttr>();
17569   // -fshort-enums is the equivalent to specifying the packed attribute on all
17570   // enum definitions.
17571   if (LangOpts.ShortEnums)
17572     Packed = true;
17573
17574   // If the enum already has a type because it is fixed or dictated by the
17575   // target, promote that type instead of analyzing the enumerators.
17576   if (Enum->isComplete()) {
17577     BestType = Enum->getIntegerType();
17578     if (BestType->isPromotableIntegerType())
17579       BestPromotionType = Context.getPromotedIntegerType(BestType);
17580     else
17581       BestPromotionType = BestType;
17582
17583     BestWidth = Context.getIntWidth(BestType);
17584   }
17585   else if (NumNegativeBits) {
17586     // If there is a negative value, figure out the smallest integer type (of
17587     // int/long/longlong) that fits.
17588     // If it's packed, check also if it fits a char or a short.
17589     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17590       BestType = Context.SignedCharTy;
17591       BestWidth = CharWidth;
17592     } else if (Packed && NumNegativeBits <= ShortWidth &&
17593                NumPositiveBits < ShortWidth) {
17594       BestType = Context.ShortTy;
17595       BestWidth = ShortWidth;
17596     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17597       BestType = Context.IntTy;
17598       BestWidth = IntWidth;
17599     } else {
17600       BestWidth = Context.getTargetInfo().getLongWidth();
17601
17602       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17603         BestType = Context.LongTy;
17604       } else {
17605         BestWidth = Context.getTargetInfo().getLongLongWidth();
17606
17607         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17608           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17609         BestType = Context.LongLongTy;
17610       }
17611     }
17612     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17613   } else {
17614     // If there is no negative value, figure out the smallest type that fits
17615     // all of the enumerator values.
17616     // If it's packed, check also if it fits a char or a short.
17617     if (Packed && NumPositiveBits <= CharWidth) {
17618       BestType = Context.UnsignedCharTy;
17619       BestPromotionType = Context.IntTy;
17620       BestWidth = CharWidth;
17621     } else if (Packed && NumPositiveBits <= ShortWidth) {
17622       BestType = Context.UnsignedShortTy;
17623       BestPromotionType = Context.IntTy;
17624       BestWidth = ShortWidth;
17625     } else if (NumPositiveBits <= IntWidth) {
17626       BestType = Context.UnsignedIntTy;
17627       BestWidth = IntWidth;
17628       BestPromotionType
17629         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17630                            ? Context.UnsignedIntTy : Context.IntTy;
17631     } else if (NumPositiveBits <=
17632                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17633       BestType = Context.UnsignedLongTy;
17634       BestPromotionType
17635         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17636                            ? Context.UnsignedLongTy : Context.LongTy;
17637     } else {
17638       BestWidth = Context.getTargetInfo().getLongLongWidth();
17639       assert(NumPositiveBits <= BestWidth &&
17640              "How could an initializer get larger than ULL?");
17641       BestType = Context.UnsignedLongLongTy;
17642       BestPromotionType
17643         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17644                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17645     }
17646   }
17647
17648   // Loop over all of the enumerator constants, changing their types to match
17649   // the type of the enum if needed.
17650   for (auto *D : Elements) {
17651     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17652     if (!ECD) continue;  // Already issued a diagnostic.
17653
17654     // Standard C says the enumerators have int type, but we allow, as an
17655     // extension, the enumerators to be larger than int size.  If each
17656     // enumerator value fits in an int, type it as an int, otherwise type it the
17657     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17658     // that X has type 'int', not 'unsigned'.
17659
17660     // Determine whether the value fits into an int.
17661     llvm::APSInt InitVal = ECD->getInitVal();
17662
17663     // If it fits into an integer type, force it.  Otherwise force it to match
17664     // the enum decl type.
17665     QualType NewTy;
17666     unsigned NewWidth;
17667     bool NewSign;
17668     if (!getLangOpts().CPlusPlus &&
17669         !Enum->isFixed() &&
17670         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17671       NewTy = Context.IntTy;
17672       NewWidth = IntWidth;
17673       NewSign = true;
17674     } else if (ECD->getType() == BestType) {
17675       // Already the right type!
17676       if (getLangOpts().CPlusPlus)
17677         // C++ [dcl.enum]p4: Following the closing brace of an
17678         // enum-specifier, each enumerator has the type of its
17679         // enumeration.
17680         ECD->setType(EnumType);
17681       continue;
17682     } else {
17683       NewTy = BestType;
17684       NewWidth = BestWidth;
17685       NewSign = BestType->isSignedIntegerOrEnumerationType();
17686     }
17687
17688     // Adjust the APSInt value.
17689     InitVal = InitVal.extOrTrunc(NewWidth);
17690     InitVal.setIsSigned(NewSign);
17691     ECD->setInitVal(InitVal);
17692
17693     // Adjust the Expr initializer and type.
17694     if (ECD->getInitExpr() &&
17695         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17696       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17697                                                 CK_IntegralCast,
17698                                                 ECD->getInitExpr(),
17699                                                 /*base paths*/ nullptr,
17700                                                 VK_RValue));
17701     if (getLangOpts().CPlusPlus)
17702       // C++ [dcl.enum]p4: Following the closing brace of an
17703       // enum-specifier, each enumerator has the type of its
17704       // enumeration.
17705       ECD->setType(EnumType);
17706     else
17707       ECD->setType(NewTy);
17708   }
17709
17710   Enum->completeDefinition(BestType, BestPromotionType,
17711                            NumPositiveBits, NumNegativeBits);
17712
17713   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17714
17715   if (Enum->isClosedFlag()) {
17716     for (Decl *D : Elements) {
17717       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17718       if (!ECD) continue;  // Already issued a diagnostic.
17719
17720       llvm::APSInt InitVal = ECD->getInitVal();
17721       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17722           !IsValueInFlagEnum(Enum, InitVal, true))
17723         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17724           << ECD << Enum;
17725     }
17726   }
17727
17728   // Now that the enum type is defined, ensure it's not been underaligned.
17729   if (Enum->hasAttrs())
17730     CheckAlignasUnderalignment(Enum);
17731 }
17732
17733 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17734                                   SourceLocation StartLoc,
17735                                   SourceLocation EndLoc) {
17736   StringLiteral *AsmString = cast<StringLiteral>(expr);
17737
17738   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17739                                                    AsmString, StartLoc,
17740                                                    EndLoc);
17741   CurContext->addDecl(New);
17742   return New;
17743 }
17744
17745 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17746                                       IdentifierInfo* AliasName,
17747                                       SourceLocation PragmaLoc,
17748                                       SourceLocation NameLoc,
17749                                       SourceLocation AliasNameLoc) {
17750   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17751                                          LookupOrdinaryName);
17752   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17753                            AttributeCommonInfo::AS_Pragma);
17754   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17755       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17756
17757   // If a declaration that:
17758   // 1) declares a function or a variable
17759   // 2) has external linkage
17760   // already exists, add a label attribute to it.
17761   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17762     if (isDeclExternC(PrevDecl))
17763       PrevDecl->addAttr(Attr);
17764     else
17765       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17766           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17767   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17768   } else
17769     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17770 }
17771
17772 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17773                              SourceLocation PragmaLoc,
17774                              SourceLocation NameLoc) {
17775   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17776
17777   if (PrevDecl) {
17778     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17779   } else {
17780     (void)WeakUndeclaredIdentifiers.insert(
17781       std::pair<IdentifierInfo*,WeakInfo>
17782         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17783   }
17784 }
17785
17786 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17787                                 IdentifierInfo* AliasName,
17788                                 SourceLocation PragmaLoc,
17789                                 SourceLocation NameLoc,
17790                                 SourceLocation AliasNameLoc) {
17791   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17792                                     LookupOrdinaryName);
17793   WeakInfo W = WeakInfo(Name, NameLoc);
17794
17795   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17796     if (!PrevDecl->hasAttr<AliasAttr>())
17797       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17798         DeclApplyPragmaWeak(TUScope, ND, W);
17799   } else {
17800     (void)WeakUndeclaredIdentifiers.insert(
17801       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17802   }
17803 }
17804
17805 Decl *Sema::getObjCDeclContext() const {
17806   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17807 }
17808
17809 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17810   // Templates are emitted when they're instantiated.
17811   if (FD->isDependentContext())
17812     return FunctionEmissionStatus::TemplateDiscarded;
17813
17814   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17815   if (LangOpts.OpenMPIsDevice) {
17816     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17817         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17818     if (DevTy.hasValue()) {
17819       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17820         OMPES = FunctionEmissionStatus::OMPDiscarded;
17821       else if (DeviceKnownEmittedFns.count(FD) > 0)
17822         OMPES = FunctionEmissionStatus::Emitted;
17823     }
17824   } else if (LangOpts.OpenMP) {
17825     // In OpenMP 4.5 all the functions are host functions.
17826     if (LangOpts.OpenMP <= 45) {
17827       OMPES = FunctionEmissionStatus::Emitted;
17828     } else {
17829       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17830           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17831       // In OpenMP 5.0 or above, DevTy may be changed later by
17832       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17833       // having no value does not imply host. The emission status will be
17834       // checked again at the end of compilation unit.
17835       if (DevTy.hasValue()) {
17836         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17837           OMPES = FunctionEmissionStatus::OMPDiscarded;
17838         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17839           OMPES = FunctionEmissionStatus::Emitted;
17840         }
17841       }
17842     }
17843   }
17844   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17845       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17846     return OMPES;
17847
17848   if (LangOpts.CUDA) {
17849     // When compiling for device, host functions are never emitted.  Similarly,
17850     // when compiling for host, device and global functions are never emitted.
17851     // (Technically, we do emit a host-side stub for global functions, but this
17852     // doesn't count for our purposes here.)
17853     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17854     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17855       return FunctionEmissionStatus::CUDADiscarded;
17856     if (!LangOpts.CUDAIsDevice &&
17857         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17858       return FunctionEmissionStatus::CUDADiscarded;
17859
17860     // Check whether this function is externally visible -- if so, it's
17861     // known-emitted.
17862     //
17863     // We have to check the GVA linkage of the function's *definition* -- if we
17864     // only have a declaration, we don't know whether or not the function will
17865     // be emitted, because (say) the definition could include "inline".
17866     FunctionDecl *Def = FD->getDefinition();
17867
17868     if (Def &&
17869         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17870         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17871       return FunctionEmissionStatus::Emitted;
17872   }
17873
17874   // Otherwise, the function is known-emitted if it's in our set of
17875   // known-emitted functions.
17876   return (DeviceKnownEmittedFns.count(FD) > 0)
17877              ? FunctionEmissionStatus::Emitted
17878              : FunctionEmissionStatus::Unknown;
17879 }
17880
17881 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17882   // Host-side references to a __global__ function refer to the stub, so the
17883   // function itself is never emitted and therefore should not be marked.
17884   // If we have host fn calls kernel fn calls host+device, the HD function
17885   // does not get instantiated on the host. We model this by omitting at the
17886   // call to the kernel from the callgraph. This ensures that, when compiling
17887   // for host, only HD functions actually called from the host get marked as
17888   // known-emitted.
17889   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17890          IdentifyCUDATarget(Callee) == CFT_Global;
17891 }