1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw___float128:
136   case tok::kw_wchar_t:
137   case tok::kw_bool:
138   case tok::kw___underlying_type:
139   case tok::kw___auto_type:
140     return true;
141 
142   case tok::annot_typename:
143   case tok::kw_char16_t:
144   case tok::kw_char32_t:
145   case tok::kw_typeof:
146   case tok::annot_decltype:
147   case tok::kw_decltype:
148     return getLangOpts().CPlusPlus;
149 
150   default:
151     break;
152   }
153 
154   return false;
155 }
156 
157 namespace {
158 enum class UnqualifiedTypeNameLookupResult {
159   NotFound,
160   FoundNonType,
161   FoundType
162 };
163 } // end anonymous namespace
164 
165 /// \brief Tries to perform unqualified lookup of the type decls in bases for
166 /// dependent class.
167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
168 /// type decl, \a FoundType if only type decls are found.
169 static UnqualifiedTypeNameLookupResult
170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
171                                 SourceLocation NameLoc,
172                                 const CXXRecordDecl *RD) {
173   if (!RD->hasDefinition())
174     return UnqualifiedTypeNameLookupResult::NotFound;
175   // Look for type decls in base classes.
176   UnqualifiedTypeNameLookupResult FoundTypeDecl =
177       UnqualifiedTypeNameLookupResult::NotFound;
178   for (const auto &Base : RD->bases()) {
179     const CXXRecordDecl *BaseRD = nullptr;
180     if (auto *BaseTT = Base.getType()->getAs<TagType>())
181       BaseRD = BaseTT->getAsCXXRecordDecl();
182     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
183       // Look for type decls in dependent base classes that have known primary
184       // templates.
185       if (!TST || !TST->isDependentType())
186         continue;
187       auto *TD = TST->getTemplateName().getAsTemplateDecl();
188       if (!TD)
189         continue;
190       if (auto *BasePrimaryTemplate =
191           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
192         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
193           BaseRD = BasePrimaryTemplate;
194         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
195           if (const ClassTemplatePartialSpecializationDecl *PS =
196                   CTD->findPartialSpecialization(Base.getType()))
197             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
198               BaseRD = PS;
199         }
200       }
201     }
202     if (BaseRD) {
203       for (NamedDecl *ND : BaseRD->lookup(&II)) {
204         if (!isa<TypeDecl>(ND))
205           return UnqualifiedTypeNameLookupResult::FoundNonType;
206         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
207       }
208       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
209         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
210         case UnqualifiedTypeNameLookupResult::FoundNonType:
211           return UnqualifiedTypeNameLookupResult::FoundNonType;
212         case UnqualifiedTypeNameLookupResult::FoundType:
213           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214           break;
215         case UnqualifiedTypeNameLookupResult::NotFound:
216           break;
217         }
218       }
219     }
220   }
221 
222   return FoundTypeDecl;
223 }
224 
225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
226                                                       const IdentifierInfo &II,
227                                                       SourceLocation NameLoc) {
228   // Lookup in the parent class template context, if any.
229   const CXXRecordDecl *RD = nullptr;
230   UnqualifiedTypeNameLookupResult FoundTypeDecl =
231       UnqualifiedTypeNameLookupResult::NotFound;
232   for (DeclContext *DC = S.CurContext;
233        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
234        DC = DC->getParent()) {
235     // Look for type decls in dependent base classes that have known primary
236     // templates.
237     RD = dyn_cast<CXXRecordDecl>(DC);
238     if (RD && RD->getDescribedClassTemplate())
239       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
240   }
241   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
242     return nullptr;
243 
244   // We found some types in dependent base classes.  Recover as if the user
245   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
246   // lookup during template instantiation.
247   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
248 
249   ASTContext &Context = S.Context;
250   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
251                                           cast<Type>(Context.getRecordType(RD)));
252   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
253 
254   CXXScopeSpec SS;
255   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
256 
257   TypeLocBuilder Builder;
258   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
259   DepTL.setNameLoc(NameLoc);
260   DepTL.setElaboratedKeywordLoc(SourceLocation());
261   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
262   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
263 }
264 
265 /// \brief If the identifier refers to a type name within this scope,
266 /// return the declaration of that type.
267 ///
268 /// This routine performs ordinary name lookup of the identifier II
269 /// within the given scope, with optional C++ scope specifier SS, to
270 /// determine whether the name refers to a type. If so, returns an
271 /// opaque pointer (actually a QualType) corresponding to that
272 /// type. Otherwise, returns NULL.
273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
274                              Scope *S, CXXScopeSpec *SS,
275                              bool isClassName, bool HasTrailingDot,
276                              ParsedType ObjectTypePtr,
277                              bool IsCtorOrDtorName,
278                              bool WantNontrivialTypeSourceInfo,
279                              bool IsClassTemplateDeductionContext,
280                              IdentifierInfo **CorrectedII) {
281   // FIXME: Consider allowing this outside C++1z mode as an extension.
282   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
284                               !isClassName && !HasTrailingDot;
285 
286   // Determine where we will perform name lookup.
287   DeclContext *LookupCtx = nullptr;
288   if (ObjectTypePtr) {
289     QualType ObjectType = ObjectTypePtr.get();
290     if (ObjectType->isRecordType())
291       LookupCtx = computeDeclContext(ObjectType);
292   } else if (SS && SS->isNotEmpty()) {
293     LookupCtx = computeDeclContext(*SS, false);
294 
295     if (!LookupCtx) {
296       if (isDependentScopeSpecifier(*SS)) {
297         // C++ [temp.res]p3:
298         //   A qualified-id that refers to a type and in which the
299         //   nested-name-specifier depends on a template-parameter (14.6.2)
300         //   shall be prefixed by the keyword typename to indicate that the
301         //   qualified-id denotes a type, forming an
302         //   elaborated-type-specifier (7.1.5.3).
303         //
304         // We therefore do not perform any name lookup if the result would
305         // refer to a member of an unknown specialization.
306         if (!isClassName && !IsCtorOrDtorName)
307           return nullptr;
308 
309         // We know from the grammar that this name refers to a type,
310         // so build a dependent node to describe the type.
311         if (WantNontrivialTypeSourceInfo)
312           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
313 
314         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
315         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
316                                        II, NameLoc);
317         return ParsedType::make(T);
318       }
319 
320       return nullptr;
321     }
322 
323     if (!LookupCtx->isDependentContext() &&
324         RequireCompleteDeclContext(*SS, LookupCtx))
325       return nullptr;
326   }
327 
328   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
329   // lookup for class-names.
330   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
331                                       LookupOrdinaryName;
332   LookupResult Result(*this, &II, NameLoc, Kind);
333   if (LookupCtx) {
334     // Perform "qualified" name lookup into the declaration context we
335     // computed, which is either the type of the base of a member access
336     // expression or the declaration context associated with a prior
337     // nested-name-specifier.
338     LookupQualifiedName(Result, LookupCtx);
339 
340     if (ObjectTypePtr && Result.empty()) {
341       // C++ [basic.lookup.classref]p3:
342       //   If the unqualified-id is ~type-name, the type-name is looked up
343       //   in the context of the entire postfix-expression. If the type T of
344       //   the object expression is of a class type C, the type-name is also
345       //   looked up in the scope of class C. At least one of the lookups shall
346       //   find a name that refers to (possibly cv-qualified) T.
347       LookupName(Result, S);
348     }
349   } else {
350     // Perform unqualified name lookup.
351     LookupName(Result, S);
352 
353     // For unqualified lookup in a class template in MSVC mode, look into
354     // dependent base classes where the primary class template is known.
355     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
356       if (ParsedType TypeInBase =
357               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
358         return TypeInBase;
359     }
360   }
361 
362   NamedDecl *IIDecl = nullptr;
363   switch (Result.getResultKind()) {
364   case LookupResult::NotFound:
365   case LookupResult::NotFoundInCurrentInstantiation:
366     if (CorrectedII) {
367       TypoCorrection Correction =
368           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
369                       llvm::make_unique<TypeNameValidatorCCC>(
370                           true, isClassName, AllowDeducedTemplate),
371                       CTK_ErrorRecovery);
372       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
373       TemplateTy Template;
374       bool MemberOfUnknownSpecialization;
375       UnqualifiedId TemplateName;
376       TemplateName.setIdentifier(NewII, NameLoc);
377       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
378       CXXScopeSpec NewSS, *NewSSPtr = SS;
379       if (SS && NNS) {
380         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
381         NewSSPtr = &NewSS;
382       }
383       if (Correction && (NNS || NewII != &II) &&
384           // Ignore a correction to a template type as the to-be-corrected
385           // identifier is not a template (typo correction for template names
386           // is handled elsewhere).
387           !(getLangOpts().CPlusPlus && NewSSPtr &&
388             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
389                            Template, MemberOfUnknownSpecialization))) {
390         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
391                                     isClassName, HasTrailingDot, ObjectTypePtr,
392                                     IsCtorOrDtorName,
393                                     WantNontrivialTypeSourceInfo,
394                                     IsClassTemplateDeductionContext);
395         if (Ty) {
396           diagnoseTypo(Correction,
397                        PDiag(diag::err_unknown_type_or_class_name_suggest)
398                          << Result.getLookupName() << isClassName);
399           if (SS && NNS)
400             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
401           *CorrectedII = NewII;
402           return Ty;
403         }
404       }
405     }
406     // If typo correction failed or was not performed, fall through
407     LLVM_FALLTHROUGH;
408   case LookupResult::FoundOverloaded:
409   case LookupResult::FoundUnresolvedValue:
410     Result.suppressDiagnostics();
411     return nullptr;
412 
413   case LookupResult::Ambiguous:
414     // Recover from type-hiding ambiguities by hiding the type.  We'll
415     // do the lookup again when looking for an object, and we can
416     // diagnose the error then.  If we don't do this, then the error
417     // about hiding the type will be immediately followed by an error
418     // that only makes sense if the identifier was treated like a type.
419     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
420       Result.suppressDiagnostics();
421       return nullptr;
422     }
423 
424     // Look to see if we have a type anywhere in the list of results.
425     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
426          Res != ResEnd; ++Res) {
427       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
428           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
429         if (!IIDecl ||
430             (*Res)->getLocation().getRawEncoding() <
431               IIDecl->getLocation().getRawEncoding())
432           IIDecl = *Res;
433       }
434     }
435 
436     if (!IIDecl) {
437       // None of the entities we found is a type, so there is no way
438       // to even assume that the result is a type. In this case, don't
439       // complain about the ambiguity. The parser will either try to
440       // perform this lookup again (e.g., as an object name), which
441       // will produce the ambiguity, or will complain that it expected
442       // a type name.
443       Result.suppressDiagnostics();
444       return nullptr;
445     }
446 
447     // We found a type within the ambiguous lookup; diagnose the
448     // ambiguity and then return that type. This might be the right
449     // answer, or it might not be, but it suppresses any attempt to
450     // perform the name lookup again.
451     break;
452 
453   case LookupResult::Found:
454     IIDecl = Result.getFoundDecl();
455     break;
456   }
457 
458   assert(IIDecl && "Didn't find decl");
459 
460   QualType T;
461   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
462     // C++ [class.qual]p2: A lookup that would find the injected-class-name
463     // instead names the constructors of the class, except when naming a class.
464     // This is ill-formed when we're not actually forming a ctor or dtor name.
465     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
466     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
467     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
468         FoundRD->isInjectedClassName() &&
469         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
470       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
471           << &II << /*Type*/1;
472 
473     DiagnoseUseOfDecl(IIDecl, NameLoc);
474 
475     T = Context.getTypeDeclType(TD);
476     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
477   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
478     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
479     if (!HasTrailingDot)
480       T = Context.getObjCInterfaceType(IDecl);
481   } else if (AllowDeducedTemplate) {
482     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
483       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
484                                                        QualType(), false);
485   }
486 
487   if (T.isNull()) {
488     // If it's not plausibly a type, suppress diagnostics.
489     Result.suppressDiagnostics();
490     return nullptr;
491   }
492 
493   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
494   // constructor or destructor name (in such a case, the scope specifier
495   // will be attached to the enclosing Expr or Decl node).
496   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
497       !isa<ObjCInterfaceDecl>(IIDecl)) {
498     if (WantNontrivialTypeSourceInfo) {
499       // Construct a type with type-source information.
500       TypeLocBuilder Builder;
501       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
502 
503       T = getElaboratedType(ETK_None, *SS, T);
504       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
505       ElabTL.setElaboratedKeywordLoc(SourceLocation());
506       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
507       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
508     } else {
509       T = getElaboratedType(ETK_None, *SS, T);
510     }
511   }
512 
513   return ParsedType::make(T);
514 }
515 
516 // Builds a fake NNS for the given decl context.
517 static NestedNameSpecifier *
518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
519   for (;; DC = DC->getLookupParent()) {
520     DC = DC->getPrimaryContext();
521     auto *ND = dyn_cast<NamespaceDecl>(DC);
522     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
523       return NestedNameSpecifier::Create(Context, nullptr, ND);
524     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
525       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
526                                          RD->getTypeForDecl());
527     else if (isa<TranslationUnitDecl>(DC))
528       return NestedNameSpecifier::GlobalSpecifier(Context);
529   }
530   llvm_unreachable("something isn't in TU scope?");
531 }
532 
533 /// Find the parent class with dependent bases of the innermost enclosing method
534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
535 /// up allowing unqualified dependent type names at class-level, which MSVC
536 /// correctly rejects.
537 static const CXXRecordDecl *
538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
539   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
540     DC = DC->getPrimaryContext();
541     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
542       if (MD->getParent()->hasAnyDependentBases())
543         return MD->getParent();
544   }
545   return nullptr;
546 }
547 
548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
549                                           SourceLocation NameLoc,
550                                           bool IsTemplateTypeArg) {
551   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
552 
553   NestedNameSpecifier *NNS = nullptr;
554   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
555     // If we weren't able to parse a default template argument, delay lookup
556     // until instantiation time by making a non-dependent DependentTypeName. We
557     // pretend we saw a NestedNameSpecifier referring to the current scope, and
558     // lookup is retried.
559     // FIXME: This hurts our diagnostic quality, since we get errors like "no
560     // type named 'Foo' in 'current_namespace'" when the user didn't write any
561     // name specifiers.
562     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
563     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
564   } else if (const CXXRecordDecl *RD =
565                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
566     // Build a DependentNameType that will perform lookup into RD at
567     // instantiation time.
568     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569                                       RD->getTypeForDecl());
570 
571     // Diagnose that this identifier was undeclared, and retry the lookup during
572     // template instantiation.
573     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
574                                                                       << RD;
575   } else {
576     // This is not a situation that we should recover from.
577     return ParsedType();
578   }
579 
580   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
581 
582   // Build type location information.  We synthesized the qualifier, so we have
583   // to build a fake NestedNameSpecifierLoc.
584   NestedNameSpecifierLocBuilder NNSLocBuilder;
585   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
586   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
587 
588   TypeLocBuilder Builder;
589   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
590   DepTL.setNameLoc(NameLoc);
591   DepTL.setElaboratedKeywordLoc(SourceLocation());
592   DepTL.setQualifierLoc(QualifierLoc);
593   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
594 }
595 
596 /// isTagName() - This method is called *for error recovery purposes only*
597 /// to determine if the specified name is a valid tag name ("struct foo").  If
598 /// so, this returns the TST for the tag corresponding to it (TST_enum,
599 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
600 /// cases in C where the user forgot to specify the tag.
601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
602   // Do a tag name lookup in this scope.
603   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
604   LookupName(R, S, false);
605   R.suppressDiagnostics();
606   if (R.getResultKind() == LookupResult::Found)
607     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
608       switch (TD->getTagKind()) {
609       case TTK_Struct: return DeclSpec::TST_struct;
610       case TTK_Interface: return DeclSpec::TST_interface;
611       case TTK_Union:  return DeclSpec::TST_union;
612       case TTK_Class:  return DeclSpec::TST_class;
613       case TTK_Enum:   return DeclSpec::TST_enum;
614       }
615     }
616 
617   return DeclSpec::TST_unspecified;
618 }
619 
620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
622 /// then downgrade the missing typename error to a warning.
623 /// This is needed for MSVC compatibility; Example:
624 /// @code
625 /// template<class T> class A {
626 /// public:
627 ///   typedef int TYPE;
628 /// };
629 /// template<class T> class B : public A<T> {
630 /// public:
631 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
632 /// };
633 /// @endcode
634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
635   if (CurContext->isRecord()) {
636     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
637       return true;
638 
639     const Type *Ty = SS->getScopeRep()->getAsType();
640 
641     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
642     for (const auto &Base : RD->bases())
643       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
644         return true;
645     return S->isFunctionPrototypeScope();
646   }
647   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
648 }
649 
650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
651                                    SourceLocation IILoc,
652                                    Scope *S,
653                                    CXXScopeSpec *SS,
654                                    ParsedType &SuggestedType,
655                                    bool IsTemplateName) {
656   // Don't report typename errors for editor placeholders.
657   if (II->isEditorPlaceholder())
658     return;
659   // We don't have anything to suggest (yet).
660   SuggestedType = nullptr;
661 
662   // There may have been a typo in the name of the type. Look up typo
663   // results, in case we have something that we can suggest.
664   if (TypoCorrection Corrected =
665           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
666                       llvm::make_unique<TypeNameValidatorCCC>(
667                           false, false, IsTemplateName, !IsTemplateName),
668                       CTK_ErrorRecovery)) {
669     // FIXME: Support error recovery for the template-name case.
670     bool CanRecover = !IsTemplateName;
671     if (Corrected.isKeyword()) {
672       // We corrected to a keyword.
673       diagnoseTypo(Corrected,
674                    PDiag(IsTemplateName ? diag::err_no_template_suggest
675                                         : diag::err_unknown_typename_suggest)
676                        << II);
677       II = Corrected.getCorrectionAsIdentifierInfo();
678     } else {
679       // We found a similarly-named type or interface; suggest that.
680       if (!SS || !SS->isSet()) {
681         diagnoseTypo(Corrected,
682                      PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                           : diag::err_unknown_typename_suggest)
684                          << II, CanRecover);
685       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
686         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
687         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
688                                 II->getName().equals(CorrectedStr);
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName
691                                ? diag::err_no_member_template_suggest
692                                : diag::err_unknown_nested_typename_suggest)
693                          << II << DC << DroppedSpecifier << SS->getRange(),
694                      CanRecover);
695       } else {
696         llvm_unreachable("could not have corrected a typo here");
697       }
698 
699       if (!CanRecover)
700         return;
701 
702       CXXScopeSpec tmpSS;
703       if (Corrected.getCorrectionSpecifier())
704         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
705                           SourceRange(IILoc));
706       // FIXME: Support class template argument deduction here.
707       SuggestedType =
708           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
709                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
710                       /*IsCtorOrDtorName=*/false,
711                       /*NonTrivialTypeSourceInfo=*/true);
712     }
713     return;
714   }
715 
716   if (getLangOpts().CPlusPlus && !IsTemplateName) {
717     // See if II is a class template that the user forgot to pass arguments to.
718     UnqualifiedId Name;
719     Name.setIdentifier(II, IILoc);
720     CXXScopeSpec EmptySS;
721     TemplateTy TemplateResult;
722     bool MemberOfUnknownSpecialization;
723     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
724                        Name, nullptr, true, TemplateResult,
725                        MemberOfUnknownSpecialization) == TNK_Type_template) {
726       TemplateName TplName = TemplateResult.get();
727       Diag(IILoc, diag::err_template_missing_args)
728         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
729       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
730         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
731           << TplDecl->getTemplateParameters()->getSourceRange();
732       }
733       return;
734     }
735   }
736 
737   // FIXME: Should we move the logic that tries to recover from a missing tag
738   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
739 
740   if (!SS || (!SS->isSet() && !SS->isInvalid()))
741     Diag(IILoc, IsTemplateName ? diag::err_no_template
742                                : diag::err_unknown_typename)
743         << II;
744   else if (DeclContext *DC = computeDeclContext(*SS, false))
745     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
746                                : diag::err_typename_nested_not_found)
747         << II << DC << SS->getRange();
748   else if (isDependentScopeSpecifier(*SS)) {
749     unsigned DiagID = diag::err_typename_missing;
750     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
751       DiagID = diag::ext_typename_missing;
752 
753     Diag(SS->getRange().getBegin(), DiagID)
754       << SS->getScopeRep() << II->getName()
755       << SourceRange(SS->getRange().getBegin(), IILoc)
756       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
757     SuggestedType = ActOnTypenameType(S, SourceLocation(),
758                                       *SS, *II, IILoc).get();
759   } else {
760     assert(SS && SS->isInvalid() &&
761            "Invalid scope specifier has already been diagnosed");
762   }
763 }
764 
765 /// \brief Determine whether the given result set contains either a type name
766 /// or
767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
768   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
769                        NextToken.is(tok::less);
770 
771   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
772     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
773       return true;
774 
775     if (CheckTemplate && isa<TemplateDecl>(*I))
776       return true;
777   }
778 
779   return false;
780 }
781 
782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
783                                     Scope *S, CXXScopeSpec &SS,
784                                     IdentifierInfo *&Name,
785                                     SourceLocation NameLoc) {
786   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
787   SemaRef.LookupParsedName(R, S, &SS);
788   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
789     StringRef FixItTagName;
790     switch (Tag->getTagKind()) {
791       case TTK_Class:
792         FixItTagName = "class ";
793         break;
794 
795       case TTK_Enum:
796         FixItTagName = "enum ";
797         break;
798 
799       case TTK_Struct:
800         FixItTagName = "struct ";
801         break;
802 
803       case TTK_Interface:
804         FixItTagName = "__interface ";
805         break;
806 
807       case TTK_Union:
808         FixItTagName = "union ";
809         break;
810     }
811 
812     StringRef TagName = FixItTagName.drop_back();
813     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
814       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
815       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
816 
817     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
818          I != IEnd; ++I)
819       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
820         << Name << TagName;
821 
822     // Replace lookup results with just the tag decl.
823     Result.clear(Sema::LookupTagName);
824     SemaRef.LookupParsedName(Result, S, &SS);
825     return true;
826   }
827 
828   return false;
829 }
830 
831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
833                                   QualType T, SourceLocation NameLoc) {
834   ASTContext &Context = S.Context;
835 
836   TypeLocBuilder Builder;
837   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
838 
839   T = S.getElaboratedType(ETK_None, SS, T);
840   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
841   ElabTL.setElaboratedKeywordLoc(SourceLocation());
842   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
843   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
844 }
845 
846 Sema::NameClassification
847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
848                    SourceLocation NameLoc, const Token &NextToken,
849                    bool IsAddressOfOperand,
850                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865 
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868 
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876 
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886 
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889 
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919 
920     // In C, we first see whether there is a tag type by the same name, in
921     // which case it's likely that the user just forgot to write "enum",
922     // "struct", or "union".
923     if (!getLangOpts().CPlusPlus && !SecondTry &&
924         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
925       break;
926     }
927 
928     // Perform typo correction to determine if there is another name that is
929     // close to this name.
930     if (!SecondTry && CCC) {
931       SecondTry = true;
932       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
933                                                  Result.getLookupKind(), S,
934                                                  &SS, std::move(CCC),
935                                                  CTK_ErrorRecovery)) {
936         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
937         unsigned QualifiedDiag = diag::err_no_member_suggest;
938 
939         NamedDecl *FirstDecl = Corrected.getFoundDecl();
940         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
941         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
942             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
943           UnqualifiedDiag = diag::err_no_template_suggest;
944           QualifiedDiag = diag::err_no_member_template_suggest;
945         } else if (UnderlyingFirstDecl &&
946                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
947                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
949           UnqualifiedDiag = diag::err_unknown_typename_suggest;
950           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
951         }
952 
953         if (SS.isEmpty()) {
954           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
955         } else {// FIXME: is this even reachable? Test it.
956           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
957           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
958                                   Name->getName().equals(CorrectedStr);
959           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
960                                     << Name << computeDeclContext(SS, false)
961                                     << DroppedSpecifier << SS.getRange());
962         }
963 
964         // Update the name, so that the caller has the new name.
965         Name = Corrected.getCorrectionAsIdentifierInfo();
966 
967         // Typo correction corrected to a keyword.
968         if (Corrected.isKeyword())
969           return Name;
970 
971         // Also update the LookupResult...
972         // FIXME: This should probably go away at some point
973         Result.clear();
974         Result.setLookupName(Corrected.getCorrection());
975         if (FirstDecl)
976           Result.addDecl(FirstDecl);
977 
978         // If we found an Objective-C instance variable, let
979         // LookupInObjCMethod build the appropriate expression to
980         // reference the ivar.
981         // FIXME: This is a gross hack.
982         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
983           Result.clear();
984           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
985           return E;
986         }
987 
988         goto Corrected;
989       }
990     }
991 
992     // We failed to correct; just fall through and let the parser deal with it.
993     Result.suppressDiagnostics();
994     return NameClassification::Unknown();
995 
996   case LookupResult::NotFoundInCurrentInstantiation: {
997     // We performed name lookup into the current instantiation, and there were
998     // dependent bases, so we treat this result the same way as any other
999     // dependent nested-name-specifier.
1000 
1001     // C++ [temp.res]p2:
1002     //   A name used in a template declaration or definition and that is
1003     //   dependent on a template-parameter is assumed not to name a type
1004     //   unless the applicable name lookup finds a type name or the name is
1005     //   qualified by the keyword typename.
1006     //
1007     // FIXME: If the next token is '<', we might want to ask the parser to
1008     // perform some heroics to see if we actually have a
1009     // template-argument-list, which would indicate a missing 'template'
1010     // keyword here.
1011     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1012                                       NameInfo, IsAddressOfOperand,
1013                                       /*TemplateArgs=*/nullptr);
1014   }
1015 
1016   case LookupResult::Found:
1017   case LookupResult::FoundOverloaded:
1018   case LookupResult::FoundUnresolvedValue:
1019     break;
1020 
1021   case LookupResult::Ambiguous:
1022     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1023         hasAnyAcceptableTemplateNames(Result)) {
1024       // C++ [temp.local]p3:
1025       //   A lookup that finds an injected-class-name (10.2) can result in an
1026       //   ambiguity in certain cases (for example, if it is found in more than
1027       //   one base class). If all of the injected-class-names that are found
1028       //   refer to specializations of the same class template, and if the name
1029       //   is followed by a template-argument-list, the reference refers to the
1030       //   class template itself and not a specialization thereof, and is not
1031       //   ambiguous.
1032       //
1033       // This filtering can make an ambiguous result into an unambiguous one,
1034       // so try again after filtering out template names.
1035       FilterAcceptableTemplateNames(Result);
1036       if (!Result.isAmbiguous()) {
1037         IsFilteredTemplateName = true;
1038         break;
1039       }
1040     }
1041 
1042     // Diagnose the ambiguity and return an error.
1043     return NameClassification::Error();
1044   }
1045 
1046   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1048     // C++ [temp.names]p3:
1049     //   After name lookup (3.4) finds that a name is a template-name or that
1050     //   an operator-function-id or a literal- operator-id refers to a set of
1051     //   overloaded functions any member of which is a function template if
1052     //   this is followed by a <, the < is always taken as the delimiter of a
1053     //   template-argument-list and never as the less-than operator.
1054     if (!IsFilteredTemplateName)
1055       FilterAcceptableTemplateNames(Result);
1056 
1057     if (!Result.empty()) {
1058       bool IsFunctionTemplate;
1059       bool IsVarTemplate;
1060       TemplateName Template;
1061       if (Result.end() - Result.begin() > 1) {
1062         IsFunctionTemplate = true;
1063         Template = Context.getOverloadedTemplateName(Result.begin(),
1064                                                      Result.end());
1065       } else {
1066         TemplateDecl *TD
1067           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1068         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1069         IsVarTemplate = isa<VarTemplateDecl>(TD);
1070 
1071         if (SS.isSet() && !SS.isInvalid())
1072           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1073                                                     /*TemplateKeyword=*/false,
1074                                                       TD);
1075         else
1076           Template = TemplateName(TD);
1077       }
1078 
1079       if (IsFunctionTemplate) {
1080         // Function templates always go through overload resolution, at which
1081         // point we'll perform the various checks (e.g., accessibility) we need
1082         // to based on which function we selected.
1083         Result.suppressDiagnostics();
1084 
1085         return NameClassification::FunctionTemplate(Template);
1086       }
1087 
1088       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1089                            : NameClassification::TypeTemplate(Template);
1090     }
1091   }
1092 
1093   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1094   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1097     QualType T = Context.getTypeDeclType(Type);
1098     if (SS.isNotEmpty())
1099       return buildNestedType(*this, SS, T, NameLoc);
1100     return ParsedType::make(T);
1101   }
1102 
1103   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1104   if (!Class) {
1105     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1106     if (ObjCCompatibleAliasDecl *Alias =
1107             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1108       Class = Alias->getClassInterface();
1109   }
1110 
1111   if (Class) {
1112     DiagnoseUseOfDecl(Class, NameLoc);
1113 
1114     if (NextToken.is(tok::period)) {
1115       // Interface. <something> is parsed as a property reference expression.
1116       // Just return "unknown" as a fall-through for now.
1117       Result.suppressDiagnostics();
1118       return NameClassification::Unknown();
1119     }
1120 
1121     QualType T = Context.getObjCInterfaceType(Class);
1122     return ParsedType::make(T);
1123   }
1124 
1125   // We can have a type template here if we're classifying a template argument.
1126   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1127       !isa<VarTemplateDecl>(FirstDecl))
1128     return NameClassification::TypeTemplate(
1129         TemplateName(cast<TemplateDecl>(FirstDecl)));
1130 
1131   // Check for a tag type hidden by a non-type decl in a few cases where it
1132   // seems likely a type is wanted instead of the non-type that was found.
1133   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1134   if ((NextToken.is(tok::identifier) ||
1135        (NextIsOp &&
1136         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1137       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1138     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     QualType T = Context.getTypeDeclType(Type);
1141     if (SS.isNotEmpty())
1142       return buildNestedType(*this, SS, T, NameLoc);
1143     return ParsedType::make(T);
1144   }
1145 
1146   if (FirstDecl->isCXXClassMember())
1147     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1148                                            nullptr, S);
1149 
1150   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1151   return BuildDeclarationNameExpr(SS, Result, ADL);
1152 }
1153 
1154 Sema::TemplateNameKindForDiagnostics
1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1156   auto *TD = Name.getAsTemplateDecl();
1157   if (!TD)
1158     return TemplateNameKindForDiagnostics::DependentTemplate;
1159   if (isa<ClassTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::ClassTemplate;
1161   if (isa<FunctionTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::FunctionTemplate;
1163   if (isa<VarTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::VarTemplate;
1165   if (isa<TypeAliasTemplateDecl>(TD))
1166     return TemplateNameKindForDiagnostics::AliasTemplate;
1167   if (isa<TemplateTemplateParmDecl>(TD))
1168     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1169   return TemplateNameKindForDiagnostics::DependentTemplate;
1170 }
1171 
1172 // Determines the context to return to after temporarily entering a
1173 // context.  This depends in an unnecessarily complicated way on the
1174 // exact ordering of callbacks from the parser.
1175 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1176 
1177   // Functions defined inline within classes aren't parsed until we've
1178   // finished parsing the top-level class, so the top-level class is
1179   // the context we'll need to return to.
1180   // A Lambda call operator whose parent is a class must not be treated
1181   // as an inline member function.  A Lambda can be used legally
1182   // either as an in-class member initializer or a default argument.  These
1183   // are parsed once the class has been marked complete and so the containing
1184   // context would be the nested class (when the lambda is defined in one);
1185   // If the class is not complete, then the lambda is being used in an
1186   // ill-formed fashion (such as to specify the width of a bit-field, or
1187   // in an array-bound) - in which case we still want to return the
1188   // lexically containing DC (which could be a nested class).
1189   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1190     DC = DC->getLexicalParent();
1191 
1192     // A function not defined within a class will always return to its
1193     // lexical context.
1194     if (!isa<CXXRecordDecl>(DC))
1195       return DC;
1196 
1197     // A C++ inline method/friend is parsed *after* the topmost class
1198     // it was declared in is fully parsed ("complete");  the topmost
1199     // class is the context we need to return to.
1200     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1201       DC = RD;
1202 
1203     // Return the declaration context of the topmost class the inline method is
1204     // declared in.
1205     return DC;
1206   }
1207 
1208   return DC->getLexicalParent();
1209 }
1210 
1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1212   assert(getContainingDC(DC) == CurContext &&
1213       "The next DeclContext should be lexically contained in the current one.");
1214   CurContext = DC;
1215   S->setEntity(DC);
1216 }
1217 
1218 void Sema::PopDeclContext() {
1219   assert(CurContext && "DeclContext imbalance!");
1220 
1221   CurContext = getContainingDC(CurContext);
1222   assert(CurContext && "Popped translation unit!");
1223 }
1224 
1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1226                                                                     Decl *D) {
1227   // Unlike PushDeclContext, the context to which we return is not necessarily
1228   // the containing DC of TD, because the new context will be some pre-existing
1229   // TagDecl definition instead of a fresh one.
1230   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1231   CurContext = cast<TagDecl>(D)->getDefinition();
1232   assert(CurContext && "skipping definition of undefined tag");
1233   // Start lookups from the parent of the current context; we don't want to look
1234   // into the pre-existing complete definition.
1235   S->setEntity(CurContext->getLookupParent());
1236   return Result;
1237 }
1238 
1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1240   CurContext = static_cast<decltype(CurContext)>(Context);
1241 }
1242 
1243 /// EnterDeclaratorContext - Used when we must lookup names in the context
1244 /// of a declarator's nested name specifier.
1245 ///
1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1247   // C++0x [basic.lookup.unqual]p13:
1248   //   A name used in the definition of a static data member of class
1249   //   X (after the qualified-id of the static member) is looked up as
1250   //   if the name was used in a member function of X.
1251   // C++0x [basic.lookup.unqual]p14:
1252   //   If a variable member of a namespace is defined outside of the
1253   //   scope of its namespace then any name used in the definition of
1254   //   the variable member (after the declarator-id) is looked up as
1255   //   if the definition of the variable member occurred in its
1256   //   namespace.
1257   // Both of these imply that we should push a scope whose context
1258   // is the semantic context of the declaration.  We can't use
1259   // PushDeclContext here because that context is not necessarily
1260   // lexically contained in the current context.  Fortunately,
1261   // the containing scope should have the appropriate information.
1262 
1263   assert(!S->getEntity() && "scope already has entity");
1264 
1265 #ifndef NDEBUG
1266   Scope *Ancestor = S->getParent();
1267   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1268   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1269 #endif
1270 
1271   CurContext = DC;
1272   S->setEntity(DC);
1273 }
1274 
1275 void Sema::ExitDeclaratorContext(Scope *S) {
1276   assert(S->getEntity() == CurContext && "Context imbalance!");
1277 
1278   // Switch back to the lexical context.  The safety of this is
1279   // enforced by an assert in EnterDeclaratorContext.
1280   Scope *Ancestor = S->getParent();
1281   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1282   CurContext = Ancestor->getEntity();
1283 
1284   // We don't need to do anything with the scope, which is going to
1285   // disappear.
1286 }
1287 
1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1289   // We assume that the caller has already called
1290   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1291   FunctionDecl *FD = D->getAsFunction();
1292   if (!FD)
1293     return;
1294 
1295   // Same implementation as PushDeclContext, but enters the context
1296   // from the lexical parent, rather than the top-level class.
1297   assert(CurContext == FD->getLexicalParent() &&
1298     "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = FD;
1300   S->setEntity(CurContext);
1301 
1302   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1303     ParmVarDecl *Param = FD->getParamDecl(P);
1304     // If the parameter has an identifier, then add it to the scope
1305     if (Param->getIdentifier()) {
1306       S->AddDecl(Param);
1307       IdResolver.AddDecl(Param);
1308     }
1309   }
1310 }
1311 
1312 void Sema::ActOnExitFunctionContext() {
1313   // Same implementation as PopDeclContext, but returns to the lexical parent,
1314   // rather than the top-level class.
1315   assert(CurContext && "DeclContext imbalance!");
1316   CurContext = CurContext->getLexicalParent();
1317   assert(CurContext && "Popped translation unit!");
1318 }
1319 
1320 /// \brief Determine whether we allow overloading of the function
1321 /// PrevDecl with another declaration.
1322 ///
1323 /// This routine determines whether overloading is possible, not
1324 /// whether some new function is actually an overload. It will return
1325 /// true in C++ (where we can always provide overloads) or, as an
1326 /// extension, in C when the previous function is already an
1327 /// overloaded function declaration or has the "overloadable"
1328 /// attribute.
1329 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1330                                        ASTContext &Context,
1331                                        const FunctionDecl *New) {
1332   if (Context.getLangOpts().CPlusPlus)
1333     return true;
1334 
1335   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1336     return true;
1337 
1338   return Previous.getResultKind() == LookupResult::Found &&
1339          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1340           New->hasAttr<OverloadableAttr>());
1341 }
1342 
1343 /// Add this decl to the scope shadowed decl chains.
1344 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1345   // Move up the scope chain until we find the nearest enclosing
1346   // non-transparent context. The declaration will be introduced into this
1347   // scope.
1348   while (S->getEntity() && S->getEntity()->isTransparentContext())
1349     S = S->getParent();
1350 
1351   // Add scoped declarations into their context, so that they can be
1352   // found later. Declarations without a context won't be inserted
1353   // into any context.
1354   if (AddToContext)
1355     CurContext->addDecl(D);
1356 
1357   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1358   // are function-local declarations.
1359   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1360       !D->getDeclContext()->getRedeclContext()->Equals(
1361         D->getLexicalDeclContext()->getRedeclContext()) &&
1362       !D->getLexicalDeclContext()->isFunctionOrMethod())
1363     return;
1364 
1365   // Template instantiations should also not be pushed into scope.
1366   if (isa<FunctionDecl>(D) &&
1367       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1368     return;
1369 
1370   // If this replaces anything in the current scope,
1371   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1372                                IEnd = IdResolver.end();
1373   for (; I != IEnd; ++I) {
1374     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1375       S->RemoveDecl(*I);
1376       IdResolver.RemoveDecl(*I);
1377 
1378       // Should only need to replace one decl.
1379       break;
1380     }
1381   }
1382 
1383   S->AddDecl(D);
1384 
1385   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1386     // Implicitly-generated labels may end up getting generated in an order that
1387     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1388     // the label at the appropriate place in the identifier chain.
1389     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1390       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1391       if (IDC == CurContext) {
1392         if (!S->isDeclScope(*I))
1393           continue;
1394       } else if (IDC->Encloses(CurContext))
1395         break;
1396     }
1397 
1398     IdResolver.InsertDeclAfter(I, D);
1399   } else {
1400     IdResolver.AddDecl(D);
1401   }
1402 }
1403 
1404 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1405   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1406     TUScope->AddDecl(D);
1407 }
1408 
1409 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1410                          bool AllowInlineNamespace) {
1411   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1412 }
1413 
1414 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1415   DeclContext *TargetDC = DC->getPrimaryContext();
1416   do {
1417     if (DeclContext *ScopeDC = S->getEntity())
1418       if (ScopeDC->getPrimaryContext() == TargetDC)
1419         return S;
1420   } while ((S = S->getParent()));
1421 
1422   return nullptr;
1423 }
1424 
1425 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1426                                             DeclContext*,
1427                                             ASTContext&);
1428 
1429 /// Filters out lookup results that don't fall within the given scope
1430 /// as determined by isDeclInScope.
1431 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1432                                 bool ConsiderLinkage,
1433                                 bool AllowInlineNamespace) {
1434   LookupResult::Filter F = R.makeFilter();
1435   while (F.hasNext()) {
1436     NamedDecl *D = F.next();
1437 
1438     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1439       continue;
1440 
1441     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1442       continue;
1443 
1444     F.erase();
1445   }
1446 
1447   F.done();
1448 }
1449 
1450 static bool isUsingDecl(NamedDecl *D) {
1451   return isa<UsingShadowDecl>(D) ||
1452          isa<UnresolvedUsingTypenameDecl>(D) ||
1453          isa<UnresolvedUsingValueDecl>(D);
1454 }
1455 
1456 /// Removes using shadow declarations from the lookup results.
1457 static void RemoveUsingDecls(LookupResult &R) {
1458   LookupResult::Filter F = R.makeFilter();
1459   while (F.hasNext())
1460     if (isUsingDecl(F.next()))
1461       F.erase();
1462 
1463   F.done();
1464 }
1465 
1466 /// \brief Check for this common pattern:
1467 /// @code
1468 /// class S {
1469 ///   S(const S&); // DO NOT IMPLEMENT
1470 ///   void operator=(const S&); // DO NOT IMPLEMENT
1471 /// };
1472 /// @endcode
1473 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1474   // FIXME: Should check for private access too but access is set after we get
1475   // the decl here.
1476   if (D->doesThisDeclarationHaveABody())
1477     return false;
1478 
1479   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1480     return CD->isCopyConstructor();
1481   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1482     return Method->isCopyAssignmentOperator();
1483   return false;
1484 }
1485 
1486 // We need this to handle
1487 //
1488 // typedef struct {
1489 //   void *foo() { return 0; }
1490 // } A;
1491 //
1492 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1493 // for example. If 'A', foo will have external linkage. If we have '*A',
1494 // foo will have no linkage. Since we can't know until we get to the end
1495 // of the typedef, this function finds out if D might have non-external linkage.
1496 // Callers should verify at the end of the TU if it D has external linkage or
1497 // not.
1498 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1499   const DeclContext *DC = D->getDeclContext();
1500   while (!DC->isTranslationUnit()) {
1501     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1502       if (!RD->hasNameForLinkage())
1503         return true;
1504     }
1505     DC = DC->getParent();
1506   }
1507 
1508   return !D->isExternallyVisible();
1509 }
1510 
1511 // FIXME: This needs to be refactored; some other isInMainFile users want
1512 // these semantics.
1513 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1514   if (S.TUKind != TU_Complete)
1515     return false;
1516   return S.SourceMgr.isInMainFile(Loc);
1517 }
1518 
1519 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1520   assert(D);
1521 
1522   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1523     return false;
1524 
1525   // Ignore all entities declared within templates, and out-of-line definitions
1526   // of members of class templates.
1527   if (D->getDeclContext()->isDependentContext() ||
1528       D->getLexicalDeclContext()->isDependentContext())
1529     return false;
1530 
1531   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1533       return false;
1534     // A non-out-of-line declaration of a member specialization was implicitly
1535     // instantiated; it's the out-of-line declaration that we're interested in.
1536     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1537         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1538       return false;
1539 
1540     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1541       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1542         return false;
1543     } else {
1544       // 'static inline' functions are defined in headers; don't warn.
1545       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1546         return false;
1547     }
1548 
1549     if (FD->doesThisDeclarationHaveABody() &&
1550         Context.DeclMustBeEmitted(FD))
1551       return false;
1552   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1553     // Constants and utility variables are defined in headers with internal
1554     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1555     // like "inline".)
1556     if (!isMainFileLoc(*this, VD->getLocation()))
1557       return false;
1558 
1559     if (Context.DeclMustBeEmitted(VD))
1560       return false;
1561 
1562     if (VD->isStaticDataMember() &&
1563         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1564       return false;
1565     if (VD->isStaticDataMember() &&
1566         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1567         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1568       return false;
1569 
1570     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1571       return false;
1572   } else {
1573     return false;
1574   }
1575 
1576   // Only warn for unused decls internal to the translation unit.
1577   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1578   // for inline functions defined in the main source file, for instance.
1579   return mightHaveNonExternalLinkage(D);
1580 }
1581 
1582 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1583   if (!D)
1584     return;
1585 
1586   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1587     const FunctionDecl *First = FD->getFirstDecl();
1588     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1589       return; // First should already be in the vector.
1590   }
1591 
1592   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1593     const VarDecl *First = VD->getFirstDecl();
1594     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1595       return; // First should already be in the vector.
1596   }
1597 
1598   if (ShouldWarnIfUnusedFileScopedDecl(D))
1599     UnusedFileScopedDecls.push_back(D);
1600 }
1601 
1602 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1603   if (D->isInvalidDecl())
1604     return false;
1605 
1606   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1607       D->hasAttr<ObjCPreciseLifetimeAttr>())
1608     return false;
1609 
1610   if (isa<LabelDecl>(D))
1611     return true;
1612 
1613   // Except for labels, we only care about unused decls that are local to
1614   // functions.
1615   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1616   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1617     // For dependent types, the diagnostic is deferred.
1618     WithinFunction =
1619         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1620   if (!WithinFunction)
1621     return false;
1622 
1623   if (isa<TypedefNameDecl>(D))
1624     return true;
1625 
1626   // White-list anything that isn't a local variable.
1627   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1628     return false;
1629 
1630   // Types of valid local variables should be complete, so this should succeed.
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632 
1633     // White-list anything with an __attribute__((unused)) type.
1634     const auto *Ty = VD->getType().getTypePtr();
1635 
1636     // Only look at the outermost level of typedef.
1637     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1638       if (TT->getDecl()->hasAttr<UnusedAttr>())
1639         return false;
1640     }
1641 
1642     // If we failed to complete the type for some reason, or if the type is
1643     // dependent, don't diagnose the variable.
1644     if (Ty->isIncompleteType() || Ty->isDependentType())
1645       return false;
1646 
1647     // Look at the element type to ensure that the warning behaviour is
1648     // consistent for both scalars and arrays.
1649     Ty = Ty->getBaseElementTypeUnsafe();
1650 
1651     if (const TagType *TT = Ty->getAs<TagType>()) {
1652       const TagDecl *Tag = TT->getDecl();
1653       if (Tag->hasAttr<UnusedAttr>())
1654         return false;
1655 
1656       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1657         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1658           return false;
1659 
1660         if (const Expr *Init = VD->getInit()) {
1661           if (const ExprWithCleanups *Cleanups =
1662                   dyn_cast<ExprWithCleanups>(Init))
1663             Init = Cleanups->getSubExpr();
1664           const CXXConstructExpr *Construct =
1665             dyn_cast<CXXConstructExpr>(Init);
1666           if (Construct && !Construct->isElidable()) {
1667             CXXConstructorDecl *CD = Construct->getConstructor();
1668             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1669               return false;
1670           }
1671         }
1672       }
1673     }
1674 
1675     // TODO: __attribute__((unused)) templates?
1676   }
1677 
1678   return true;
1679 }
1680 
1681 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1682                                      FixItHint &Hint) {
1683   if (isa<LabelDecl>(D)) {
1684     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1685                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1686     if (AfterColon.isInvalid())
1687       return;
1688     Hint = FixItHint::CreateRemoval(CharSourceRange::
1689                                     getCharRange(D->getLocStart(), AfterColon));
1690   }
1691 }
1692 
1693 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1694   if (D->getTypeForDecl()->isDependentType())
1695     return;
1696 
1697   for (auto *TmpD : D->decls()) {
1698     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1699       DiagnoseUnusedDecl(T);
1700     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1701       DiagnoseUnusedNestedTypedefs(R);
1702   }
1703 }
1704 
1705 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1706 /// unless they are marked attr(unused).
1707 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1708   if (!ShouldDiagnoseUnusedDecl(D))
1709     return;
1710 
1711   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1712     // typedefs can be referenced later on, so the diagnostics are emitted
1713     // at end-of-translation-unit.
1714     UnusedLocalTypedefNameCandidates.insert(TD);
1715     return;
1716   }
1717 
1718   FixItHint Hint;
1719   GenerateFixForUnusedDecl(D, Context, Hint);
1720 
1721   unsigned DiagID;
1722   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1723     DiagID = diag::warn_unused_exception_param;
1724   else if (isa<LabelDecl>(D))
1725     DiagID = diag::warn_unused_label;
1726   else
1727     DiagID = diag::warn_unused_variable;
1728 
1729   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1730 }
1731 
1732 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1733   // Verify that we have no forward references left.  If so, there was a goto
1734   // or address of a label taken, but no definition of it.  Label fwd
1735   // definitions are indicated with a null substmt which is also not a resolved
1736   // MS inline assembly label name.
1737   bool Diagnose = false;
1738   if (L->isMSAsmLabel())
1739     Diagnose = !L->isResolvedMSAsmLabel();
1740   else
1741     Diagnose = L->getStmt() == nullptr;
1742   if (Diagnose)
1743     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1744 }
1745 
1746 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1747   S->mergeNRVOIntoParent();
1748 
1749   if (S->decl_empty()) return;
1750   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1751          "Scope shouldn't contain decls!");
1752 
1753   for (auto *TmpD : S->decls()) {
1754     assert(TmpD && "This decl didn't get pushed??");
1755 
1756     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1757     NamedDecl *D = cast<NamedDecl>(TmpD);
1758 
1759     if (!D->getDeclName()) continue;
1760 
1761     // Diagnose unused variables in this scope.
1762     if (!S->hasUnrecoverableErrorOccurred()) {
1763       DiagnoseUnusedDecl(D);
1764       if (const auto *RD = dyn_cast<RecordDecl>(D))
1765         DiagnoseUnusedNestedTypedefs(RD);
1766     }
1767 
1768     // If this was a forward reference to a label, verify it was defined.
1769     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1770       CheckPoppedLabel(LD, *this);
1771 
1772     // Remove this name from our lexical scope, and warn on it if we haven't
1773     // already.
1774     IdResolver.RemoveDecl(D);
1775     auto ShadowI = ShadowingDecls.find(D);
1776     if (ShadowI != ShadowingDecls.end()) {
1777       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1778         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1779             << D << FD << FD->getParent();
1780         Diag(FD->getLocation(), diag::note_previous_declaration);
1781       }
1782       ShadowingDecls.erase(ShadowI);
1783     }
1784   }
1785 }
1786 
1787 /// \brief Look for an Objective-C class in the translation unit.
1788 ///
1789 /// \param Id The name of the Objective-C class we're looking for. If
1790 /// typo-correction fixes this name, the Id will be updated
1791 /// to the fixed name.
1792 ///
1793 /// \param IdLoc The location of the name in the translation unit.
1794 ///
1795 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1796 /// if there is no class with the given name.
1797 ///
1798 /// \returns The declaration of the named Objective-C class, or NULL if the
1799 /// class could not be found.
1800 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1801                                               SourceLocation IdLoc,
1802                                               bool DoTypoCorrection) {
1803   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1804   // creation from this context.
1805   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1806 
1807   if (!IDecl && DoTypoCorrection) {
1808     // Perform typo correction at the given location, but only if we
1809     // find an Objective-C class name.
1810     if (TypoCorrection C = CorrectTypo(
1811             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1812             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1813             CTK_ErrorRecovery)) {
1814       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1815       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1816       Id = IDecl->getIdentifier();
1817     }
1818   }
1819   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1820   // This routine must always return a class definition, if any.
1821   if (Def && Def->getDefinition())
1822       Def = Def->getDefinition();
1823   return Def;
1824 }
1825 
1826 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1827 /// from S, where a non-field would be declared. This routine copes
1828 /// with the difference between C and C++ scoping rules in structs and
1829 /// unions. For example, the following code is well-formed in C but
1830 /// ill-formed in C++:
1831 /// @code
1832 /// struct S6 {
1833 ///   enum { BAR } e;
1834 /// };
1835 ///
1836 /// void test_S6() {
1837 ///   struct S6 a;
1838 ///   a.e = BAR;
1839 /// }
1840 /// @endcode
1841 /// For the declaration of BAR, this routine will return a different
1842 /// scope. The scope S will be the scope of the unnamed enumeration
1843 /// within S6. In C++, this routine will return the scope associated
1844 /// with S6, because the enumeration's scope is a transparent
1845 /// context but structures can contain non-field names. In C, this
1846 /// routine will return the translation unit scope, since the
1847 /// enumeration's scope is a transparent context and structures cannot
1848 /// contain non-field names.
1849 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1850   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1851          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1852          (S->isClassScope() && !getLangOpts().CPlusPlus))
1853     S = S->getParent();
1854   return S;
1855 }
1856 
1857 /// \brief Looks up the declaration of "struct objc_super" and
1858 /// saves it for later use in building builtin declaration of
1859 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1860 /// pre-existing declaration exists no action takes place.
1861 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1862                                         IdentifierInfo *II) {
1863   if (!II->isStr("objc_msgSendSuper"))
1864     return;
1865   ASTContext &Context = ThisSema.Context;
1866 
1867   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1868                       SourceLocation(), Sema::LookupTagName);
1869   ThisSema.LookupName(Result, S);
1870   if (Result.getResultKind() == LookupResult::Found)
1871     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1872       Context.setObjCSuperType(Context.getTagDeclType(TD));
1873 }
1874 
1875 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1876   switch (Error) {
1877   case ASTContext::GE_None:
1878     return "";
1879   case ASTContext::GE_Missing_stdio:
1880     return "stdio.h";
1881   case ASTContext::GE_Missing_setjmp:
1882     return "setjmp.h";
1883   case ASTContext::GE_Missing_ucontext:
1884     return "ucontext.h";
1885   }
1886   llvm_unreachable("unhandled error kind");
1887 }
1888 
1889 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1890 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1891 /// if we're creating this built-in in anticipation of redeclaring the
1892 /// built-in.
1893 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1894                                      Scope *S, bool ForRedeclaration,
1895                                      SourceLocation Loc) {
1896   LookupPredefedObjCSuperType(*this, S, II);
1897 
1898   ASTContext::GetBuiltinTypeError Error;
1899   QualType R = Context.GetBuiltinType(ID, Error);
1900   if (Error) {
1901     if (ForRedeclaration)
1902       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1903           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1904     return nullptr;
1905   }
1906 
1907   if (!ForRedeclaration &&
1908       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1909        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1910     Diag(Loc, diag::ext_implicit_lib_function_decl)
1911         << Context.BuiltinInfo.getName(ID) << R;
1912     if (Context.BuiltinInfo.getHeaderName(ID) &&
1913         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1914       Diag(Loc, diag::note_include_header_or_declare)
1915           << Context.BuiltinInfo.getHeaderName(ID)
1916           << Context.BuiltinInfo.getName(ID);
1917   }
1918 
1919   if (R.isNull())
1920     return nullptr;
1921 
1922   DeclContext *Parent = Context.getTranslationUnitDecl();
1923   if (getLangOpts().CPlusPlus) {
1924     LinkageSpecDecl *CLinkageDecl =
1925         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1926                                 LinkageSpecDecl::lang_c, false);
1927     CLinkageDecl->setImplicit();
1928     Parent->addDecl(CLinkageDecl);
1929     Parent = CLinkageDecl;
1930   }
1931 
1932   FunctionDecl *New = FunctionDecl::Create(Context,
1933                                            Parent,
1934                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1935                                            SC_Extern,
1936                                            false,
1937                                            R->isFunctionProtoType());
1938   New->setImplicit();
1939 
1940   // Create Decl objects for each parameter, adding them to the
1941   // FunctionDecl.
1942   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1943     SmallVector<ParmVarDecl*, 16> Params;
1944     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1945       ParmVarDecl *parm =
1946           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1947                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1948                               SC_None, nullptr);
1949       parm->setScopeInfo(0, i);
1950       Params.push_back(parm);
1951     }
1952     New->setParams(Params);
1953   }
1954 
1955   AddKnownFunctionAttributes(New);
1956   RegisterLocallyScopedExternCDecl(New, S);
1957 
1958   // TUScope is the translation-unit scope to insert this function into.
1959   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1960   // relate Scopes to DeclContexts, and probably eliminate CurContext
1961   // entirely, but we're not there yet.
1962   DeclContext *SavedContext = CurContext;
1963   CurContext = Parent;
1964   PushOnScopeChains(New, TUScope);
1965   CurContext = SavedContext;
1966   return New;
1967 }
1968 
1969 /// Typedef declarations don't have linkage, but they still denote the same
1970 /// entity if their types are the same.
1971 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1972 /// isSameEntity.
1973 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1974                                                      TypedefNameDecl *Decl,
1975                                                      LookupResult &Previous) {
1976   // This is only interesting when modules are enabled.
1977   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1978     return;
1979 
1980   // Empty sets are uninteresting.
1981   if (Previous.empty())
1982     return;
1983 
1984   LookupResult::Filter Filter = Previous.makeFilter();
1985   while (Filter.hasNext()) {
1986     NamedDecl *Old = Filter.next();
1987 
1988     // Non-hidden declarations are never ignored.
1989     if (S.isVisible(Old))
1990       continue;
1991 
1992     // Declarations of the same entity are not ignored, even if they have
1993     // different linkages.
1994     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1995       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1996                                 Decl->getUnderlyingType()))
1997         continue;
1998 
1999       // If both declarations give a tag declaration a typedef name for linkage
2000       // purposes, then they declare the same entity.
2001       if (S.getLangOpts().CPlusPlus &&
2002           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2003           Decl->getAnonDeclWithTypedefName())
2004         continue;
2005     }
2006 
2007     Filter.erase();
2008   }
2009 
2010   Filter.done();
2011 }
2012 
2013 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2014   QualType OldType;
2015   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2016     OldType = OldTypedef->getUnderlyingType();
2017   else
2018     OldType = Context.getTypeDeclType(Old);
2019   QualType NewType = New->getUnderlyingType();
2020 
2021   if (NewType->isVariablyModifiedType()) {
2022     // Must not redefine a typedef with a variably-modified type.
2023     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2024     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2025       << Kind << NewType;
2026     if (Old->getLocation().isValid())
2027       notePreviousDefinition(Old, New->getLocation());
2028     New->setInvalidDecl();
2029     return true;
2030   }
2031 
2032   if (OldType != NewType &&
2033       !OldType->isDependentType() &&
2034       !NewType->isDependentType() &&
2035       !Context.hasSameType(OldType, NewType)) {
2036     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2037     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2038       << Kind << NewType << OldType;
2039     if (Old->getLocation().isValid())
2040       notePreviousDefinition(Old, New->getLocation());
2041     New->setInvalidDecl();
2042     return true;
2043   }
2044   return false;
2045 }
2046 
2047 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2048 /// same name and scope as a previous declaration 'Old'.  Figure out
2049 /// how to resolve this situation, merging decls or emitting
2050 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2051 ///
2052 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2053                                 LookupResult &OldDecls) {
2054   // If the new decl is known invalid already, don't bother doing any
2055   // merging checks.
2056   if (New->isInvalidDecl()) return;
2057 
2058   // Allow multiple definitions for ObjC built-in typedefs.
2059   // FIXME: Verify the underlying types are equivalent!
2060   if (getLangOpts().ObjC1) {
2061     const IdentifierInfo *TypeID = New->getIdentifier();
2062     switch (TypeID->getLength()) {
2063     default: break;
2064     case 2:
2065       {
2066         if (!TypeID->isStr("id"))
2067           break;
2068         QualType T = New->getUnderlyingType();
2069         if (!T->isPointerType())
2070           break;
2071         if (!T->isVoidPointerType()) {
2072           QualType PT = T->getAs<PointerType>()->getPointeeType();
2073           if (!PT->isStructureType())
2074             break;
2075         }
2076         Context.setObjCIdRedefinitionType(T);
2077         // Install the built-in type for 'id', ignoring the current definition.
2078         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2079         return;
2080       }
2081     case 5:
2082       if (!TypeID->isStr("Class"))
2083         break;
2084       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2085       // Install the built-in type for 'Class', ignoring the current definition.
2086       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2087       return;
2088     case 3:
2089       if (!TypeID->isStr("SEL"))
2090         break;
2091       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2092       // Install the built-in type for 'SEL', ignoring the current definition.
2093       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2094       return;
2095     }
2096     // Fall through - the typedef name was not a builtin type.
2097   }
2098 
2099   // Verify the old decl was also a type.
2100   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2101   if (!Old) {
2102     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2103       << New->getDeclName();
2104 
2105     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2106     if (OldD->getLocation().isValid())
2107       notePreviousDefinition(OldD, New->getLocation());
2108 
2109     return New->setInvalidDecl();
2110   }
2111 
2112   // If the old declaration is invalid, just give up here.
2113   if (Old->isInvalidDecl())
2114     return New->setInvalidDecl();
2115 
2116   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2117     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2118     auto *NewTag = New->getAnonDeclWithTypedefName();
2119     NamedDecl *Hidden = nullptr;
2120     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2121         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2122         !hasVisibleDefinition(OldTag, &Hidden)) {
2123       // There is a definition of this tag, but it is not visible. Use it
2124       // instead of our tag.
2125       New->setTypeForDecl(OldTD->getTypeForDecl());
2126       if (OldTD->isModed())
2127         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2128                                     OldTD->getUnderlyingType());
2129       else
2130         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2131 
2132       // Make the old tag definition visible.
2133       makeMergedDefinitionVisible(Hidden);
2134 
2135       // If this was an unscoped enumeration, yank all of its enumerators
2136       // out of the scope.
2137       if (isa<EnumDecl>(NewTag)) {
2138         Scope *EnumScope = getNonFieldDeclScope(S);
2139         for (auto *D : NewTag->decls()) {
2140           auto *ED = cast<EnumConstantDecl>(D);
2141           assert(EnumScope->isDeclScope(ED));
2142           EnumScope->RemoveDecl(ED);
2143           IdResolver.RemoveDecl(ED);
2144           ED->getLexicalDeclContext()->removeDecl(ED);
2145         }
2146       }
2147     }
2148   }
2149 
2150   // If the typedef types are not identical, reject them in all languages and
2151   // with any extensions enabled.
2152   if (isIncompatibleTypedef(Old, New))
2153     return;
2154 
2155   // The types match.  Link up the redeclaration chain and merge attributes if
2156   // the old declaration was a typedef.
2157   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2158     New->setPreviousDecl(Typedef);
2159     mergeDeclAttributes(New, Old);
2160   }
2161 
2162   if (getLangOpts().MicrosoftExt)
2163     return;
2164 
2165   if (getLangOpts().CPlusPlus) {
2166     // C++ [dcl.typedef]p2:
2167     //   In a given non-class scope, a typedef specifier can be used to
2168     //   redefine the name of any type declared in that scope to refer
2169     //   to the type to which it already refers.
2170     if (!isa<CXXRecordDecl>(CurContext))
2171       return;
2172 
2173     // C++0x [dcl.typedef]p4:
2174     //   In a given class scope, a typedef specifier can be used to redefine
2175     //   any class-name declared in that scope that is not also a typedef-name
2176     //   to refer to the type to which it already refers.
2177     //
2178     // This wording came in via DR424, which was a correction to the
2179     // wording in DR56, which accidentally banned code like:
2180     //
2181     //   struct S {
2182     //     typedef struct A { } A;
2183     //   };
2184     //
2185     // in the C++03 standard. We implement the C++0x semantics, which
2186     // allow the above but disallow
2187     //
2188     //   struct S {
2189     //     typedef int I;
2190     //     typedef int I;
2191     //   };
2192     //
2193     // since that was the intent of DR56.
2194     if (!isa<TypedefNameDecl>(Old))
2195       return;
2196 
2197     Diag(New->getLocation(), diag::err_redefinition)
2198       << New->getDeclName();
2199     notePreviousDefinition(Old, New->getLocation());
2200     return New->setInvalidDecl();
2201   }
2202 
2203   // Modules always permit redefinition of typedefs, as does C11.
2204   if (getLangOpts().Modules || getLangOpts().C11)
2205     return;
2206 
2207   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2208   // is normally mapped to an error, but can be controlled with
2209   // -Wtypedef-redefinition.  If either the original or the redefinition is
2210   // in a system header, don't emit this for compatibility with GCC.
2211   if (getDiagnostics().getSuppressSystemWarnings() &&
2212       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2213       (Old->isImplicit() ||
2214        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2215        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2216     return;
2217 
2218   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2219     << New->getDeclName();
2220   notePreviousDefinition(Old, New->getLocation());
2221 }
2222 
2223 /// DeclhasAttr - returns true if decl Declaration already has the target
2224 /// attribute.
2225 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2226   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2227   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2228   for (const auto *i : D->attrs())
2229     if (i->getKind() == A->getKind()) {
2230       if (Ann) {
2231         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2232           return true;
2233         continue;
2234       }
2235       // FIXME: Don't hardcode this check
2236       if (OA && isa<OwnershipAttr>(i))
2237         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2238       return true;
2239     }
2240 
2241   return false;
2242 }
2243 
2244 static bool isAttributeTargetADefinition(Decl *D) {
2245   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2246     return VD->isThisDeclarationADefinition();
2247   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2248     return TD->isCompleteDefinition() || TD->isBeingDefined();
2249   return true;
2250 }
2251 
2252 /// Merge alignment attributes from \p Old to \p New, taking into account the
2253 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2254 ///
2255 /// \return \c true if any attributes were added to \p New.
2256 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2257   // Look for alignas attributes on Old, and pick out whichever attribute
2258   // specifies the strictest alignment requirement.
2259   AlignedAttr *OldAlignasAttr = nullptr;
2260   AlignedAttr *OldStrictestAlignAttr = nullptr;
2261   unsigned OldAlign = 0;
2262   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2263     // FIXME: We have no way of representing inherited dependent alignments
2264     // in a case like:
2265     //   template<int A, int B> struct alignas(A) X;
2266     //   template<int A, int B> struct alignas(B) X {};
2267     // For now, we just ignore any alignas attributes which are not on the
2268     // definition in such a case.
2269     if (I->isAlignmentDependent())
2270       return false;
2271 
2272     if (I->isAlignas())
2273       OldAlignasAttr = I;
2274 
2275     unsigned Align = I->getAlignment(S.Context);
2276     if (Align > OldAlign) {
2277       OldAlign = Align;
2278       OldStrictestAlignAttr = I;
2279     }
2280   }
2281 
2282   // Look for alignas attributes on New.
2283   AlignedAttr *NewAlignasAttr = nullptr;
2284   unsigned NewAlign = 0;
2285   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2286     if (I->isAlignmentDependent())
2287       return false;
2288 
2289     if (I->isAlignas())
2290       NewAlignasAttr = I;
2291 
2292     unsigned Align = I->getAlignment(S.Context);
2293     if (Align > NewAlign)
2294       NewAlign = Align;
2295   }
2296 
2297   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2298     // Both declarations have 'alignas' attributes. We require them to match.
2299     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2300     // fall short. (If two declarations both have alignas, they must both match
2301     // every definition, and so must match each other if there is a definition.)
2302 
2303     // If either declaration only contains 'alignas(0)' specifiers, then it
2304     // specifies the natural alignment for the type.
2305     if (OldAlign == 0 || NewAlign == 0) {
2306       QualType Ty;
2307       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2308         Ty = VD->getType();
2309       else
2310         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2311 
2312       if (OldAlign == 0)
2313         OldAlign = S.Context.getTypeAlign(Ty);
2314       if (NewAlign == 0)
2315         NewAlign = S.Context.getTypeAlign(Ty);
2316     }
2317 
2318     if (OldAlign != NewAlign) {
2319       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2320         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2321         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2322       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2323     }
2324   }
2325 
2326   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2327     // C++11 [dcl.align]p6:
2328     //   if any declaration of an entity has an alignment-specifier,
2329     //   every defining declaration of that entity shall specify an
2330     //   equivalent alignment.
2331     // C11 6.7.5/7:
2332     //   If the definition of an object does not have an alignment
2333     //   specifier, any other declaration of that object shall also
2334     //   have no alignment specifier.
2335     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2336       << OldAlignasAttr;
2337     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2338       << OldAlignasAttr;
2339   }
2340 
2341   bool AnyAdded = false;
2342 
2343   // Ensure we have an attribute representing the strictest alignment.
2344   if (OldAlign > NewAlign) {
2345     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2346     Clone->setInherited(true);
2347     New->addAttr(Clone);
2348     AnyAdded = true;
2349   }
2350 
2351   // Ensure we have an alignas attribute if the old declaration had one.
2352   if (OldAlignasAttr && !NewAlignasAttr &&
2353       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2354     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2355     Clone->setInherited(true);
2356     New->addAttr(Clone);
2357     AnyAdded = true;
2358   }
2359 
2360   return AnyAdded;
2361 }
2362 
2363 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2364                                const InheritableAttr *Attr,
2365                                Sema::AvailabilityMergeKind AMK) {
2366   // This function copies an attribute Attr from a previous declaration to the
2367   // new declaration D if the new declaration doesn't itself have that attribute
2368   // yet or if that attribute allows duplicates.
2369   // If you're adding a new attribute that requires logic different from
2370   // "use explicit attribute on decl if present, else use attribute from
2371   // previous decl", for example if the attribute needs to be consistent
2372   // between redeclarations, you need to call a custom merge function here.
2373   InheritableAttr *NewAttr = nullptr;
2374   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2375   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2376     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2377                                       AA->isImplicit(), AA->getIntroduced(),
2378                                       AA->getDeprecated(),
2379                                       AA->getObsoleted(), AA->getUnavailable(),
2380                                       AA->getMessage(), AA->getStrict(),
2381                                       AA->getReplacement(), AMK,
2382                                       AttrSpellingListIndex);
2383   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2384     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2385                                     AttrSpellingListIndex);
2386   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2387     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2388                                         AttrSpellingListIndex);
2389   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2390     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2391                                    AttrSpellingListIndex);
2392   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2393     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2394                                    AttrSpellingListIndex);
2395   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2396     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2397                                 FA->getFormatIdx(), FA->getFirstArg(),
2398                                 AttrSpellingListIndex);
2399   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2400     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2401                                  AttrSpellingListIndex);
2402   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2403     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2404                                        AttrSpellingListIndex,
2405                                        IA->getSemanticSpelling());
2406   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2407     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2408                                       &S.Context.Idents.get(AA->getSpelling()),
2409                                       AttrSpellingListIndex);
2410   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2411            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2412             isa<CUDAGlobalAttr>(Attr))) {
2413     // CUDA target attributes are part of function signature for
2414     // overloading purposes and must not be merged.
2415     return false;
2416   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2417     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2418   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2419     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2420   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2421     NewAttr = S.mergeInternalLinkageAttr(
2422         D, InternalLinkageA->getRange(),
2423         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2424         AttrSpellingListIndex);
2425   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2426     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2427                                 &S.Context.Idents.get(CommonA->getSpelling()),
2428                                 AttrSpellingListIndex);
2429   else if (isa<AlignedAttr>(Attr))
2430     // AlignedAttrs are handled separately, because we need to handle all
2431     // such attributes on a declaration at the same time.
2432     NewAttr = nullptr;
2433   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2434            (AMK == Sema::AMK_Override ||
2435             AMK == Sema::AMK_ProtocolImplementation))
2436     NewAttr = nullptr;
2437   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2438     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2439                               UA->getGuid());
2440   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2441     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2442 
2443   if (NewAttr) {
2444     NewAttr->setInherited(true);
2445     D->addAttr(NewAttr);
2446     if (isa<MSInheritanceAttr>(NewAttr))
2447       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2448     return true;
2449   }
2450 
2451   return false;
2452 }
2453 
2454 static const NamedDecl *getDefinition(const Decl *D) {
2455   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2456     return TD->getDefinition();
2457   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2458     const VarDecl *Def = VD->getDefinition();
2459     if (Def)
2460       return Def;
2461     return VD->getActingDefinition();
2462   }
2463   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2464     return FD->getDefinition();
2465   return nullptr;
2466 }
2467 
2468 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2469   for (const auto *Attribute : D->attrs())
2470     if (Attribute->getKind() == Kind)
2471       return true;
2472   return false;
2473 }
2474 
2475 /// checkNewAttributesAfterDef - If we already have a definition, check that
2476 /// there are no new attributes in this declaration.
2477 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2478   if (!New->hasAttrs())
2479     return;
2480 
2481   const NamedDecl *Def = getDefinition(Old);
2482   if (!Def || Def == New)
2483     return;
2484 
2485   AttrVec &NewAttributes = New->getAttrs();
2486   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2487     const Attr *NewAttribute = NewAttributes[I];
2488 
2489     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2490       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2491         Sema::SkipBodyInfo SkipBody;
2492         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2493 
2494         // If we're skipping this definition, drop the "alias" attribute.
2495         if (SkipBody.ShouldSkip) {
2496           NewAttributes.erase(NewAttributes.begin() + I);
2497           --E;
2498           continue;
2499         }
2500       } else {
2501         VarDecl *VD = cast<VarDecl>(New);
2502         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2503                                 VarDecl::TentativeDefinition
2504                             ? diag::err_alias_after_tentative
2505                             : diag::err_redefinition;
2506         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2507         if (Diag == diag::err_redefinition)
2508           S.notePreviousDefinition(Def, VD->getLocation());
2509         else
2510           S.Diag(Def->getLocation(), diag::note_previous_definition);
2511         VD->setInvalidDecl();
2512       }
2513       ++I;
2514       continue;
2515     }
2516 
2517     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2518       // Tentative definitions are only interesting for the alias check above.
2519       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2520         ++I;
2521         continue;
2522       }
2523     }
2524 
2525     if (hasAttribute(Def, NewAttribute->getKind())) {
2526       ++I;
2527       continue; // regular attr merging will take care of validating this.
2528     }
2529 
2530     if (isa<C11NoReturnAttr>(NewAttribute)) {
2531       // C's _Noreturn is allowed to be added to a function after it is defined.
2532       ++I;
2533       continue;
2534     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2535       if (AA->isAlignas()) {
2536         // C++11 [dcl.align]p6:
2537         //   if any declaration of an entity has an alignment-specifier,
2538         //   every defining declaration of that entity shall specify an
2539         //   equivalent alignment.
2540         // C11 6.7.5/7:
2541         //   If the definition of an object does not have an alignment
2542         //   specifier, any other declaration of that object shall also
2543         //   have no alignment specifier.
2544         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2545           << AA;
2546         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2547           << AA;
2548         NewAttributes.erase(NewAttributes.begin() + I);
2549         --E;
2550         continue;
2551       }
2552     }
2553 
2554     S.Diag(NewAttribute->getLocation(),
2555            diag::warn_attribute_precede_definition);
2556     S.Diag(Def->getLocation(), diag::note_previous_definition);
2557     NewAttributes.erase(NewAttributes.begin() + I);
2558     --E;
2559   }
2560 }
2561 
2562 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2563 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2564                                AvailabilityMergeKind AMK) {
2565   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2566     UsedAttr *NewAttr = OldAttr->clone(Context);
2567     NewAttr->setInherited(true);
2568     New->addAttr(NewAttr);
2569   }
2570 
2571   if (!Old->hasAttrs() && !New->hasAttrs())
2572     return;
2573 
2574   // Attributes declared post-definition are currently ignored.
2575   checkNewAttributesAfterDef(*this, New, Old);
2576 
2577   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2578     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2579       if (OldA->getLabel() != NewA->getLabel()) {
2580         // This redeclaration changes __asm__ label.
2581         Diag(New->getLocation(), diag::err_different_asm_label);
2582         Diag(OldA->getLocation(), diag::note_previous_declaration);
2583       }
2584     } else if (Old->isUsed()) {
2585       // This redeclaration adds an __asm__ label to a declaration that has
2586       // already been ODR-used.
2587       Diag(New->getLocation(), diag::err_late_asm_label_name)
2588         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2589     }
2590   }
2591 
2592   // Re-declaration cannot add abi_tag's.
2593   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2594     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2595       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2596         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2597                       NewTag) == OldAbiTagAttr->tags_end()) {
2598           Diag(NewAbiTagAttr->getLocation(),
2599                diag::err_new_abi_tag_on_redeclaration)
2600               << NewTag;
2601           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2602         }
2603       }
2604     } else {
2605       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2606       Diag(Old->getLocation(), diag::note_previous_declaration);
2607     }
2608   }
2609 
2610   if (!Old->hasAttrs())
2611     return;
2612 
2613   bool foundAny = New->hasAttrs();
2614 
2615   // Ensure that any moving of objects within the allocated map is done before
2616   // we process them.
2617   if (!foundAny) New->setAttrs(AttrVec());
2618 
2619   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2620     // Ignore deprecated/unavailable/availability attributes if requested.
2621     AvailabilityMergeKind LocalAMK = AMK_None;
2622     if (isa<DeprecatedAttr>(I) ||
2623         isa<UnavailableAttr>(I) ||
2624         isa<AvailabilityAttr>(I)) {
2625       switch (AMK) {
2626       case AMK_None:
2627         continue;
2628 
2629       case AMK_Redeclaration:
2630       case AMK_Override:
2631       case AMK_ProtocolImplementation:
2632         LocalAMK = AMK;
2633         break;
2634       }
2635     }
2636 
2637     // Already handled.
2638     if (isa<UsedAttr>(I))
2639       continue;
2640 
2641     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2642       foundAny = true;
2643   }
2644 
2645   if (mergeAlignedAttrs(*this, New, Old))
2646     foundAny = true;
2647 
2648   if (!foundAny) New->dropAttrs();
2649 }
2650 
2651 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2652 /// to the new one.
2653 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2654                                      const ParmVarDecl *oldDecl,
2655                                      Sema &S) {
2656   // C++11 [dcl.attr.depend]p2:
2657   //   The first declaration of a function shall specify the
2658   //   carries_dependency attribute for its declarator-id if any declaration
2659   //   of the function specifies the carries_dependency attribute.
2660   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2661   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2662     S.Diag(CDA->getLocation(),
2663            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2664     // Find the first declaration of the parameter.
2665     // FIXME: Should we build redeclaration chains for function parameters?
2666     const FunctionDecl *FirstFD =
2667       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2668     const ParmVarDecl *FirstVD =
2669       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2670     S.Diag(FirstVD->getLocation(),
2671            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2672   }
2673 
2674   if (!oldDecl->hasAttrs())
2675     return;
2676 
2677   bool foundAny = newDecl->hasAttrs();
2678 
2679   // Ensure that any moving of objects within the allocated map is
2680   // done before we process them.
2681   if (!foundAny) newDecl->setAttrs(AttrVec());
2682 
2683   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2684     if (!DeclHasAttr(newDecl, I)) {
2685       InheritableAttr *newAttr =
2686         cast<InheritableParamAttr>(I->clone(S.Context));
2687       newAttr->setInherited(true);
2688       newDecl->addAttr(newAttr);
2689       foundAny = true;
2690     }
2691   }
2692 
2693   if (!foundAny) newDecl->dropAttrs();
2694 }
2695 
2696 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2697                                 const ParmVarDecl *OldParam,
2698                                 Sema &S) {
2699   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2700     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2701       if (*Oldnullability != *Newnullability) {
2702         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2703           << DiagNullabilityKind(
2704                *Newnullability,
2705                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2706                 != 0))
2707           << DiagNullabilityKind(
2708                *Oldnullability,
2709                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2710                 != 0));
2711         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2712       }
2713     } else {
2714       QualType NewT = NewParam->getType();
2715       NewT = S.Context.getAttributedType(
2716                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2717                          NewT, NewT);
2718       NewParam->setType(NewT);
2719     }
2720   }
2721 }
2722 
2723 namespace {
2724 
2725 /// Used in MergeFunctionDecl to keep track of function parameters in
2726 /// C.
2727 struct GNUCompatibleParamWarning {
2728   ParmVarDecl *OldParm;
2729   ParmVarDecl *NewParm;
2730   QualType PromotedType;
2731 };
2732 
2733 } // end anonymous namespace
2734 
2735 /// getSpecialMember - get the special member enum for a method.
2736 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2737   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2738     if (Ctor->isDefaultConstructor())
2739       return Sema::CXXDefaultConstructor;
2740 
2741     if (Ctor->isCopyConstructor())
2742       return Sema::CXXCopyConstructor;
2743 
2744     if (Ctor->isMoveConstructor())
2745       return Sema::CXXMoveConstructor;
2746   } else if (isa<CXXDestructorDecl>(MD)) {
2747     return Sema::CXXDestructor;
2748   } else if (MD->isCopyAssignmentOperator()) {
2749     return Sema::CXXCopyAssignment;
2750   } else if (MD->isMoveAssignmentOperator()) {
2751     return Sema::CXXMoveAssignment;
2752   }
2753 
2754   return Sema::CXXInvalid;
2755 }
2756 
2757 // Determine whether the previous declaration was a definition, implicit
2758 // declaration, or a declaration.
2759 template <typename T>
2760 static std::pair<diag::kind, SourceLocation>
2761 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2762   diag::kind PrevDiag;
2763   SourceLocation OldLocation = Old->getLocation();
2764   if (Old->isThisDeclarationADefinition())
2765     PrevDiag = diag::note_previous_definition;
2766   else if (Old->isImplicit()) {
2767     PrevDiag = diag::note_previous_implicit_declaration;
2768     if (OldLocation.isInvalid())
2769       OldLocation = New->getLocation();
2770   } else
2771     PrevDiag = diag::note_previous_declaration;
2772   return std::make_pair(PrevDiag, OldLocation);
2773 }
2774 
2775 /// canRedefineFunction - checks if a function can be redefined. Currently,
2776 /// only extern inline functions can be redefined, and even then only in
2777 /// GNU89 mode.
2778 static bool canRedefineFunction(const FunctionDecl *FD,
2779                                 const LangOptions& LangOpts) {
2780   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2781           !LangOpts.CPlusPlus &&
2782           FD->isInlineSpecified() &&
2783           FD->getStorageClass() == SC_Extern);
2784 }
2785 
2786 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2787   const AttributedType *AT = T->getAs<AttributedType>();
2788   while (AT && !AT->isCallingConv())
2789     AT = AT->getModifiedType()->getAs<AttributedType>();
2790   return AT;
2791 }
2792 
2793 template <typename T>
2794 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2795   const DeclContext *DC = Old->getDeclContext();
2796   if (DC->isRecord())
2797     return false;
2798 
2799   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2800   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2801     return true;
2802   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2803     return true;
2804   return false;
2805 }
2806 
2807 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2808 static bool isExternC(VarTemplateDecl *) { return false; }
2809 
2810 /// \brief Check whether a redeclaration of an entity introduced by a
2811 /// using-declaration is valid, given that we know it's not an overload
2812 /// (nor a hidden tag declaration).
2813 template<typename ExpectedDecl>
2814 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2815                                    ExpectedDecl *New) {
2816   // C++11 [basic.scope.declarative]p4:
2817   //   Given a set of declarations in a single declarative region, each of
2818   //   which specifies the same unqualified name,
2819   //   -- they shall all refer to the same entity, or all refer to functions
2820   //      and function templates; or
2821   //   -- exactly one declaration shall declare a class name or enumeration
2822   //      name that is not a typedef name and the other declarations shall all
2823   //      refer to the same variable or enumerator, or all refer to functions
2824   //      and function templates; in this case the class name or enumeration
2825   //      name is hidden (3.3.10).
2826 
2827   // C++11 [namespace.udecl]p14:
2828   //   If a function declaration in namespace scope or block scope has the
2829   //   same name and the same parameter-type-list as a function introduced
2830   //   by a using-declaration, and the declarations do not declare the same
2831   //   function, the program is ill-formed.
2832 
2833   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2834   if (Old &&
2835       !Old->getDeclContext()->getRedeclContext()->Equals(
2836           New->getDeclContext()->getRedeclContext()) &&
2837       !(isExternC(Old) && isExternC(New)))
2838     Old = nullptr;
2839 
2840   if (!Old) {
2841     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2842     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2843     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2844     return true;
2845   }
2846   return false;
2847 }
2848 
2849 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2850                                             const FunctionDecl *B) {
2851   assert(A->getNumParams() == B->getNumParams());
2852 
2853   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2854     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2855     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2856     if (AttrA == AttrB)
2857       return true;
2858     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2859   };
2860 
2861   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2862 }
2863 
2864 /// MergeFunctionDecl - We just parsed a function 'New' from
2865 /// declarator D which has the same name and scope as a previous
2866 /// declaration 'Old'.  Figure out how to resolve this situation,
2867 /// merging decls or emitting diagnostics as appropriate.
2868 ///
2869 /// In C++, New and Old must be declarations that are not
2870 /// overloaded. Use IsOverload to determine whether New and Old are
2871 /// overloaded, and to select the Old declaration that New should be
2872 /// merged with.
2873 ///
2874 /// Returns true if there was an error, false otherwise.
2875 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2876                              Scope *S, bool MergeTypeWithOld) {
2877   // Verify the old decl was also a function.
2878   FunctionDecl *Old = OldD->getAsFunction();
2879   if (!Old) {
2880     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2881       if (New->getFriendObjectKind()) {
2882         Diag(New->getLocation(), diag::err_using_decl_friend);
2883         Diag(Shadow->getTargetDecl()->getLocation(),
2884              diag::note_using_decl_target);
2885         Diag(Shadow->getUsingDecl()->getLocation(),
2886              diag::note_using_decl) << 0;
2887         return true;
2888       }
2889 
2890       // Check whether the two declarations might declare the same function.
2891       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2892         return true;
2893       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2894     } else {
2895       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2896         << New->getDeclName();
2897       notePreviousDefinition(OldD, New->getLocation());
2898       return true;
2899     }
2900   }
2901 
2902   // If the old declaration is invalid, just give up here.
2903   if (Old->isInvalidDecl())
2904     return true;
2905 
2906   diag::kind PrevDiag;
2907   SourceLocation OldLocation;
2908   std::tie(PrevDiag, OldLocation) =
2909       getNoteDiagForInvalidRedeclaration(Old, New);
2910 
2911   // Don't complain about this if we're in GNU89 mode and the old function
2912   // is an extern inline function.
2913   // Don't complain about specializations. They are not supposed to have
2914   // storage classes.
2915   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2916       New->getStorageClass() == SC_Static &&
2917       Old->hasExternalFormalLinkage() &&
2918       !New->getTemplateSpecializationInfo() &&
2919       !canRedefineFunction(Old, getLangOpts())) {
2920     if (getLangOpts().MicrosoftExt) {
2921       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2922       Diag(OldLocation, PrevDiag);
2923     } else {
2924       Diag(New->getLocation(), diag::err_static_non_static) << New;
2925       Diag(OldLocation, PrevDiag);
2926       return true;
2927     }
2928   }
2929 
2930   if (New->hasAttr<InternalLinkageAttr>() &&
2931       !Old->hasAttr<InternalLinkageAttr>()) {
2932     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2933         << New->getDeclName();
2934     notePreviousDefinition(Old, New->getLocation());
2935     New->dropAttr<InternalLinkageAttr>();
2936   }
2937 
2938   if (!getLangOpts().CPlusPlus) {
2939     bool OldOvl = Old->hasAttr<OverloadableAttr>();
2940     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
2941       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
2942         << New << OldOvl;
2943 
2944       // Try our best to find a decl that actually has the overloadable
2945       // attribute for the note. In most cases (e.g. programs with only one
2946       // broken declaration/definition), this won't matter.
2947       //
2948       // FIXME: We could do this if we juggled some extra state in
2949       // OverloadableAttr, rather than just removing it.
2950       const Decl *DiagOld = Old;
2951       if (OldOvl) {
2952         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
2953           const auto *A = D->getAttr<OverloadableAttr>();
2954           return A && !A->isImplicit();
2955         });
2956         // If we've implicitly added *all* of the overloadable attrs to this
2957         // chain, emitting a "previous redecl" note is pointless.
2958         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
2959       }
2960 
2961       if (DiagOld)
2962         Diag(DiagOld->getLocation(),
2963              diag::note_attribute_overloadable_prev_overload)
2964           << OldOvl;
2965 
2966       if (OldOvl)
2967         New->addAttr(OverloadableAttr::CreateImplicit(Context));
2968       else
2969         New->dropAttr<OverloadableAttr>();
2970     }
2971   }
2972 
2973   // If a function is first declared with a calling convention, but is later
2974   // declared or defined without one, all following decls assume the calling
2975   // convention of the first.
2976   //
2977   // It's OK if a function is first declared without a calling convention,
2978   // but is later declared or defined with the default calling convention.
2979   //
2980   // To test if either decl has an explicit calling convention, we look for
2981   // AttributedType sugar nodes on the type as written.  If they are missing or
2982   // were canonicalized away, we assume the calling convention was implicit.
2983   //
2984   // Note also that we DO NOT return at this point, because we still have
2985   // other tests to run.
2986   QualType OldQType = Context.getCanonicalType(Old->getType());
2987   QualType NewQType = Context.getCanonicalType(New->getType());
2988   const FunctionType *OldType = cast<FunctionType>(OldQType);
2989   const FunctionType *NewType = cast<FunctionType>(NewQType);
2990   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2991   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2992   bool RequiresAdjustment = false;
2993 
2994   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2995     FunctionDecl *First = Old->getFirstDecl();
2996     const FunctionType *FT =
2997         First->getType().getCanonicalType()->castAs<FunctionType>();
2998     FunctionType::ExtInfo FI = FT->getExtInfo();
2999     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3000     if (!NewCCExplicit) {
3001       // Inherit the CC from the previous declaration if it was specified
3002       // there but not here.
3003       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3004       RequiresAdjustment = true;
3005     } else {
3006       // Calling conventions aren't compatible, so complain.
3007       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3008       Diag(New->getLocation(), diag::err_cconv_change)
3009         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3010         << !FirstCCExplicit
3011         << (!FirstCCExplicit ? "" :
3012             FunctionType::getNameForCallConv(FI.getCC()));
3013 
3014       // Put the note on the first decl, since it is the one that matters.
3015       Diag(First->getLocation(), diag::note_previous_declaration);
3016       return true;
3017     }
3018   }
3019 
3020   // FIXME: diagnose the other way around?
3021   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3022     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3023     RequiresAdjustment = true;
3024   }
3025 
3026   // Merge regparm attribute.
3027   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3028       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3029     if (NewTypeInfo.getHasRegParm()) {
3030       Diag(New->getLocation(), diag::err_regparm_mismatch)
3031         << NewType->getRegParmType()
3032         << OldType->getRegParmType();
3033       Diag(OldLocation, diag::note_previous_declaration);
3034       return true;
3035     }
3036 
3037     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3038     RequiresAdjustment = true;
3039   }
3040 
3041   // Merge ns_returns_retained attribute.
3042   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3043     if (NewTypeInfo.getProducesResult()) {
3044       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3045           << "'ns_returns_retained'";
3046       Diag(OldLocation, diag::note_previous_declaration);
3047       return true;
3048     }
3049 
3050     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3051     RequiresAdjustment = true;
3052   }
3053 
3054   if (OldTypeInfo.getNoCallerSavedRegs() !=
3055       NewTypeInfo.getNoCallerSavedRegs()) {
3056     if (NewTypeInfo.getNoCallerSavedRegs()) {
3057       AnyX86NoCallerSavedRegistersAttr *Attr =
3058         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3059       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3060       Diag(OldLocation, diag::note_previous_declaration);
3061       return true;
3062     }
3063 
3064     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3065     RequiresAdjustment = true;
3066   }
3067 
3068   if (RequiresAdjustment) {
3069     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3070     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3071     New->setType(QualType(AdjustedType, 0));
3072     NewQType = Context.getCanonicalType(New->getType());
3073     NewType = cast<FunctionType>(NewQType);
3074   }
3075 
3076   // If this redeclaration makes the function inline, we may need to add it to
3077   // UndefinedButUsed.
3078   if (!Old->isInlined() && New->isInlined() &&
3079       !New->hasAttr<GNUInlineAttr>() &&
3080       !getLangOpts().GNUInline &&
3081       Old->isUsed(false) &&
3082       !Old->isDefined() && !New->isThisDeclarationADefinition())
3083     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3084                                            SourceLocation()));
3085 
3086   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3087   // about it.
3088   if (New->hasAttr<GNUInlineAttr>() &&
3089       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3090     UndefinedButUsed.erase(Old->getCanonicalDecl());
3091   }
3092 
3093   // If pass_object_size params don't match up perfectly, this isn't a valid
3094   // redeclaration.
3095   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3096       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3097     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3098         << New->getDeclName();
3099     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3100     return true;
3101   }
3102 
3103   if (getLangOpts().CPlusPlus) {
3104     // C++1z [over.load]p2
3105     //   Certain function declarations cannot be overloaded:
3106     //     -- Function declarations that differ only in the return type,
3107     //        the exception specification, or both cannot be overloaded.
3108 
3109     // Check the exception specifications match. This may recompute the type of
3110     // both Old and New if it resolved exception specifications, so grab the
3111     // types again after this. Because this updates the type, we do this before
3112     // any of the other checks below, which may update the "de facto" NewQType
3113     // but do not necessarily update the type of New.
3114     if (CheckEquivalentExceptionSpec(Old, New))
3115       return true;
3116     OldQType = Context.getCanonicalType(Old->getType());
3117     NewQType = Context.getCanonicalType(New->getType());
3118 
3119     // Go back to the type source info to compare the declared return types,
3120     // per C++1y [dcl.type.auto]p13:
3121     //   Redeclarations or specializations of a function or function template
3122     //   with a declared return type that uses a placeholder type shall also
3123     //   use that placeholder, not a deduced type.
3124     QualType OldDeclaredReturnType =
3125         (Old->getTypeSourceInfo()
3126              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3127              : OldType)->getReturnType();
3128     QualType NewDeclaredReturnType =
3129         (New->getTypeSourceInfo()
3130              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3131              : NewType)->getReturnType();
3132     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3133         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3134           New->isLocalExternDecl())) {
3135       QualType ResQT;
3136       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3137           OldDeclaredReturnType->isObjCObjectPointerType())
3138         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3139       if (ResQT.isNull()) {
3140         if (New->isCXXClassMember() && New->isOutOfLine())
3141           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3142               << New << New->getReturnTypeSourceRange();
3143         else
3144           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3145               << New->getReturnTypeSourceRange();
3146         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3147                                     << Old->getReturnTypeSourceRange();
3148         return true;
3149       }
3150       else
3151         NewQType = ResQT;
3152     }
3153 
3154     QualType OldReturnType = OldType->getReturnType();
3155     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3156     if (OldReturnType != NewReturnType) {
3157       // If this function has a deduced return type and has already been
3158       // defined, copy the deduced value from the old declaration.
3159       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3160       if (OldAT && OldAT->isDeduced()) {
3161         New->setType(
3162             SubstAutoType(New->getType(),
3163                           OldAT->isDependentType() ? Context.DependentTy
3164                                                    : OldAT->getDeducedType()));
3165         NewQType = Context.getCanonicalType(
3166             SubstAutoType(NewQType,
3167                           OldAT->isDependentType() ? Context.DependentTy
3168                                                    : OldAT->getDeducedType()));
3169       }
3170     }
3171 
3172     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3173     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3174     if (OldMethod && NewMethod) {
3175       // Preserve triviality.
3176       NewMethod->setTrivial(OldMethod->isTrivial());
3177 
3178       // MSVC allows explicit template specialization at class scope:
3179       // 2 CXXMethodDecls referring to the same function will be injected.
3180       // We don't want a redeclaration error.
3181       bool IsClassScopeExplicitSpecialization =
3182                               OldMethod->isFunctionTemplateSpecialization() &&
3183                               NewMethod->isFunctionTemplateSpecialization();
3184       bool isFriend = NewMethod->getFriendObjectKind();
3185 
3186       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3187           !IsClassScopeExplicitSpecialization) {
3188         //    -- Member function declarations with the same name and the
3189         //       same parameter types cannot be overloaded if any of them
3190         //       is a static member function declaration.
3191         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3192           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3193           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3194           return true;
3195         }
3196 
3197         // C++ [class.mem]p1:
3198         //   [...] A member shall not be declared twice in the
3199         //   member-specification, except that a nested class or member
3200         //   class template can be declared and then later defined.
3201         if (!inTemplateInstantiation()) {
3202           unsigned NewDiag;
3203           if (isa<CXXConstructorDecl>(OldMethod))
3204             NewDiag = diag::err_constructor_redeclared;
3205           else if (isa<CXXDestructorDecl>(NewMethod))
3206             NewDiag = diag::err_destructor_redeclared;
3207           else if (isa<CXXConversionDecl>(NewMethod))
3208             NewDiag = diag::err_conv_function_redeclared;
3209           else
3210             NewDiag = diag::err_member_redeclared;
3211 
3212           Diag(New->getLocation(), NewDiag);
3213         } else {
3214           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3215             << New << New->getType();
3216         }
3217         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3218         return true;
3219 
3220       // Complain if this is an explicit declaration of a special
3221       // member that was initially declared implicitly.
3222       //
3223       // As an exception, it's okay to befriend such methods in order
3224       // to permit the implicit constructor/destructor/operator calls.
3225       } else if (OldMethod->isImplicit()) {
3226         if (isFriend) {
3227           NewMethod->setImplicit();
3228         } else {
3229           Diag(NewMethod->getLocation(),
3230                diag::err_definition_of_implicitly_declared_member)
3231             << New << getSpecialMember(OldMethod);
3232           return true;
3233         }
3234       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3235         Diag(NewMethod->getLocation(),
3236              diag::err_definition_of_explicitly_defaulted_member)
3237           << getSpecialMember(OldMethod);
3238         return true;
3239       }
3240     }
3241 
3242     // C++11 [dcl.attr.noreturn]p1:
3243     //   The first declaration of a function shall specify the noreturn
3244     //   attribute if any declaration of that function specifies the noreturn
3245     //   attribute.
3246     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3247     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3248       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3249       Diag(Old->getFirstDecl()->getLocation(),
3250            diag::note_noreturn_missing_first_decl);
3251     }
3252 
3253     // C++11 [dcl.attr.depend]p2:
3254     //   The first declaration of a function shall specify the
3255     //   carries_dependency attribute for its declarator-id if any declaration
3256     //   of the function specifies the carries_dependency attribute.
3257     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3258     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3259       Diag(CDA->getLocation(),
3260            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3261       Diag(Old->getFirstDecl()->getLocation(),
3262            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3263     }
3264 
3265     // (C++98 8.3.5p3):
3266     //   All declarations for a function shall agree exactly in both the
3267     //   return type and the parameter-type-list.
3268     // We also want to respect all the extended bits except noreturn.
3269 
3270     // noreturn should now match unless the old type info didn't have it.
3271     QualType OldQTypeForComparison = OldQType;
3272     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3273       auto *OldType = OldQType->castAs<FunctionProtoType>();
3274       const FunctionType *OldTypeForComparison
3275         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3276       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3277       assert(OldQTypeForComparison.isCanonical());
3278     }
3279 
3280     if (haveIncompatibleLanguageLinkages(Old, New)) {
3281       // As a special case, retain the language linkage from previous
3282       // declarations of a friend function as an extension.
3283       //
3284       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3285       // and is useful because there's otherwise no way to specify language
3286       // linkage within class scope.
3287       //
3288       // Check cautiously as the friend object kind isn't yet complete.
3289       if (New->getFriendObjectKind() != Decl::FOK_None) {
3290         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3291         Diag(OldLocation, PrevDiag);
3292       } else {
3293         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3294         Diag(OldLocation, PrevDiag);
3295         return true;
3296       }
3297     }
3298 
3299     if (OldQTypeForComparison == NewQType)
3300       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3301 
3302     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3303         New->isLocalExternDecl()) {
3304       // It's OK if we couldn't merge types for a local function declaraton
3305       // if either the old or new type is dependent. We'll merge the types
3306       // when we instantiate the function.
3307       return false;
3308     }
3309 
3310     // Fall through for conflicting redeclarations and redefinitions.
3311   }
3312 
3313   // C: Function types need to be compatible, not identical. This handles
3314   // duplicate function decls like "void f(int); void f(enum X);" properly.
3315   if (!getLangOpts().CPlusPlus &&
3316       Context.typesAreCompatible(OldQType, NewQType)) {
3317     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3318     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3319     const FunctionProtoType *OldProto = nullptr;
3320     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3321         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3322       // The old declaration provided a function prototype, but the
3323       // new declaration does not. Merge in the prototype.
3324       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3325       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3326       NewQType =
3327           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3328                                   OldProto->getExtProtoInfo());
3329       New->setType(NewQType);
3330       New->setHasInheritedPrototype();
3331 
3332       // Synthesize parameters with the same types.
3333       SmallVector<ParmVarDecl*, 16> Params;
3334       for (const auto &ParamType : OldProto->param_types()) {
3335         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3336                                                  SourceLocation(), nullptr,
3337                                                  ParamType, /*TInfo=*/nullptr,
3338                                                  SC_None, nullptr);
3339         Param->setScopeInfo(0, Params.size());
3340         Param->setImplicit();
3341         Params.push_back(Param);
3342       }
3343 
3344       New->setParams(Params);
3345     }
3346 
3347     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3348   }
3349 
3350   // GNU C permits a K&R definition to follow a prototype declaration
3351   // if the declared types of the parameters in the K&R definition
3352   // match the types in the prototype declaration, even when the
3353   // promoted types of the parameters from the K&R definition differ
3354   // from the types in the prototype. GCC then keeps the types from
3355   // the prototype.
3356   //
3357   // If a variadic prototype is followed by a non-variadic K&R definition,
3358   // the K&R definition becomes variadic.  This is sort of an edge case, but
3359   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3360   // C99 6.9.1p8.
3361   if (!getLangOpts().CPlusPlus &&
3362       Old->hasPrototype() && !New->hasPrototype() &&
3363       New->getType()->getAs<FunctionProtoType>() &&
3364       Old->getNumParams() == New->getNumParams()) {
3365     SmallVector<QualType, 16> ArgTypes;
3366     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3367     const FunctionProtoType *OldProto
3368       = Old->getType()->getAs<FunctionProtoType>();
3369     const FunctionProtoType *NewProto
3370       = New->getType()->getAs<FunctionProtoType>();
3371 
3372     // Determine whether this is the GNU C extension.
3373     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3374                                                NewProto->getReturnType());
3375     bool LooseCompatible = !MergedReturn.isNull();
3376     for (unsigned Idx = 0, End = Old->getNumParams();
3377          LooseCompatible && Idx != End; ++Idx) {
3378       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3379       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3380       if (Context.typesAreCompatible(OldParm->getType(),
3381                                      NewProto->getParamType(Idx))) {
3382         ArgTypes.push_back(NewParm->getType());
3383       } else if (Context.typesAreCompatible(OldParm->getType(),
3384                                             NewParm->getType(),
3385                                             /*CompareUnqualified=*/true)) {
3386         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3387                                            NewProto->getParamType(Idx) };
3388         Warnings.push_back(Warn);
3389         ArgTypes.push_back(NewParm->getType());
3390       } else
3391         LooseCompatible = false;
3392     }
3393 
3394     if (LooseCompatible) {
3395       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3396         Diag(Warnings[Warn].NewParm->getLocation(),
3397              diag::ext_param_promoted_not_compatible_with_prototype)
3398           << Warnings[Warn].PromotedType
3399           << Warnings[Warn].OldParm->getType();
3400         if (Warnings[Warn].OldParm->getLocation().isValid())
3401           Diag(Warnings[Warn].OldParm->getLocation(),
3402                diag::note_previous_declaration);
3403       }
3404 
3405       if (MergeTypeWithOld)
3406         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3407                                              OldProto->getExtProtoInfo()));
3408       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3409     }
3410 
3411     // Fall through to diagnose conflicting types.
3412   }
3413 
3414   // A function that has already been declared has been redeclared or
3415   // defined with a different type; show an appropriate diagnostic.
3416 
3417   // If the previous declaration was an implicitly-generated builtin
3418   // declaration, then at the very least we should use a specialized note.
3419   unsigned BuiltinID;
3420   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3421     // If it's actually a library-defined builtin function like 'malloc'
3422     // or 'printf', just warn about the incompatible redeclaration.
3423     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3424       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3425       Diag(OldLocation, diag::note_previous_builtin_declaration)
3426         << Old << Old->getType();
3427 
3428       // If this is a global redeclaration, just forget hereafter
3429       // about the "builtin-ness" of the function.
3430       //
3431       // Doing this for local extern declarations is problematic.  If
3432       // the builtin declaration remains visible, a second invalid
3433       // local declaration will produce a hard error; if it doesn't
3434       // remain visible, a single bogus local redeclaration (which is
3435       // actually only a warning) could break all the downstream code.
3436       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3437         New->getIdentifier()->revertBuiltin();
3438 
3439       return false;
3440     }
3441 
3442     PrevDiag = diag::note_previous_builtin_declaration;
3443   }
3444 
3445   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3446   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3447   return true;
3448 }
3449 
3450 /// \brief Completes the merge of two function declarations that are
3451 /// known to be compatible.
3452 ///
3453 /// This routine handles the merging of attributes and other
3454 /// properties of function declarations from the old declaration to
3455 /// the new declaration, once we know that New is in fact a
3456 /// redeclaration of Old.
3457 ///
3458 /// \returns false
3459 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3460                                         Scope *S, bool MergeTypeWithOld) {
3461   // Merge the attributes
3462   mergeDeclAttributes(New, Old);
3463 
3464   // Merge "pure" flag.
3465   if (Old->isPure())
3466     New->setPure();
3467 
3468   // Merge "used" flag.
3469   if (Old->getMostRecentDecl()->isUsed(false))
3470     New->setIsUsed();
3471 
3472   // Merge attributes from the parameters.  These can mismatch with K&R
3473   // declarations.
3474   if (New->getNumParams() == Old->getNumParams())
3475       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3476         ParmVarDecl *NewParam = New->getParamDecl(i);
3477         ParmVarDecl *OldParam = Old->getParamDecl(i);
3478         mergeParamDeclAttributes(NewParam, OldParam, *this);
3479         mergeParamDeclTypes(NewParam, OldParam, *this);
3480       }
3481 
3482   if (getLangOpts().CPlusPlus)
3483     return MergeCXXFunctionDecl(New, Old, S);
3484 
3485   // Merge the function types so the we get the composite types for the return
3486   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3487   // was visible.
3488   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3489   if (!Merged.isNull() && MergeTypeWithOld)
3490     New->setType(Merged);
3491 
3492   return false;
3493 }
3494 
3495 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3496                                 ObjCMethodDecl *oldMethod) {
3497   // Merge the attributes, including deprecated/unavailable
3498   AvailabilityMergeKind MergeKind =
3499     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3500       ? AMK_ProtocolImplementation
3501       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3502                                                        : AMK_Override;
3503 
3504   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3505 
3506   // Merge attributes from the parameters.
3507   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3508                                        oe = oldMethod->param_end();
3509   for (ObjCMethodDecl::param_iterator
3510          ni = newMethod->param_begin(), ne = newMethod->param_end();
3511        ni != ne && oi != oe; ++ni, ++oi)
3512     mergeParamDeclAttributes(*ni, *oi, *this);
3513 
3514   CheckObjCMethodOverride(newMethod, oldMethod);
3515 }
3516 
3517 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3518   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3519 
3520   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3521          ? diag::err_redefinition_different_type
3522          : diag::err_redeclaration_different_type)
3523     << New->getDeclName() << New->getType() << Old->getType();
3524 
3525   diag::kind PrevDiag;
3526   SourceLocation OldLocation;
3527   std::tie(PrevDiag, OldLocation)
3528     = getNoteDiagForInvalidRedeclaration(Old, New);
3529   S.Diag(OldLocation, PrevDiag);
3530   New->setInvalidDecl();
3531 }
3532 
3533 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3534 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3535 /// emitting diagnostics as appropriate.
3536 ///
3537 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3538 /// to here in AddInitializerToDecl. We can't check them before the initializer
3539 /// is attached.
3540 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3541                              bool MergeTypeWithOld) {
3542   if (New->isInvalidDecl() || Old->isInvalidDecl())
3543     return;
3544 
3545   QualType MergedT;
3546   if (getLangOpts().CPlusPlus) {
3547     if (New->getType()->isUndeducedType()) {
3548       // We don't know what the new type is until the initializer is attached.
3549       return;
3550     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3551       // These could still be something that needs exception specs checked.
3552       return MergeVarDeclExceptionSpecs(New, Old);
3553     }
3554     // C++ [basic.link]p10:
3555     //   [...] the types specified by all declarations referring to a given
3556     //   object or function shall be identical, except that declarations for an
3557     //   array object can specify array types that differ by the presence or
3558     //   absence of a major array bound (8.3.4).
3559     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3560       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3561       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3562 
3563       // We are merging a variable declaration New into Old. If it has an array
3564       // bound, and that bound differs from Old's bound, we should diagnose the
3565       // mismatch.
3566       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3567         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3568              PrevVD = PrevVD->getPreviousDecl()) {
3569           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3570           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3571             continue;
3572 
3573           if (!Context.hasSameType(NewArray, PrevVDTy))
3574             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3575         }
3576       }
3577 
3578       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3579         if (Context.hasSameType(OldArray->getElementType(),
3580                                 NewArray->getElementType()))
3581           MergedT = New->getType();
3582       }
3583       // FIXME: Check visibility. New is hidden but has a complete type. If New
3584       // has no array bound, it should not inherit one from Old, if Old is not
3585       // visible.
3586       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3587         if (Context.hasSameType(OldArray->getElementType(),
3588                                 NewArray->getElementType()))
3589           MergedT = Old->getType();
3590       }
3591     }
3592     else if (New->getType()->isObjCObjectPointerType() &&
3593                Old->getType()->isObjCObjectPointerType()) {
3594       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3595                                               Old->getType());
3596     }
3597   } else {
3598     // C 6.2.7p2:
3599     //   All declarations that refer to the same object or function shall have
3600     //   compatible type.
3601     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3602   }
3603   if (MergedT.isNull()) {
3604     // It's OK if we couldn't merge types if either type is dependent, for a
3605     // block-scope variable. In other cases (static data members of class
3606     // templates, variable templates, ...), we require the types to be
3607     // equivalent.
3608     // FIXME: The C++ standard doesn't say anything about this.
3609     if ((New->getType()->isDependentType() ||
3610          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3611       // If the old type was dependent, we can't merge with it, so the new type
3612       // becomes dependent for now. We'll reproduce the original type when we
3613       // instantiate the TypeSourceInfo for the variable.
3614       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3615         New->setType(Context.DependentTy);
3616       return;
3617     }
3618     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3619   }
3620 
3621   // Don't actually update the type on the new declaration if the old
3622   // declaration was an extern declaration in a different scope.
3623   if (MergeTypeWithOld)
3624     New->setType(MergedT);
3625 }
3626 
3627 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3628                                   LookupResult &Previous) {
3629   // C11 6.2.7p4:
3630   //   For an identifier with internal or external linkage declared
3631   //   in a scope in which a prior declaration of that identifier is
3632   //   visible, if the prior declaration specifies internal or
3633   //   external linkage, the type of the identifier at the later
3634   //   declaration becomes the composite type.
3635   //
3636   // If the variable isn't visible, we do not merge with its type.
3637   if (Previous.isShadowed())
3638     return false;
3639 
3640   if (S.getLangOpts().CPlusPlus) {
3641     // C++11 [dcl.array]p3:
3642     //   If there is a preceding declaration of the entity in the same
3643     //   scope in which the bound was specified, an omitted array bound
3644     //   is taken to be the same as in that earlier declaration.
3645     return NewVD->isPreviousDeclInSameBlockScope() ||
3646            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3647             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3648   } else {
3649     // If the old declaration was function-local, don't merge with its
3650     // type unless we're in the same function.
3651     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3652            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3653   }
3654 }
3655 
3656 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3657 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3658 /// situation, merging decls or emitting diagnostics as appropriate.
3659 ///
3660 /// Tentative definition rules (C99 6.9.2p2) are checked by
3661 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3662 /// definitions here, since the initializer hasn't been attached.
3663 ///
3664 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3665   // If the new decl is already invalid, don't do any other checking.
3666   if (New->isInvalidDecl())
3667     return;
3668 
3669   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3670     return;
3671 
3672   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3673 
3674   // Verify the old decl was also a variable or variable template.
3675   VarDecl *Old = nullptr;
3676   VarTemplateDecl *OldTemplate = nullptr;
3677   if (Previous.isSingleResult()) {
3678     if (NewTemplate) {
3679       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3680       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3681 
3682       if (auto *Shadow =
3683               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3684         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3685           return New->setInvalidDecl();
3686     } else {
3687       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3688 
3689       if (auto *Shadow =
3690               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3691         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3692           return New->setInvalidDecl();
3693     }
3694   }
3695   if (!Old) {
3696     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3697         << New->getDeclName();
3698     notePreviousDefinition(Previous.getRepresentativeDecl(),
3699                            New->getLocation());
3700     return New->setInvalidDecl();
3701   }
3702 
3703   // Ensure the template parameters are compatible.
3704   if (NewTemplate &&
3705       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3706                                       OldTemplate->getTemplateParameters(),
3707                                       /*Complain=*/true, TPL_TemplateMatch))
3708     return New->setInvalidDecl();
3709 
3710   // C++ [class.mem]p1:
3711   //   A member shall not be declared twice in the member-specification [...]
3712   //
3713   // Here, we need only consider static data members.
3714   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3715     Diag(New->getLocation(), diag::err_duplicate_member)
3716       << New->getIdentifier();
3717     Diag(Old->getLocation(), diag::note_previous_declaration);
3718     New->setInvalidDecl();
3719   }
3720 
3721   mergeDeclAttributes(New, Old);
3722   // Warn if an already-declared variable is made a weak_import in a subsequent
3723   // declaration
3724   if (New->hasAttr<WeakImportAttr>() &&
3725       Old->getStorageClass() == SC_None &&
3726       !Old->hasAttr<WeakImportAttr>()) {
3727     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3728     notePreviousDefinition(Old, New->getLocation());
3729     // Remove weak_import attribute on new declaration.
3730     New->dropAttr<WeakImportAttr>();
3731   }
3732 
3733   if (New->hasAttr<InternalLinkageAttr>() &&
3734       !Old->hasAttr<InternalLinkageAttr>()) {
3735     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3736         << New->getDeclName();
3737     notePreviousDefinition(Old, New->getLocation());
3738     New->dropAttr<InternalLinkageAttr>();
3739   }
3740 
3741   // Merge the types.
3742   VarDecl *MostRecent = Old->getMostRecentDecl();
3743   if (MostRecent != Old) {
3744     MergeVarDeclTypes(New, MostRecent,
3745                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3746     if (New->isInvalidDecl())
3747       return;
3748   }
3749 
3750   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3751   if (New->isInvalidDecl())
3752     return;
3753 
3754   diag::kind PrevDiag;
3755   SourceLocation OldLocation;
3756   std::tie(PrevDiag, OldLocation) =
3757       getNoteDiagForInvalidRedeclaration(Old, New);
3758 
3759   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3760   if (New->getStorageClass() == SC_Static &&
3761       !New->isStaticDataMember() &&
3762       Old->hasExternalFormalLinkage()) {
3763     if (getLangOpts().MicrosoftExt) {
3764       Diag(New->getLocation(), diag::ext_static_non_static)
3765           << New->getDeclName();
3766       Diag(OldLocation, PrevDiag);
3767     } else {
3768       Diag(New->getLocation(), diag::err_static_non_static)
3769           << New->getDeclName();
3770       Diag(OldLocation, PrevDiag);
3771       return New->setInvalidDecl();
3772     }
3773   }
3774   // C99 6.2.2p4:
3775   //   For an identifier declared with the storage-class specifier
3776   //   extern in a scope in which a prior declaration of that
3777   //   identifier is visible,23) if the prior declaration specifies
3778   //   internal or external linkage, the linkage of the identifier at
3779   //   the later declaration is the same as the linkage specified at
3780   //   the prior declaration. If no prior declaration is visible, or
3781   //   if the prior declaration specifies no linkage, then the
3782   //   identifier has external linkage.
3783   if (New->hasExternalStorage() && Old->hasLinkage())
3784     /* Okay */;
3785   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3786            !New->isStaticDataMember() &&
3787            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3788     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3789     Diag(OldLocation, PrevDiag);
3790     return New->setInvalidDecl();
3791   }
3792 
3793   // Check if extern is followed by non-extern and vice-versa.
3794   if (New->hasExternalStorage() &&
3795       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3796     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3797     Diag(OldLocation, PrevDiag);
3798     return New->setInvalidDecl();
3799   }
3800   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3801       !New->hasExternalStorage()) {
3802     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3803     Diag(OldLocation, PrevDiag);
3804     return New->setInvalidDecl();
3805   }
3806 
3807   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3808 
3809   // FIXME: The test for external storage here seems wrong? We still
3810   // need to check for mismatches.
3811   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3812       // Don't complain about out-of-line definitions of static members.
3813       !(Old->getLexicalDeclContext()->isRecord() &&
3814         !New->getLexicalDeclContext()->isRecord())) {
3815     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3816     Diag(OldLocation, PrevDiag);
3817     return New->setInvalidDecl();
3818   }
3819 
3820   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3821     if (VarDecl *Def = Old->getDefinition()) {
3822       // C++1z [dcl.fcn.spec]p4:
3823       //   If the definition of a variable appears in a translation unit before
3824       //   its first declaration as inline, the program is ill-formed.
3825       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3826       Diag(Def->getLocation(), diag::note_previous_definition);
3827     }
3828   }
3829 
3830   // If this redeclaration makes the function inline, we may need to add it to
3831   // UndefinedButUsed.
3832   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3833       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3834     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3835                                            SourceLocation()));
3836 
3837   if (New->getTLSKind() != Old->getTLSKind()) {
3838     if (!Old->getTLSKind()) {
3839       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3840       Diag(OldLocation, PrevDiag);
3841     } else if (!New->getTLSKind()) {
3842       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3843       Diag(OldLocation, PrevDiag);
3844     } else {
3845       // Do not allow redeclaration to change the variable between requiring
3846       // static and dynamic initialization.
3847       // FIXME: GCC allows this, but uses the TLS keyword on the first
3848       // declaration to determine the kind. Do we need to be compatible here?
3849       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3850         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3851       Diag(OldLocation, PrevDiag);
3852     }
3853   }
3854 
3855   // C++ doesn't have tentative definitions, so go right ahead and check here.
3856   if (getLangOpts().CPlusPlus &&
3857       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3858     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3859         Old->getCanonicalDecl()->isConstexpr()) {
3860       // This definition won't be a definition any more once it's been merged.
3861       Diag(New->getLocation(),
3862            diag::warn_deprecated_redundant_constexpr_static_def);
3863     } else if (VarDecl *Def = Old->getDefinition()) {
3864       if (checkVarDeclRedefinition(Def, New))
3865         return;
3866     }
3867   }
3868 
3869   if (haveIncompatibleLanguageLinkages(Old, New)) {
3870     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3871     Diag(OldLocation, PrevDiag);
3872     New->setInvalidDecl();
3873     return;
3874   }
3875 
3876   // Merge "used" flag.
3877   if (Old->getMostRecentDecl()->isUsed(false))
3878     New->setIsUsed();
3879 
3880   // Keep a chain of previous declarations.
3881   New->setPreviousDecl(Old);
3882   if (NewTemplate)
3883     NewTemplate->setPreviousDecl(OldTemplate);
3884 
3885   // Inherit access appropriately.
3886   New->setAccess(Old->getAccess());
3887   if (NewTemplate)
3888     NewTemplate->setAccess(New->getAccess());
3889 
3890   if (Old->isInline())
3891     New->setImplicitlyInline();
3892 }
3893 
3894 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3895   SourceManager &SrcMgr = getSourceManager();
3896   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3897   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3898   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3899   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3900   auto &HSI = PP.getHeaderSearchInfo();
3901   StringRef HdrFilename =
3902       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3903 
3904   auto noteFromModuleOrInclude = [&](Module *Mod,
3905                                      SourceLocation IncLoc) -> bool {
3906     // Redefinition errors with modules are common with non modular mapped
3907     // headers, example: a non-modular header H in module A that also gets
3908     // included directly in a TU. Pointing twice to the same header/definition
3909     // is confusing, try to get better diagnostics when modules is on.
3910     if (IncLoc.isValid()) {
3911       if (Mod) {
3912         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3913             << HdrFilename.str() << Mod->getFullModuleName();
3914         if (!Mod->DefinitionLoc.isInvalid())
3915           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3916               << Mod->getFullModuleName();
3917       } else {
3918         Diag(IncLoc, diag::note_redefinition_include_same_file)
3919             << HdrFilename.str();
3920       }
3921       return true;
3922     }
3923 
3924     return false;
3925   };
3926 
3927   // Is it the same file and same offset? Provide more information on why
3928   // this leads to a redefinition error.
3929   bool EmittedDiag = false;
3930   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3931     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3932     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3933     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3934     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3935 
3936     // If the header has no guards, emit a note suggesting one.
3937     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3938       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3939 
3940     if (EmittedDiag)
3941       return;
3942   }
3943 
3944   // Redefinition coming from different files or couldn't do better above.
3945   Diag(Old->getLocation(), diag::note_previous_definition);
3946 }
3947 
3948 /// We've just determined that \p Old and \p New both appear to be definitions
3949 /// of the same variable. Either diagnose or fix the problem.
3950 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3951   if (!hasVisibleDefinition(Old) &&
3952       (New->getFormalLinkage() == InternalLinkage ||
3953        New->isInline() ||
3954        New->getDescribedVarTemplate() ||
3955        New->getNumTemplateParameterLists() ||
3956        New->getDeclContext()->isDependentContext())) {
3957     // The previous definition is hidden, and multiple definitions are
3958     // permitted (in separate TUs). Demote this to a declaration.
3959     New->demoteThisDefinitionToDeclaration();
3960 
3961     // Make the canonical definition visible.
3962     if (auto *OldTD = Old->getDescribedVarTemplate())
3963       makeMergedDefinitionVisible(OldTD);
3964     makeMergedDefinitionVisible(Old);
3965     return false;
3966   } else {
3967     Diag(New->getLocation(), diag::err_redefinition) << New;
3968     notePreviousDefinition(Old, New->getLocation());
3969     New->setInvalidDecl();
3970     return true;
3971   }
3972 }
3973 
3974 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3975 /// no declarator (e.g. "struct foo;") is parsed.
3976 Decl *
3977 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3978                                  RecordDecl *&AnonRecord) {
3979   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3980                                     AnonRecord);
3981 }
3982 
3983 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3984 // disambiguate entities defined in different scopes.
3985 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3986 // compatibility.
3987 // We will pick our mangling number depending on which version of MSVC is being
3988 // targeted.
3989 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3990   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3991              ? S->getMSCurManglingNumber()
3992              : S->getMSLastManglingNumber();
3993 }
3994 
3995 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3996   if (!Context.getLangOpts().CPlusPlus)
3997     return;
3998 
3999   if (isa<CXXRecordDecl>(Tag->getParent())) {
4000     // If this tag is the direct child of a class, number it if
4001     // it is anonymous.
4002     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4003       return;
4004     MangleNumberingContext &MCtx =
4005         Context.getManglingNumberContext(Tag->getParent());
4006     Context.setManglingNumber(
4007         Tag, MCtx.getManglingNumber(
4008                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4009     return;
4010   }
4011 
4012   // If this tag isn't a direct child of a class, number it if it is local.
4013   Decl *ManglingContextDecl;
4014   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4015           Tag->getDeclContext(), ManglingContextDecl)) {
4016     Context.setManglingNumber(
4017         Tag, MCtx->getManglingNumber(
4018                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4019   }
4020 }
4021 
4022 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4023                                         TypedefNameDecl *NewTD) {
4024   if (TagFromDeclSpec->isInvalidDecl())
4025     return;
4026 
4027   // Do nothing if the tag already has a name for linkage purposes.
4028   if (TagFromDeclSpec->hasNameForLinkage())
4029     return;
4030 
4031   // A well-formed anonymous tag must always be a TUK_Definition.
4032   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4033 
4034   // The type must match the tag exactly;  no qualifiers allowed.
4035   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4036                            Context.getTagDeclType(TagFromDeclSpec))) {
4037     if (getLangOpts().CPlusPlus)
4038       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4039     return;
4040   }
4041 
4042   // If we've already computed linkage for the anonymous tag, then
4043   // adding a typedef name for the anonymous decl can change that
4044   // linkage, which might be a serious problem.  Diagnose this as
4045   // unsupported and ignore the typedef name.  TODO: we should
4046   // pursue this as a language defect and establish a formal rule
4047   // for how to handle it.
4048   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4049     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4050 
4051     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4052     tagLoc = getLocForEndOfToken(tagLoc);
4053 
4054     llvm::SmallString<40> textToInsert;
4055     textToInsert += ' ';
4056     textToInsert += NewTD->getIdentifier()->getName();
4057     Diag(tagLoc, diag::note_typedef_changes_linkage)
4058         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4059     return;
4060   }
4061 
4062   // Otherwise, set this is the anon-decl typedef for the tag.
4063   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4064 }
4065 
4066 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4067   switch (T) {
4068   case DeclSpec::TST_class:
4069     return 0;
4070   case DeclSpec::TST_struct:
4071     return 1;
4072   case DeclSpec::TST_interface:
4073     return 2;
4074   case DeclSpec::TST_union:
4075     return 3;
4076   case DeclSpec::TST_enum:
4077     return 4;
4078   default:
4079     llvm_unreachable("unexpected type specifier");
4080   }
4081 }
4082 
4083 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4084 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4085 /// parameters to cope with template friend declarations.
4086 Decl *
4087 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4088                                  MultiTemplateParamsArg TemplateParams,
4089                                  bool IsExplicitInstantiation,
4090                                  RecordDecl *&AnonRecord) {
4091   Decl *TagD = nullptr;
4092   TagDecl *Tag = nullptr;
4093   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4094       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4095       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4096       DS.getTypeSpecType() == DeclSpec::TST_union ||
4097       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4098     TagD = DS.getRepAsDecl();
4099 
4100     if (!TagD) // We probably had an error
4101       return nullptr;
4102 
4103     // Note that the above type specs guarantee that the
4104     // type rep is a Decl, whereas in many of the others
4105     // it's a Type.
4106     if (isa<TagDecl>(TagD))
4107       Tag = cast<TagDecl>(TagD);
4108     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4109       Tag = CTD->getTemplatedDecl();
4110   }
4111 
4112   if (Tag) {
4113     handleTagNumbering(Tag, S);
4114     Tag->setFreeStanding();
4115     if (Tag->isInvalidDecl())
4116       return Tag;
4117   }
4118 
4119   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4120     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4121     // or incomplete types shall not be restrict-qualified."
4122     if (TypeQuals & DeclSpec::TQ_restrict)
4123       Diag(DS.getRestrictSpecLoc(),
4124            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4125            << DS.getSourceRange();
4126   }
4127 
4128   if (DS.isInlineSpecified())
4129     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4130         << getLangOpts().CPlusPlus1z;
4131 
4132   if (DS.isConstexprSpecified()) {
4133     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4134     // and definitions of functions and variables.
4135     if (Tag)
4136       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4137           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4138     else
4139       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4140     // Don't emit warnings after this error.
4141     return TagD;
4142   }
4143 
4144   if (DS.isConceptSpecified()) {
4145     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4146     // either a function concept and its definition or a variable concept and
4147     // its initializer.
4148     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4149     return TagD;
4150   }
4151 
4152   DiagnoseFunctionSpecifiers(DS);
4153 
4154   if (DS.isFriendSpecified()) {
4155     // If we're dealing with a decl but not a TagDecl, assume that
4156     // whatever routines created it handled the friendship aspect.
4157     if (TagD && !Tag)
4158       return nullptr;
4159     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4160   }
4161 
4162   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4163   bool IsExplicitSpecialization =
4164     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4165   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4166       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4167       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4168     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4169     // nested-name-specifier unless it is an explicit instantiation
4170     // or an explicit specialization.
4171     //
4172     // FIXME: We allow class template partial specializations here too, per the
4173     // obvious intent of DR1819.
4174     //
4175     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4176     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4177         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4178     return nullptr;
4179   }
4180 
4181   // Track whether this decl-specifier declares anything.
4182   bool DeclaresAnything = true;
4183 
4184   // Handle anonymous struct definitions.
4185   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4186     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4187         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4188       if (getLangOpts().CPlusPlus ||
4189           Record->getDeclContext()->isRecord()) {
4190         // If CurContext is a DeclContext that can contain statements,
4191         // RecursiveASTVisitor won't visit the decls that
4192         // BuildAnonymousStructOrUnion() will put into CurContext.
4193         // Also store them here so that they can be part of the
4194         // DeclStmt that gets created in this case.
4195         // FIXME: Also return the IndirectFieldDecls created by
4196         // BuildAnonymousStructOr union, for the same reason?
4197         if (CurContext->isFunctionOrMethod())
4198           AnonRecord = Record;
4199         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4200                                            Context.getPrintingPolicy());
4201       }
4202 
4203       DeclaresAnything = false;
4204     }
4205   }
4206 
4207   // C11 6.7.2.1p2:
4208   //   A struct-declaration that does not declare an anonymous structure or
4209   //   anonymous union shall contain a struct-declarator-list.
4210   //
4211   // This rule also existed in C89 and C99; the grammar for struct-declaration
4212   // did not permit a struct-declaration without a struct-declarator-list.
4213   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4214       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4215     // Check for Microsoft C extension: anonymous struct/union member.
4216     // Handle 2 kinds of anonymous struct/union:
4217     //   struct STRUCT;
4218     //   union UNION;
4219     // and
4220     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4221     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4222     if ((Tag && Tag->getDeclName()) ||
4223         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4224       RecordDecl *Record = nullptr;
4225       if (Tag)
4226         Record = dyn_cast<RecordDecl>(Tag);
4227       else if (const RecordType *RT =
4228                    DS.getRepAsType().get()->getAsStructureType())
4229         Record = RT->getDecl();
4230       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4231         Record = UT->getDecl();
4232 
4233       if (Record && getLangOpts().MicrosoftExt) {
4234         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4235           << Record->isUnion() << DS.getSourceRange();
4236         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4237       }
4238 
4239       DeclaresAnything = false;
4240     }
4241   }
4242 
4243   // Skip all the checks below if we have a type error.
4244   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4245       (TagD && TagD->isInvalidDecl()))
4246     return TagD;
4247 
4248   if (getLangOpts().CPlusPlus &&
4249       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4250     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4251       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4252           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4253         DeclaresAnything = false;
4254 
4255   if (!DS.isMissingDeclaratorOk()) {
4256     // Customize diagnostic for a typedef missing a name.
4257     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4258       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4259         << DS.getSourceRange();
4260     else
4261       DeclaresAnything = false;
4262   }
4263 
4264   if (DS.isModulePrivateSpecified() &&
4265       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4266     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4267       << Tag->getTagKind()
4268       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4269 
4270   ActOnDocumentableDecl(TagD);
4271 
4272   // C 6.7/2:
4273   //   A declaration [...] shall declare at least a declarator [...], a tag,
4274   //   or the members of an enumeration.
4275   // C++ [dcl.dcl]p3:
4276   //   [If there are no declarators], and except for the declaration of an
4277   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4278   //   names into the program, or shall redeclare a name introduced by a
4279   //   previous declaration.
4280   if (!DeclaresAnything) {
4281     // In C, we allow this as a (popular) extension / bug. Don't bother
4282     // producing further diagnostics for redundant qualifiers after this.
4283     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4284     return TagD;
4285   }
4286 
4287   // C++ [dcl.stc]p1:
4288   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4289   //   init-declarator-list of the declaration shall not be empty.
4290   // C++ [dcl.fct.spec]p1:
4291   //   If a cv-qualifier appears in a decl-specifier-seq, the
4292   //   init-declarator-list of the declaration shall not be empty.
4293   //
4294   // Spurious qualifiers here appear to be valid in C.
4295   unsigned DiagID = diag::warn_standalone_specifier;
4296   if (getLangOpts().CPlusPlus)
4297     DiagID = diag::ext_standalone_specifier;
4298 
4299   // Note that a linkage-specification sets a storage class, but
4300   // 'extern "C" struct foo;' is actually valid and not theoretically
4301   // useless.
4302   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4303     if (SCS == DeclSpec::SCS_mutable)
4304       // Since mutable is not a viable storage class specifier in C, there is
4305       // no reason to treat it as an extension. Instead, diagnose as an error.
4306       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4307     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4308       Diag(DS.getStorageClassSpecLoc(), DiagID)
4309         << DeclSpec::getSpecifierName(SCS);
4310   }
4311 
4312   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4313     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4314       << DeclSpec::getSpecifierName(TSCS);
4315   if (DS.getTypeQualifiers()) {
4316     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4317       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4318     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4319       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4320     // Restrict is covered above.
4321     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4322       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4323     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4324       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4325   }
4326 
4327   // Warn about ignored type attributes, for example:
4328   // __attribute__((aligned)) struct A;
4329   // Attributes should be placed after tag to apply to type declaration.
4330   if (!DS.getAttributes().empty()) {
4331     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4332     if (TypeSpecType == DeclSpec::TST_class ||
4333         TypeSpecType == DeclSpec::TST_struct ||
4334         TypeSpecType == DeclSpec::TST_interface ||
4335         TypeSpecType == DeclSpec::TST_union ||
4336         TypeSpecType == DeclSpec::TST_enum) {
4337       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4338            attrs = attrs->getNext())
4339         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4340             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4341     }
4342   }
4343 
4344   return TagD;
4345 }
4346 
4347 /// We are trying to inject an anonymous member into the given scope;
4348 /// check if there's an existing declaration that can't be overloaded.
4349 ///
4350 /// \return true if this is a forbidden redeclaration
4351 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4352                                          Scope *S,
4353                                          DeclContext *Owner,
4354                                          DeclarationName Name,
4355                                          SourceLocation NameLoc,
4356                                          bool IsUnion) {
4357   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4358                  Sema::ForRedeclaration);
4359   if (!SemaRef.LookupName(R, S)) return false;
4360 
4361   // Pick a representative declaration.
4362   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4363   assert(PrevDecl && "Expected a non-null Decl");
4364 
4365   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4366     return false;
4367 
4368   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4369     << IsUnion << Name;
4370   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4371 
4372   return true;
4373 }
4374 
4375 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4376 /// anonymous struct or union AnonRecord into the owning context Owner
4377 /// and scope S. This routine will be invoked just after we realize
4378 /// that an unnamed union or struct is actually an anonymous union or
4379 /// struct, e.g.,
4380 ///
4381 /// @code
4382 /// union {
4383 ///   int i;
4384 ///   float f;
4385 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4386 ///    // f into the surrounding scope.x
4387 /// @endcode
4388 ///
4389 /// This routine is recursive, injecting the names of nested anonymous
4390 /// structs/unions into the owning context and scope as well.
4391 static bool
4392 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4393                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4394                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4395   bool Invalid = false;
4396 
4397   // Look every FieldDecl and IndirectFieldDecl with a name.
4398   for (auto *D : AnonRecord->decls()) {
4399     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4400         cast<NamedDecl>(D)->getDeclName()) {
4401       ValueDecl *VD = cast<ValueDecl>(D);
4402       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4403                                        VD->getLocation(),
4404                                        AnonRecord->isUnion())) {
4405         // C++ [class.union]p2:
4406         //   The names of the members of an anonymous union shall be
4407         //   distinct from the names of any other entity in the
4408         //   scope in which the anonymous union is declared.
4409         Invalid = true;
4410       } else {
4411         // C++ [class.union]p2:
4412         //   For the purpose of name lookup, after the anonymous union
4413         //   definition, the members of the anonymous union are
4414         //   considered to have been defined in the scope in which the
4415         //   anonymous union is declared.
4416         unsigned OldChainingSize = Chaining.size();
4417         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4418           Chaining.append(IF->chain_begin(), IF->chain_end());
4419         else
4420           Chaining.push_back(VD);
4421 
4422         assert(Chaining.size() >= 2);
4423         NamedDecl **NamedChain =
4424           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4425         for (unsigned i = 0; i < Chaining.size(); i++)
4426           NamedChain[i] = Chaining[i];
4427 
4428         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4429             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4430             VD->getType(), {NamedChain, Chaining.size()});
4431 
4432         for (const auto *Attr : VD->attrs())
4433           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4434 
4435         IndirectField->setAccess(AS);
4436         IndirectField->setImplicit();
4437         SemaRef.PushOnScopeChains(IndirectField, S);
4438 
4439         // That includes picking up the appropriate access specifier.
4440         if (AS != AS_none) IndirectField->setAccess(AS);
4441 
4442         Chaining.resize(OldChainingSize);
4443       }
4444     }
4445   }
4446 
4447   return Invalid;
4448 }
4449 
4450 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4451 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4452 /// illegal input values are mapped to SC_None.
4453 static StorageClass
4454 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4455   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4456   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4457          "Parser allowed 'typedef' as storage class VarDecl.");
4458   switch (StorageClassSpec) {
4459   case DeclSpec::SCS_unspecified:    return SC_None;
4460   case DeclSpec::SCS_extern:
4461     if (DS.isExternInLinkageSpec())
4462       return SC_None;
4463     return SC_Extern;
4464   case DeclSpec::SCS_static:         return SC_Static;
4465   case DeclSpec::SCS_auto:           return SC_Auto;
4466   case DeclSpec::SCS_register:       return SC_Register;
4467   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4468     // Illegal SCSs map to None: error reporting is up to the caller.
4469   case DeclSpec::SCS_mutable:        // Fall through.
4470   case DeclSpec::SCS_typedef:        return SC_None;
4471   }
4472   llvm_unreachable("unknown storage class specifier");
4473 }
4474 
4475 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4476   assert(Record->hasInClassInitializer());
4477 
4478   for (const auto *I : Record->decls()) {
4479     const auto *FD = dyn_cast<FieldDecl>(I);
4480     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4481       FD = IFD->getAnonField();
4482     if (FD && FD->hasInClassInitializer())
4483       return FD->getLocation();
4484   }
4485 
4486   llvm_unreachable("couldn't find in-class initializer");
4487 }
4488 
4489 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4490                                       SourceLocation DefaultInitLoc) {
4491   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4492     return;
4493 
4494   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4495   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4496 }
4497 
4498 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4499                                       CXXRecordDecl *AnonUnion) {
4500   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4501     return;
4502 
4503   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4504 }
4505 
4506 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4507 /// anonymous structure or union. Anonymous unions are a C++ feature
4508 /// (C++ [class.union]) and a C11 feature; anonymous structures
4509 /// are a C11 feature and GNU C++ extension.
4510 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4511                                         AccessSpecifier AS,
4512                                         RecordDecl *Record,
4513                                         const PrintingPolicy &Policy) {
4514   DeclContext *Owner = Record->getDeclContext();
4515 
4516   // Diagnose whether this anonymous struct/union is an extension.
4517   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4518     Diag(Record->getLocation(), diag::ext_anonymous_union);
4519   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4520     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4521   else if (!Record->isUnion() && !getLangOpts().C11)
4522     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4523 
4524   // C and C++ require different kinds of checks for anonymous
4525   // structs/unions.
4526   bool Invalid = false;
4527   if (getLangOpts().CPlusPlus) {
4528     const char *PrevSpec = nullptr;
4529     unsigned DiagID;
4530     if (Record->isUnion()) {
4531       // C++ [class.union]p6:
4532       //   Anonymous unions declared in a named namespace or in the
4533       //   global namespace shall be declared static.
4534       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4535           (isa<TranslationUnitDecl>(Owner) ||
4536            (isa<NamespaceDecl>(Owner) &&
4537             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4538         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4539           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4540 
4541         // Recover by adding 'static'.
4542         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4543                                PrevSpec, DiagID, Policy);
4544       }
4545       // C++ [class.union]p6:
4546       //   A storage class is not allowed in a declaration of an
4547       //   anonymous union in a class scope.
4548       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4549                isa<RecordDecl>(Owner)) {
4550         Diag(DS.getStorageClassSpecLoc(),
4551              diag::err_anonymous_union_with_storage_spec)
4552           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4553 
4554         // Recover by removing the storage specifier.
4555         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4556                                SourceLocation(),
4557                                PrevSpec, DiagID, Context.getPrintingPolicy());
4558       }
4559     }
4560 
4561     // Ignore const/volatile/restrict qualifiers.
4562     if (DS.getTypeQualifiers()) {
4563       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4564         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4565           << Record->isUnion() << "const"
4566           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4567       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4568         Diag(DS.getVolatileSpecLoc(),
4569              diag::ext_anonymous_struct_union_qualified)
4570           << Record->isUnion() << "volatile"
4571           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4572       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4573         Diag(DS.getRestrictSpecLoc(),
4574              diag::ext_anonymous_struct_union_qualified)
4575           << Record->isUnion() << "restrict"
4576           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4577       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4578         Diag(DS.getAtomicSpecLoc(),
4579              diag::ext_anonymous_struct_union_qualified)
4580           << Record->isUnion() << "_Atomic"
4581           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4582       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4583         Diag(DS.getUnalignedSpecLoc(),
4584              diag::ext_anonymous_struct_union_qualified)
4585           << Record->isUnion() << "__unaligned"
4586           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4587 
4588       DS.ClearTypeQualifiers();
4589     }
4590 
4591     // C++ [class.union]p2:
4592     //   The member-specification of an anonymous union shall only
4593     //   define non-static data members. [Note: nested types and
4594     //   functions cannot be declared within an anonymous union. ]
4595     for (auto *Mem : Record->decls()) {
4596       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4597         // C++ [class.union]p3:
4598         //   An anonymous union shall not have private or protected
4599         //   members (clause 11).
4600         assert(FD->getAccess() != AS_none);
4601         if (FD->getAccess() != AS_public) {
4602           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4603             << Record->isUnion() << (FD->getAccess() == AS_protected);
4604           Invalid = true;
4605         }
4606 
4607         // C++ [class.union]p1
4608         //   An object of a class with a non-trivial constructor, a non-trivial
4609         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4610         //   assignment operator cannot be a member of a union, nor can an
4611         //   array of such objects.
4612         if (CheckNontrivialField(FD))
4613           Invalid = true;
4614       } else if (Mem->isImplicit()) {
4615         // Any implicit members are fine.
4616       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4617         // This is a type that showed up in an
4618         // elaborated-type-specifier inside the anonymous struct or
4619         // union, but which actually declares a type outside of the
4620         // anonymous struct or union. It's okay.
4621       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4622         if (!MemRecord->isAnonymousStructOrUnion() &&
4623             MemRecord->getDeclName()) {
4624           // Visual C++ allows type definition in anonymous struct or union.
4625           if (getLangOpts().MicrosoftExt)
4626             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4627               << Record->isUnion();
4628           else {
4629             // This is a nested type declaration.
4630             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4631               << Record->isUnion();
4632             Invalid = true;
4633           }
4634         } else {
4635           // This is an anonymous type definition within another anonymous type.
4636           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4637           // not part of standard C++.
4638           Diag(MemRecord->getLocation(),
4639                diag::ext_anonymous_record_with_anonymous_type)
4640             << Record->isUnion();
4641         }
4642       } else if (isa<AccessSpecDecl>(Mem)) {
4643         // Any access specifier is fine.
4644       } else if (isa<StaticAssertDecl>(Mem)) {
4645         // In C++1z, static_assert declarations are also fine.
4646       } else {
4647         // We have something that isn't a non-static data
4648         // member. Complain about it.
4649         unsigned DK = diag::err_anonymous_record_bad_member;
4650         if (isa<TypeDecl>(Mem))
4651           DK = diag::err_anonymous_record_with_type;
4652         else if (isa<FunctionDecl>(Mem))
4653           DK = diag::err_anonymous_record_with_function;
4654         else if (isa<VarDecl>(Mem))
4655           DK = diag::err_anonymous_record_with_static;
4656 
4657         // Visual C++ allows type definition in anonymous struct or union.
4658         if (getLangOpts().MicrosoftExt &&
4659             DK == diag::err_anonymous_record_with_type)
4660           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4661             << Record->isUnion();
4662         else {
4663           Diag(Mem->getLocation(), DK) << Record->isUnion();
4664           Invalid = true;
4665         }
4666       }
4667     }
4668 
4669     // C++11 [class.union]p8 (DR1460):
4670     //   At most one variant member of a union may have a
4671     //   brace-or-equal-initializer.
4672     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4673         Owner->isRecord())
4674       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4675                                 cast<CXXRecordDecl>(Record));
4676   }
4677 
4678   if (!Record->isUnion() && !Owner->isRecord()) {
4679     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4680       << getLangOpts().CPlusPlus;
4681     Invalid = true;
4682   }
4683 
4684   // Mock up a declarator.
4685   Declarator Dc(DS, Declarator::MemberContext);
4686   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4687   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4688 
4689   // Create a declaration for this anonymous struct/union.
4690   NamedDecl *Anon = nullptr;
4691   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4692     Anon = FieldDecl::Create(Context, OwningClass,
4693                              DS.getLocStart(),
4694                              Record->getLocation(),
4695                              /*IdentifierInfo=*/nullptr,
4696                              Context.getTypeDeclType(Record),
4697                              TInfo,
4698                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4699                              /*InitStyle=*/ICIS_NoInit);
4700     Anon->setAccess(AS);
4701     if (getLangOpts().CPlusPlus)
4702       FieldCollector->Add(cast<FieldDecl>(Anon));
4703   } else {
4704     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4705     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4706     if (SCSpec == DeclSpec::SCS_mutable) {
4707       // mutable can only appear on non-static class members, so it's always
4708       // an error here
4709       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4710       Invalid = true;
4711       SC = SC_None;
4712     }
4713 
4714     Anon = VarDecl::Create(Context, Owner,
4715                            DS.getLocStart(),
4716                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4717                            Context.getTypeDeclType(Record),
4718                            TInfo, SC);
4719 
4720     // Default-initialize the implicit variable. This initialization will be
4721     // trivial in almost all cases, except if a union member has an in-class
4722     // initializer:
4723     //   union { int n = 0; };
4724     ActOnUninitializedDecl(Anon);
4725   }
4726   Anon->setImplicit();
4727 
4728   // Mark this as an anonymous struct/union type.
4729   Record->setAnonymousStructOrUnion(true);
4730 
4731   // Add the anonymous struct/union object to the current
4732   // context. We'll be referencing this object when we refer to one of
4733   // its members.
4734   Owner->addDecl(Anon);
4735 
4736   // Inject the members of the anonymous struct/union into the owning
4737   // context and into the identifier resolver chain for name lookup
4738   // purposes.
4739   SmallVector<NamedDecl*, 2> Chain;
4740   Chain.push_back(Anon);
4741 
4742   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4743     Invalid = true;
4744 
4745   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4746     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4747       Decl *ManglingContextDecl;
4748       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4749               NewVD->getDeclContext(), ManglingContextDecl)) {
4750         Context.setManglingNumber(
4751             NewVD, MCtx->getManglingNumber(
4752                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4753         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4754       }
4755     }
4756   }
4757 
4758   if (Invalid)
4759     Anon->setInvalidDecl();
4760 
4761   return Anon;
4762 }
4763 
4764 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4765 /// Microsoft C anonymous structure.
4766 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4767 /// Example:
4768 ///
4769 /// struct A { int a; };
4770 /// struct B { struct A; int b; };
4771 ///
4772 /// void foo() {
4773 ///   B var;
4774 ///   var.a = 3;
4775 /// }
4776 ///
4777 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4778                                            RecordDecl *Record) {
4779   assert(Record && "expected a record!");
4780 
4781   // Mock up a declarator.
4782   Declarator Dc(DS, Declarator::TypeNameContext);
4783   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4784   assert(TInfo && "couldn't build declarator info for anonymous struct");
4785 
4786   auto *ParentDecl = cast<RecordDecl>(CurContext);
4787   QualType RecTy = Context.getTypeDeclType(Record);
4788 
4789   // Create a declaration for this anonymous struct.
4790   NamedDecl *Anon = FieldDecl::Create(Context,
4791                              ParentDecl,
4792                              DS.getLocStart(),
4793                              DS.getLocStart(),
4794                              /*IdentifierInfo=*/nullptr,
4795                              RecTy,
4796                              TInfo,
4797                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4798                              /*InitStyle=*/ICIS_NoInit);
4799   Anon->setImplicit();
4800 
4801   // Add the anonymous struct object to the current context.
4802   CurContext->addDecl(Anon);
4803 
4804   // Inject the members of the anonymous struct into the current
4805   // context and into the identifier resolver chain for name lookup
4806   // purposes.
4807   SmallVector<NamedDecl*, 2> Chain;
4808   Chain.push_back(Anon);
4809 
4810   RecordDecl *RecordDef = Record->getDefinition();
4811   if (RequireCompleteType(Anon->getLocation(), RecTy,
4812                           diag::err_field_incomplete) ||
4813       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4814                                           AS_none, Chain)) {
4815     Anon->setInvalidDecl();
4816     ParentDecl->setInvalidDecl();
4817   }
4818 
4819   return Anon;
4820 }
4821 
4822 /// GetNameForDeclarator - Determine the full declaration name for the
4823 /// given Declarator.
4824 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4825   return GetNameFromUnqualifiedId(D.getName());
4826 }
4827 
4828 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4829 DeclarationNameInfo
4830 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4831   DeclarationNameInfo NameInfo;
4832   NameInfo.setLoc(Name.StartLocation);
4833 
4834   switch (Name.getKind()) {
4835 
4836   case UnqualifiedId::IK_ImplicitSelfParam:
4837   case UnqualifiedId::IK_Identifier:
4838     NameInfo.setName(Name.Identifier);
4839     NameInfo.setLoc(Name.StartLocation);
4840     return NameInfo;
4841 
4842   case UnqualifiedId::IK_DeductionGuideName: {
4843     // C++ [temp.deduct.guide]p3:
4844     //   The simple-template-id shall name a class template specialization.
4845     //   The template-name shall be the same identifier as the template-name
4846     //   of the simple-template-id.
4847     // These together intend to imply that the template-name shall name a
4848     // class template.
4849     // FIXME: template<typename T> struct X {};
4850     //        template<typename T> using Y = X<T>;
4851     //        Y(int) -> Y<int>;
4852     //   satisfies these rules but does not name a class template.
4853     TemplateName TN = Name.TemplateName.get().get();
4854     auto *Template = TN.getAsTemplateDecl();
4855     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4856       Diag(Name.StartLocation,
4857            diag::err_deduction_guide_name_not_class_template)
4858         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4859       if (Template)
4860         Diag(Template->getLocation(), diag::note_template_decl_here);
4861       return DeclarationNameInfo();
4862     }
4863 
4864     NameInfo.setName(
4865         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4866     NameInfo.setLoc(Name.StartLocation);
4867     return NameInfo;
4868   }
4869 
4870   case UnqualifiedId::IK_OperatorFunctionId:
4871     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4872                                            Name.OperatorFunctionId.Operator));
4873     NameInfo.setLoc(Name.StartLocation);
4874     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4875       = Name.OperatorFunctionId.SymbolLocations[0];
4876     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4877       = Name.EndLocation.getRawEncoding();
4878     return NameInfo;
4879 
4880   case UnqualifiedId::IK_LiteralOperatorId:
4881     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4882                                                            Name.Identifier));
4883     NameInfo.setLoc(Name.StartLocation);
4884     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4885     return NameInfo;
4886 
4887   case UnqualifiedId::IK_ConversionFunctionId: {
4888     TypeSourceInfo *TInfo;
4889     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4890     if (Ty.isNull())
4891       return DeclarationNameInfo();
4892     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4893                                                Context.getCanonicalType(Ty)));
4894     NameInfo.setLoc(Name.StartLocation);
4895     NameInfo.setNamedTypeInfo(TInfo);
4896     return NameInfo;
4897   }
4898 
4899   case UnqualifiedId::IK_ConstructorName: {
4900     TypeSourceInfo *TInfo;
4901     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4902     if (Ty.isNull())
4903       return DeclarationNameInfo();
4904     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4905                                               Context.getCanonicalType(Ty)));
4906     NameInfo.setLoc(Name.StartLocation);
4907     NameInfo.setNamedTypeInfo(TInfo);
4908     return NameInfo;
4909   }
4910 
4911   case UnqualifiedId::IK_ConstructorTemplateId: {
4912     // In well-formed code, we can only have a constructor
4913     // template-id that refers to the current context, so go there
4914     // to find the actual type being constructed.
4915     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4916     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4917       return DeclarationNameInfo();
4918 
4919     // Determine the type of the class being constructed.
4920     QualType CurClassType = Context.getTypeDeclType(CurClass);
4921 
4922     // FIXME: Check two things: that the template-id names the same type as
4923     // CurClassType, and that the template-id does not occur when the name
4924     // was qualified.
4925 
4926     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4927                                     Context.getCanonicalType(CurClassType)));
4928     NameInfo.setLoc(Name.StartLocation);
4929     // FIXME: should we retrieve TypeSourceInfo?
4930     NameInfo.setNamedTypeInfo(nullptr);
4931     return NameInfo;
4932   }
4933 
4934   case UnqualifiedId::IK_DestructorName: {
4935     TypeSourceInfo *TInfo;
4936     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4937     if (Ty.isNull())
4938       return DeclarationNameInfo();
4939     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4940                                               Context.getCanonicalType(Ty)));
4941     NameInfo.setLoc(Name.StartLocation);
4942     NameInfo.setNamedTypeInfo(TInfo);
4943     return NameInfo;
4944   }
4945 
4946   case UnqualifiedId::IK_TemplateId: {
4947     TemplateName TName = Name.TemplateId->Template.get();
4948     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4949     return Context.getNameForTemplate(TName, TNameLoc);
4950   }
4951 
4952   } // switch (Name.getKind())
4953 
4954   llvm_unreachable("Unknown name kind");
4955 }
4956 
4957 static QualType getCoreType(QualType Ty) {
4958   do {
4959     if (Ty->isPointerType() || Ty->isReferenceType())
4960       Ty = Ty->getPointeeType();
4961     else if (Ty->isArrayType())
4962       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4963     else
4964       return Ty.withoutLocalFastQualifiers();
4965   } while (true);
4966 }
4967 
4968 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4969 /// and Definition have "nearly" matching parameters. This heuristic is
4970 /// used to improve diagnostics in the case where an out-of-line function
4971 /// definition doesn't match any declaration within the class or namespace.
4972 /// Also sets Params to the list of indices to the parameters that differ
4973 /// between the declaration and the definition. If hasSimilarParameters
4974 /// returns true and Params is empty, then all of the parameters match.
4975 static bool hasSimilarParameters(ASTContext &Context,
4976                                      FunctionDecl *Declaration,
4977                                      FunctionDecl *Definition,
4978                                      SmallVectorImpl<unsigned> &Params) {
4979   Params.clear();
4980   if (Declaration->param_size() != Definition->param_size())
4981     return false;
4982   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4983     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4984     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4985 
4986     // The parameter types are identical
4987     if (Context.hasSameType(DefParamTy, DeclParamTy))
4988       continue;
4989 
4990     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4991     QualType DefParamBaseTy = getCoreType(DefParamTy);
4992     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4993     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4994 
4995     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4996         (DeclTyName && DeclTyName == DefTyName))
4997       Params.push_back(Idx);
4998     else  // The two parameters aren't even close
4999       return false;
5000   }
5001 
5002   return true;
5003 }
5004 
5005 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5006 /// declarator needs to be rebuilt in the current instantiation.
5007 /// Any bits of declarator which appear before the name are valid for
5008 /// consideration here.  That's specifically the type in the decl spec
5009 /// and the base type in any member-pointer chunks.
5010 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5011                                                     DeclarationName Name) {
5012   // The types we specifically need to rebuild are:
5013   //   - typenames, typeofs, and decltypes
5014   //   - types which will become injected class names
5015   // Of course, we also need to rebuild any type referencing such a
5016   // type.  It's safest to just say "dependent", but we call out a
5017   // few cases here.
5018 
5019   DeclSpec &DS = D.getMutableDeclSpec();
5020   switch (DS.getTypeSpecType()) {
5021   case DeclSpec::TST_typename:
5022   case DeclSpec::TST_typeofType:
5023   case DeclSpec::TST_underlyingType:
5024   case DeclSpec::TST_atomic: {
5025     // Grab the type from the parser.
5026     TypeSourceInfo *TSI = nullptr;
5027     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5028     if (T.isNull() || !T->isDependentType()) break;
5029 
5030     // Make sure there's a type source info.  This isn't really much
5031     // of a waste; most dependent types should have type source info
5032     // attached already.
5033     if (!TSI)
5034       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5035 
5036     // Rebuild the type in the current instantiation.
5037     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5038     if (!TSI) return true;
5039 
5040     // Store the new type back in the decl spec.
5041     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5042     DS.UpdateTypeRep(LocType);
5043     break;
5044   }
5045 
5046   case DeclSpec::TST_decltype:
5047   case DeclSpec::TST_typeofExpr: {
5048     Expr *E = DS.getRepAsExpr();
5049     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5050     if (Result.isInvalid()) return true;
5051     DS.UpdateExprRep(Result.get());
5052     break;
5053   }
5054 
5055   default:
5056     // Nothing to do for these decl specs.
5057     break;
5058   }
5059 
5060   // It doesn't matter what order we do this in.
5061   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5062     DeclaratorChunk &Chunk = D.getTypeObject(I);
5063 
5064     // The only type information in the declarator which can come
5065     // before the declaration name is the base type of a member
5066     // pointer.
5067     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5068       continue;
5069 
5070     // Rebuild the scope specifier in-place.
5071     CXXScopeSpec &SS = Chunk.Mem.Scope();
5072     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5073       return true;
5074   }
5075 
5076   return false;
5077 }
5078 
5079 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5080   D.setFunctionDefinitionKind(FDK_Declaration);
5081   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5082 
5083   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5084       Dcl && Dcl->getDeclContext()->isFileContext())
5085     Dcl->setTopLevelDeclInObjCContainer();
5086 
5087   if (getLangOpts().OpenCL)
5088     setCurrentOpenCLExtensionForDecl(Dcl);
5089 
5090   return Dcl;
5091 }
5092 
5093 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5094 ///   If T is the name of a class, then each of the following shall have a
5095 ///   name different from T:
5096 ///     - every static data member of class T;
5097 ///     - every member function of class T
5098 ///     - every member of class T that is itself a type;
5099 /// \returns true if the declaration name violates these rules.
5100 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5101                                    DeclarationNameInfo NameInfo) {
5102   DeclarationName Name = NameInfo.getName();
5103 
5104   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5105   while (Record && Record->isAnonymousStructOrUnion())
5106     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5107   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5108     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5109     return true;
5110   }
5111 
5112   return false;
5113 }
5114 
5115 /// \brief Diagnose a declaration whose declarator-id has the given
5116 /// nested-name-specifier.
5117 ///
5118 /// \param SS The nested-name-specifier of the declarator-id.
5119 ///
5120 /// \param DC The declaration context to which the nested-name-specifier
5121 /// resolves.
5122 ///
5123 /// \param Name The name of the entity being declared.
5124 ///
5125 /// \param Loc The location of the name of the entity being declared.
5126 ///
5127 /// \returns true if we cannot safely recover from this error, false otherwise.
5128 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5129                                         DeclarationName Name,
5130                                         SourceLocation Loc) {
5131   DeclContext *Cur = CurContext;
5132   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5133     Cur = Cur->getParent();
5134 
5135   // If the user provided a superfluous scope specifier that refers back to the
5136   // class in which the entity is already declared, diagnose and ignore it.
5137   //
5138   // class X {
5139   //   void X::f();
5140   // };
5141   //
5142   // Note, it was once ill-formed to give redundant qualification in all
5143   // contexts, but that rule was removed by DR482.
5144   if (Cur->Equals(DC)) {
5145     if (Cur->isRecord()) {
5146       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5147                                       : diag::err_member_extra_qualification)
5148         << Name << FixItHint::CreateRemoval(SS.getRange());
5149       SS.clear();
5150     } else {
5151       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5152     }
5153     return false;
5154   }
5155 
5156   // Check whether the qualifying scope encloses the scope of the original
5157   // declaration.
5158   if (!Cur->Encloses(DC)) {
5159     if (Cur->isRecord())
5160       Diag(Loc, diag::err_member_qualification)
5161         << Name << SS.getRange();
5162     else if (isa<TranslationUnitDecl>(DC))
5163       Diag(Loc, diag::err_invalid_declarator_global_scope)
5164         << Name << SS.getRange();
5165     else if (isa<FunctionDecl>(Cur))
5166       Diag(Loc, diag::err_invalid_declarator_in_function)
5167         << Name << SS.getRange();
5168     else if (isa<BlockDecl>(Cur))
5169       Diag(Loc, diag::err_invalid_declarator_in_block)
5170         << Name << SS.getRange();
5171     else
5172       Diag(Loc, diag::err_invalid_declarator_scope)
5173       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5174 
5175     return true;
5176   }
5177 
5178   if (Cur->isRecord()) {
5179     // Cannot qualify members within a class.
5180     Diag(Loc, diag::err_member_qualification)
5181       << Name << SS.getRange();
5182     SS.clear();
5183 
5184     // C++ constructors and destructors with incorrect scopes can break
5185     // our AST invariants by having the wrong underlying types. If
5186     // that's the case, then drop this declaration entirely.
5187     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5188          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5189         !Context.hasSameType(Name.getCXXNameType(),
5190                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5191       return true;
5192 
5193     return false;
5194   }
5195 
5196   // C++11 [dcl.meaning]p1:
5197   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5198   //   not begin with a decltype-specifer"
5199   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5200   while (SpecLoc.getPrefix())
5201     SpecLoc = SpecLoc.getPrefix();
5202   if (dyn_cast_or_null<DecltypeType>(
5203         SpecLoc.getNestedNameSpecifier()->getAsType()))
5204     Diag(Loc, diag::err_decltype_in_declarator)
5205       << SpecLoc.getTypeLoc().getSourceRange();
5206 
5207   return false;
5208 }
5209 
5210 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5211                                   MultiTemplateParamsArg TemplateParamLists) {
5212   // TODO: consider using NameInfo for diagnostic.
5213   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5214   DeclarationName Name = NameInfo.getName();
5215 
5216   // All of these full declarators require an identifier.  If it doesn't have
5217   // one, the ParsedFreeStandingDeclSpec action should be used.
5218   if (D.isDecompositionDeclarator()) {
5219     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5220   } else if (!Name) {
5221     if (!D.isInvalidType())  // Reject this if we think it is valid.
5222       Diag(D.getDeclSpec().getLocStart(),
5223            diag::err_declarator_need_ident)
5224         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5225     return nullptr;
5226   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5227     return nullptr;
5228 
5229   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5230   // we find one that is.
5231   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5232          (S->getFlags() & Scope::TemplateParamScope) != 0)
5233     S = S->getParent();
5234 
5235   DeclContext *DC = CurContext;
5236   if (D.getCXXScopeSpec().isInvalid())
5237     D.setInvalidType();
5238   else if (D.getCXXScopeSpec().isSet()) {
5239     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5240                                         UPPC_DeclarationQualifier))
5241       return nullptr;
5242 
5243     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5244     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5245     if (!DC || isa<EnumDecl>(DC)) {
5246       // If we could not compute the declaration context, it's because the
5247       // declaration context is dependent but does not refer to a class,
5248       // class template, or class template partial specialization. Complain
5249       // and return early, to avoid the coming semantic disaster.
5250       Diag(D.getIdentifierLoc(),
5251            diag::err_template_qualified_declarator_no_match)
5252         << D.getCXXScopeSpec().getScopeRep()
5253         << D.getCXXScopeSpec().getRange();
5254       return nullptr;
5255     }
5256     bool IsDependentContext = DC->isDependentContext();
5257 
5258     if (!IsDependentContext &&
5259         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5260       return nullptr;
5261 
5262     // If a class is incomplete, do not parse entities inside it.
5263     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5264       Diag(D.getIdentifierLoc(),
5265            diag::err_member_def_undefined_record)
5266         << Name << DC << D.getCXXScopeSpec().getRange();
5267       return nullptr;
5268     }
5269     if (!D.getDeclSpec().isFriendSpecified()) {
5270       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5271                                       Name, D.getIdentifierLoc())) {
5272         if (DC->isRecord())
5273           return nullptr;
5274 
5275         D.setInvalidType();
5276       }
5277     }
5278 
5279     // Check whether we need to rebuild the type of the given
5280     // declaration in the current instantiation.
5281     if (EnteringContext && IsDependentContext &&
5282         TemplateParamLists.size() != 0) {
5283       ContextRAII SavedContext(*this, DC);
5284       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5285         D.setInvalidType();
5286     }
5287   }
5288 
5289   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5290   QualType R = TInfo->getType();
5291 
5292   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5293     // If this is a typedef, we'll end up spewing multiple diagnostics.
5294     // Just return early; it's safer. If this is a function, let the
5295     // "constructor cannot have a return type" diagnostic handle it.
5296     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5297       return nullptr;
5298 
5299   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5300                                       UPPC_DeclarationType))
5301     D.setInvalidType();
5302 
5303   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5304                         ForRedeclaration);
5305 
5306   // See if this is a redefinition of a variable in the same scope.
5307   if (!D.getCXXScopeSpec().isSet()) {
5308     bool IsLinkageLookup = false;
5309     bool CreateBuiltins = false;
5310 
5311     // If the declaration we're planning to build will be a function
5312     // or object with linkage, then look for another declaration with
5313     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5314     //
5315     // If the declaration we're planning to build will be declared with
5316     // external linkage in the translation unit, create any builtin with
5317     // the same name.
5318     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5319       /* Do nothing*/;
5320     else if (CurContext->isFunctionOrMethod() &&
5321              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5322               R->isFunctionType())) {
5323       IsLinkageLookup = true;
5324       CreateBuiltins =
5325           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5326     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5327                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5328       CreateBuiltins = true;
5329 
5330     if (IsLinkageLookup)
5331       Previous.clear(LookupRedeclarationWithLinkage);
5332 
5333     LookupName(Previous, S, CreateBuiltins);
5334   } else { // Something like "int foo::x;"
5335     LookupQualifiedName(Previous, DC);
5336 
5337     // C++ [dcl.meaning]p1:
5338     //   When the declarator-id is qualified, the declaration shall refer to a
5339     //  previously declared member of the class or namespace to which the
5340     //  qualifier refers (or, in the case of a namespace, of an element of the
5341     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5342     //  thereof; [...]
5343     //
5344     // Note that we already checked the context above, and that we do not have
5345     // enough information to make sure that Previous contains the declaration
5346     // we want to match. For example, given:
5347     //
5348     //   class X {
5349     //     void f();
5350     //     void f(float);
5351     //   };
5352     //
5353     //   void X::f(int) { } // ill-formed
5354     //
5355     // In this case, Previous will point to the overload set
5356     // containing the two f's declared in X, but neither of them
5357     // matches.
5358 
5359     // C++ [dcl.meaning]p1:
5360     //   [...] the member shall not merely have been introduced by a
5361     //   using-declaration in the scope of the class or namespace nominated by
5362     //   the nested-name-specifier of the declarator-id.
5363     RemoveUsingDecls(Previous);
5364   }
5365 
5366   if (Previous.isSingleResult() &&
5367       Previous.getFoundDecl()->isTemplateParameter()) {
5368     // Maybe we will complain about the shadowed template parameter.
5369     if (!D.isInvalidType())
5370       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5371                                       Previous.getFoundDecl());
5372 
5373     // Just pretend that we didn't see the previous declaration.
5374     Previous.clear();
5375   }
5376 
5377   // In C++, the previous declaration we find might be a tag type
5378   // (class or enum). In this case, the new declaration will hide the
5379   // tag type. Note that this does does not apply if we're declaring a
5380   // typedef (C++ [dcl.typedef]p4).
5381   if (Previous.isSingleTagDecl() &&
5382       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5383     Previous.clear();
5384 
5385   // Check that there are no default arguments other than in the parameters
5386   // of a function declaration (C++ only).
5387   if (getLangOpts().CPlusPlus)
5388     CheckExtraCXXDefaultArguments(D);
5389 
5390   if (D.getDeclSpec().isConceptSpecified()) {
5391     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5392     // applied only to the definition of a function template or variable
5393     // template, declared in namespace scope
5394     if (!TemplateParamLists.size()) {
5395       Diag(D.getDeclSpec().getConceptSpecLoc(),
5396            diag:: err_concept_wrong_decl_kind);
5397       return nullptr;
5398     }
5399 
5400     if (!DC->getRedeclContext()->isFileContext()) {
5401       Diag(D.getIdentifierLoc(),
5402            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5403       return nullptr;
5404     }
5405   }
5406 
5407   NamedDecl *New;
5408 
5409   bool AddToScope = true;
5410   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5411     if (TemplateParamLists.size()) {
5412       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5413       return nullptr;
5414     }
5415 
5416     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5417   } else if (R->isFunctionType()) {
5418     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5419                                   TemplateParamLists,
5420                                   AddToScope);
5421   } else {
5422     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5423                                   AddToScope);
5424   }
5425 
5426   if (!New)
5427     return nullptr;
5428 
5429   // If this has an identifier and is not a function template specialization,
5430   // add it to the scope stack.
5431   if (New->getDeclName() && AddToScope) {
5432     // Only make a locally-scoped extern declaration visible if it is the first
5433     // declaration of this entity. Qualified lookup for such an entity should
5434     // only find this declaration if there is no visible declaration of it.
5435     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5436     PushOnScopeChains(New, S, AddToContext);
5437     if (!AddToContext)
5438       CurContext->addHiddenDecl(New);
5439   }
5440 
5441   if (isInOpenMPDeclareTargetContext())
5442     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5443 
5444   return New;
5445 }
5446 
5447 /// Helper method to turn variable array types into constant array
5448 /// types in certain situations which would otherwise be errors (for
5449 /// GCC compatibility).
5450 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5451                                                     ASTContext &Context,
5452                                                     bool &SizeIsNegative,
5453                                                     llvm::APSInt &Oversized) {
5454   // This method tries to turn a variable array into a constant
5455   // array even when the size isn't an ICE.  This is necessary
5456   // for compatibility with code that depends on gcc's buggy
5457   // constant expression folding, like struct {char x[(int)(char*)2];}
5458   SizeIsNegative = false;
5459   Oversized = 0;
5460 
5461   if (T->isDependentType())
5462     return QualType();
5463 
5464   QualifierCollector Qs;
5465   const Type *Ty = Qs.strip(T);
5466 
5467   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5468     QualType Pointee = PTy->getPointeeType();
5469     QualType FixedType =
5470         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5471                                             Oversized);
5472     if (FixedType.isNull()) return FixedType;
5473     FixedType = Context.getPointerType(FixedType);
5474     return Qs.apply(Context, FixedType);
5475   }
5476   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5477     QualType Inner = PTy->getInnerType();
5478     QualType FixedType =
5479         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5480                                             Oversized);
5481     if (FixedType.isNull()) return FixedType;
5482     FixedType = Context.getParenType(FixedType);
5483     return Qs.apply(Context, FixedType);
5484   }
5485 
5486   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5487   if (!VLATy)
5488     return QualType();
5489   // FIXME: We should probably handle this case
5490   if (VLATy->getElementType()->isVariablyModifiedType())
5491     return QualType();
5492 
5493   llvm::APSInt Res;
5494   if (!VLATy->getSizeExpr() ||
5495       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5496     return QualType();
5497 
5498   // Check whether the array size is negative.
5499   if (Res.isSigned() && Res.isNegative()) {
5500     SizeIsNegative = true;
5501     return QualType();
5502   }
5503 
5504   // Check whether the array is too large to be addressed.
5505   unsigned ActiveSizeBits
5506     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5507                                               Res);
5508   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5509     Oversized = Res;
5510     return QualType();
5511   }
5512 
5513   return Context.getConstantArrayType(VLATy->getElementType(),
5514                                       Res, ArrayType::Normal, 0);
5515 }
5516 
5517 static void
5518 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5519   SrcTL = SrcTL.getUnqualifiedLoc();
5520   DstTL = DstTL.getUnqualifiedLoc();
5521   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5522     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5523     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5524                                       DstPTL.getPointeeLoc());
5525     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5526     return;
5527   }
5528   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5529     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5530     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5531                                       DstPTL.getInnerLoc());
5532     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5533     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5534     return;
5535   }
5536   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5537   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5538   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5539   TypeLoc DstElemTL = DstATL.getElementLoc();
5540   DstElemTL.initializeFullCopy(SrcElemTL);
5541   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5542   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5543   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5544 }
5545 
5546 /// Helper method to turn variable array types into constant array
5547 /// types in certain situations which would otherwise be errors (for
5548 /// GCC compatibility).
5549 static TypeSourceInfo*
5550 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5551                                               ASTContext &Context,
5552                                               bool &SizeIsNegative,
5553                                               llvm::APSInt &Oversized) {
5554   QualType FixedTy
5555     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5556                                           SizeIsNegative, Oversized);
5557   if (FixedTy.isNull())
5558     return nullptr;
5559   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5560   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5561                                     FixedTInfo->getTypeLoc());
5562   return FixedTInfo;
5563 }
5564 
5565 /// \brief Register the given locally-scoped extern "C" declaration so
5566 /// that it can be found later for redeclarations. We include any extern "C"
5567 /// declaration that is not visible in the translation unit here, not just
5568 /// function-scope declarations.
5569 void
5570 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5571   if (!getLangOpts().CPlusPlus &&
5572       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5573     // Don't need to track declarations in the TU in C.
5574     return;
5575 
5576   // Note that we have a locally-scoped external with this name.
5577   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5578 }
5579 
5580 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5581   // FIXME: We can have multiple results via __attribute__((overloadable)).
5582   auto Result = Context.getExternCContextDecl()->lookup(Name);
5583   return Result.empty() ? nullptr : *Result.begin();
5584 }
5585 
5586 /// \brief Diagnose function specifiers on a declaration of an identifier that
5587 /// does not identify a function.
5588 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5589   // FIXME: We should probably indicate the identifier in question to avoid
5590   // confusion for constructs like "virtual int a(), b;"
5591   if (DS.isVirtualSpecified())
5592     Diag(DS.getVirtualSpecLoc(),
5593          diag::err_virtual_non_function);
5594 
5595   if (DS.isExplicitSpecified())
5596     Diag(DS.getExplicitSpecLoc(),
5597          diag::err_explicit_non_function);
5598 
5599   if (DS.isNoreturnSpecified())
5600     Diag(DS.getNoreturnSpecLoc(),
5601          diag::err_noreturn_non_function);
5602 }
5603 
5604 NamedDecl*
5605 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5606                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5607   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5608   if (D.getCXXScopeSpec().isSet()) {
5609     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5610       << D.getCXXScopeSpec().getRange();
5611     D.setInvalidType();
5612     // Pretend we didn't see the scope specifier.
5613     DC = CurContext;
5614     Previous.clear();
5615   }
5616 
5617   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5618 
5619   if (D.getDeclSpec().isInlineSpecified())
5620     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5621         << getLangOpts().CPlusPlus1z;
5622   if (D.getDeclSpec().isConstexprSpecified())
5623     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5624       << 1;
5625   if (D.getDeclSpec().isConceptSpecified())
5626     Diag(D.getDeclSpec().getConceptSpecLoc(),
5627          diag::err_concept_wrong_decl_kind);
5628 
5629   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5630     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5631       Diag(D.getName().StartLocation,
5632            diag::err_deduction_guide_invalid_specifier)
5633           << "typedef";
5634     else
5635       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5636           << D.getName().getSourceRange();
5637     return nullptr;
5638   }
5639 
5640   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5641   if (!NewTD) return nullptr;
5642 
5643   // Handle attributes prior to checking for duplicates in MergeVarDecl
5644   ProcessDeclAttributes(S, NewTD, D);
5645 
5646   CheckTypedefForVariablyModifiedType(S, NewTD);
5647 
5648   bool Redeclaration = D.isRedeclaration();
5649   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5650   D.setRedeclaration(Redeclaration);
5651   return ND;
5652 }
5653 
5654 void
5655 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5656   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5657   // then it shall have block scope.
5658   // Note that variably modified types must be fixed before merging the decl so
5659   // that redeclarations will match.
5660   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5661   QualType T = TInfo->getType();
5662   if (T->isVariablyModifiedType()) {
5663     getCurFunction()->setHasBranchProtectedScope();
5664 
5665     if (S->getFnParent() == nullptr) {
5666       bool SizeIsNegative;
5667       llvm::APSInt Oversized;
5668       TypeSourceInfo *FixedTInfo =
5669         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5670                                                       SizeIsNegative,
5671                                                       Oversized);
5672       if (FixedTInfo) {
5673         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5674         NewTD->setTypeSourceInfo(FixedTInfo);
5675       } else {
5676         if (SizeIsNegative)
5677           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5678         else if (T->isVariableArrayType())
5679           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5680         else if (Oversized.getBoolValue())
5681           Diag(NewTD->getLocation(), diag::err_array_too_large)
5682             << Oversized.toString(10);
5683         else
5684           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5685         NewTD->setInvalidDecl();
5686       }
5687     }
5688   }
5689 }
5690 
5691 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5692 /// declares a typedef-name, either using the 'typedef' type specifier or via
5693 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5694 NamedDecl*
5695 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5696                            LookupResult &Previous, bool &Redeclaration) {
5697 
5698   // Find the shadowed declaration before filtering for scope.
5699   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5700 
5701   // Merge the decl with the existing one if appropriate. If the decl is
5702   // in an outer scope, it isn't the same thing.
5703   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5704                        /*AllowInlineNamespace*/false);
5705   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5706   if (!Previous.empty()) {
5707     Redeclaration = true;
5708     MergeTypedefNameDecl(S, NewTD, Previous);
5709   }
5710 
5711   if (ShadowedDecl && !Redeclaration)
5712     CheckShadow(NewTD, ShadowedDecl, Previous);
5713 
5714   // If this is the C FILE type, notify the AST context.
5715   if (IdentifierInfo *II = NewTD->getIdentifier())
5716     if (!NewTD->isInvalidDecl() &&
5717         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5718       if (II->isStr("FILE"))
5719         Context.setFILEDecl(NewTD);
5720       else if (II->isStr("jmp_buf"))
5721         Context.setjmp_bufDecl(NewTD);
5722       else if (II->isStr("sigjmp_buf"))
5723         Context.setsigjmp_bufDecl(NewTD);
5724       else if (II->isStr("ucontext_t"))
5725         Context.setucontext_tDecl(NewTD);
5726     }
5727 
5728   return NewTD;
5729 }
5730 
5731 /// \brief Determines whether the given declaration is an out-of-scope
5732 /// previous declaration.
5733 ///
5734 /// This routine should be invoked when name lookup has found a
5735 /// previous declaration (PrevDecl) that is not in the scope where a
5736 /// new declaration by the same name is being introduced. If the new
5737 /// declaration occurs in a local scope, previous declarations with
5738 /// linkage may still be considered previous declarations (C99
5739 /// 6.2.2p4-5, C++ [basic.link]p6).
5740 ///
5741 /// \param PrevDecl the previous declaration found by name
5742 /// lookup
5743 ///
5744 /// \param DC the context in which the new declaration is being
5745 /// declared.
5746 ///
5747 /// \returns true if PrevDecl is an out-of-scope previous declaration
5748 /// for a new delcaration with the same name.
5749 static bool
5750 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5751                                 ASTContext &Context) {
5752   if (!PrevDecl)
5753     return false;
5754 
5755   if (!PrevDecl->hasLinkage())
5756     return false;
5757 
5758   if (Context.getLangOpts().CPlusPlus) {
5759     // C++ [basic.link]p6:
5760     //   If there is a visible declaration of an entity with linkage
5761     //   having the same name and type, ignoring entities declared
5762     //   outside the innermost enclosing namespace scope, the block
5763     //   scope declaration declares that same entity and receives the
5764     //   linkage of the previous declaration.
5765     DeclContext *OuterContext = DC->getRedeclContext();
5766     if (!OuterContext->isFunctionOrMethod())
5767       // This rule only applies to block-scope declarations.
5768       return false;
5769 
5770     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5771     if (PrevOuterContext->isRecord())
5772       // We found a member function: ignore it.
5773       return false;
5774 
5775     // Find the innermost enclosing namespace for the new and
5776     // previous declarations.
5777     OuterContext = OuterContext->getEnclosingNamespaceContext();
5778     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5779 
5780     // The previous declaration is in a different namespace, so it
5781     // isn't the same function.
5782     if (!OuterContext->Equals(PrevOuterContext))
5783       return false;
5784   }
5785 
5786   return true;
5787 }
5788 
5789 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5790   CXXScopeSpec &SS = D.getCXXScopeSpec();
5791   if (!SS.isSet()) return;
5792   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5793 }
5794 
5795 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5796   QualType type = decl->getType();
5797   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5798   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5799     // Various kinds of declaration aren't allowed to be __autoreleasing.
5800     unsigned kind = -1U;
5801     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5802       if (var->hasAttr<BlocksAttr>())
5803         kind = 0; // __block
5804       else if (!var->hasLocalStorage())
5805         kind = 1; // global
5806     } else if (isa<ObjCIvarDecl>(decl)) {
5807       kind = 3; // ivar
5808     } else if (isa<FieldDecl>(decl)) {
5809       kind = 2; // field
5810     }
5811 
5812     if (kind != -1U) {
5813       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5814         << kind;
5815     }
5816   } else if (lifetime == Qualifiers::OCL_None) {
5817     // Try to infer lifetime.
5818     if (!type->isObjCLifetimeType())
5819       return false;
5820 
5821     lifetime = type->getObjCARCImplicitLifetime();
5822     type = Context.getLifetimeQualifiedType(type, lifetime);
5823     decl->setType(type);
5824   }
5825 
5826   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5827     // Thread-local variables cannot have lifetime.
5828     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5829         var->getTLSKind()) {
5830       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5831         << var->getType();
5832       return true;
5833     }
5834   }
5835 
5836   return false;
5837 }
5838 
5839 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5840   // Ensure that an auto decl is deduced otherwise the checks below might cache
5841   // the wrong linkage.
5842   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5843 
5844   // 'weak' only applies to declarations with external linkage.
5845   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5846     if (!ND.isExternallyVisible()) {
5847       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5848       ND.dropAttr<WeakAttr>();
5849     }
5850   }
5851   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5852     if (ND.isExternallyVisible()) {
5853       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5854       ND.dropAttr<WeakRefAttr>();
5855       ND.dropAttr<AliasAttr>();
5856     }
5857   }
5858 
5859   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5860     if (VD->hasInit()) {
5861       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5862         assert(VD->isThisDeclarationADefinition() &&
5863                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5864         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5865         VD->dropAttr<AliasAttr>();
5866       }
5867     }
5868   }
5869 
5870   // 'selectany' only applies to externally visible variable declarations.
5871   // It does not apply to functions.
5872   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5873     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5874       S.Diag(Attr->getLocation(),
5875              diag::err_attribute_selectany_non_extern_data);
5876       ND.dropAttr<SelectAnyAttr>();
5877     }
5878   }
5879 
5880   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5881     // dll attributes require external linkage. Static locals may have external
5882     // linkage but still cannot be explicitly imported or exported.
5883     auto *VD = dyn_cast<VarDecl>(&ND);
5884     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5885       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5886         << &ND << Attr;
5887       ND.setInvalidDecl();
5888     }
5889   }
5890 
5891   // Virtual functions cannot be marked as 'notail'.
5892   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5893     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5894       if (MD->isVirtual()) {
5895         S.Diag(ND.getLocation(),
5896                diag::err_invalid_attribute_on_virtual_function)
5897             << Attr;
5898         ND.dropAttr<NotTailCalledAttr>();
5899       }
5900 }
5901 
5902 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5903                                            NamedDecl *NewDecl,
5904                                            bool IsSpecialization,
5905                                            bool IsDefinition) {
5906   if (OldDecl->isInvalidDecl())
5907     return;
5908 
5909   bool IsTemplate = false;
5910   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5911     OldDecl = OldTD->getTemplatedDecl();
5912     IsTemplate = true;
5913     if (!IsSpecialization)
5914       IsDefinition = false;
5915   }
5916   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5917     NewDecl = NewTD->getTemplatedDecl();
5918     IsTemplate = true;
5919   }
5920 
5921   if (!OldDecl || !NewDecl)
5922     return;
5923 
5924   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5925   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5926   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5927   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5928 
5929   // dllimport and dllexport are inheritable attributes so we have to exclude
5930   // inherited attribute instances.
5931   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5932                     (NewExportAttr && !NewExportAttr->isInherited());
5933 
5934   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5935   // the only exception being explicit specializations.
5936   // Implicitly generated declarations are also excluded for now because there
5937   // is no other way to switch these to use dllimport or dllexport.
5938   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5939 
5940   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5941     // Allow with a warning for free functions and global variables.
5942     bool JustWarn = false;
5943     if (!OldDecl->isCXXClassMember()) {
5944       auto *VD = dyn_cast<VarDecl>(OldDecl);
5945       if (VD && !VD->getDescribedVarTemplate())
5946         JustWarn = true;
5947       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5948       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5949         JustWarn = true;
5950     }
5951 
5952     // We cannot change a declaration that's been used because IR has already
5953     // been emitted. Dllimported functions will still work though (modulo
5954     // address equality) as they can use the thunk.
5955     if (OldDecl->isUsed())
5956       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5957         JustWarn = false;
5958 
5959     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5960                                : diag::err_attribute_dll_redeclaration;
5961     S.Diag(NewDecl->getLocation(), DiagID)
5962         << NewDecl
5963         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5964     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5965     if (!JustWarn) {
5966       NewDecl->setInvalidDecl();
5967       return;
5968     }
5969   }
5970 
5971   // A redeclaration is not allowed to drop a dllimport attribute, the only
5972   // exceptions being inline function definitions (except for function
5973   // templates), local extern declarations, qualified friend declarations or
5974   // special MSVC extension: in the last case, the declaration is treated as if
5975   // it were marked dllexport.
5976   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5977   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5978   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5979     // Ignore static data because out-of-line definitions are diagnosed
5980     // separately.
5981     IsStaticDataMember = VD->isStaticDataMember();
5982     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5983                    VarDecl::DeclarationOnly;
5984   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5985     IsInline = FD->isInlined();
5986     IsQualifiedFriend = FD->getQualifier() &&
5987                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5988   }
5989 
5990   if (OldImportAttr && !HasNewAttr &&
5991       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5992       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5993     if (IsMicrosoft && IsDefinition) {
5994       S.Diag(NewDecl->getLocation(),
5995              diag::warn_redeclaration_without_import_attribute)
5996           << NewDecl;
5997       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5998       NewDecl->dropAttr<DLLImportAttr>();
5999       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6000           NewImportAttr->getRange(), S.Context,
6001           NewImportAttr->getSpellingListIndex()));
6002     } else {
6003       S.Diag(NewDecl->getLocation(),
6004              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6005           << NewDecl << OldImportAttr;
6006       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6007       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6008       OldDecl->dropAttr<DLLImportAttr>();
6009       NewDecl->dropAttr<DLLImportAttr>();
6010     }
6011   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6012     // In MinGW, seeing a function declared inline drops the dllimport attribute.
6013     OldDecl->dropAttr<DLLImportAttr>();
6014     NewDecl->dropAttr<DLLImportAttr>();
6015     S.Diag(NewDecl->getLocation(),
6016            diag::warn_dllimport_dropped_from_inline_function)
6017         << NewDecl << OldImportAttr;
6018   }
6019 }
6020 
6021 /// Given that we are within the definition of the given function,
6022 /// will that definition behave like C99's 'inline', where the
6023 /// definition is discarded except for optimization purposes?
6024 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6025   // Try to avoid calling GetGVALinkageForFunction.
6026 
6027   // All cases of this require the 'inline' keyword.
6028   if (!FD->isInlined()) return false;
6029 
6030   // This is only possible in C++ with the gnu_inline attribute.
6031   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6032     return false;
6033 
6034   // Okay, go ahead and call the relatively-more-expensive function.
6035   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6036 }
6037 
6038 /// Determine whether a variable is extern "C" prior to attaching
6039 /// an initializer. We can't just call isExternC() here, because that
6040 /// will also compute and cache whether the declaration is externally
6041 /// visible, which might change when we attach the initializer.
6042 ///
6043 /// This can only be used if the declaration is known to not be a
6044 /// redeclaration of an internal linkage declaration.
6045 ///
6046 /// For instance:
6047 ///
6048 ///   auto x = []{};
6049 ///
6050 /// Attaching the initializer here makes this declaration not externally
6051 /// visible, because its type has internal linkage.
6052 ///
6053 /// FIXME: This is a hack.
6054 template<typename T>
6055 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6056   if (S.getLangOpts().CPlusPlus) {
6057     // In C++, the overloadable attribute negates the effects of extern "C".
6058     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6059       return false;
6060 
6061     // So do CUDA's host/device attributes.
6062     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6063                                  D->template hasAttr<CUDAHostAttr>()))
6064       return false;
6065   }
6066   return D->isExternC();
6067 }
6068 
6069 static bool shouldConsiderLinkage(const VarDecl *VD) {
6070   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6071   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6072     return VD->hasExternalStorage();
6073   if (DC->isFileContext())
6074     return true;
6075   if (DC->isRecord())
6076     return false;
6077   llvm_unreachable("Unexpected context");
6078 }
6079 
6080 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6081   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6082   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6083       isa<OMPDeclareReductionDecl>(DC))
6084     return true;
6085   if (DC->isRecord())
6086     return false;
6087   llvm_unreachable("Unexpected context");
6088 }
6089 
6090 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6091                           AttributeList::Kind Kind) {
6092   for (const AttributeList *L = AttrList; L; L = L->getNext())
6093     if (L->getKind() == Kind)
6094       return true;
6095   return false;
6096 }
6097 
6098 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6099                           AttributeList::Kind Kind) {
6100   // Check decl attributes on the DeclSpec.
6101   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6102     return true;
6103 
6104   // Walk the declarator structure, checking decl attributes that were in a type
6105   // position to the decl itself.
6106   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6107     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6108       return true;
6109   }
6110 
6111   // Finally, check attributes on the decl itself.
6112   return hasParsedAttr(S, PD.getAttributes(), Kind);
6113 }
6114 
6115 /// Adjust the \c DeclContext for a function or variable that might be a
6116 /// function-local external declaration.
6117 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6118   if (!DC->isFunctionOrMethod())
6119     return false;
6120 
6121   // If this is a local extern function or variable declared within a function
6122   // template, don't add it into the enclosing namespace scope until it is
6123   // instantiated; it might have a dependent type right now.
6124   if (DC->isDependentContext())
6125     return true;
6126 
6127   // C++11 [basic.link]p7:
6128   //   When a block scope declaration of an entity with linkage is not found to
6129   //   refer to some other declaration, then that entity is a member of the
6130   //   innermost enclosing namespace.
6131   //
6132   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6133   // semantically-enclosing namespace, not a lexically-enclosing one.
6134   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6135     DC = DC->getParent();
6136   return true;
6137 }
6138 
6139 /// \brief Returns true if given declaration has external C language linkage.
6140 static bool isDeclExternC(const Decl *D) {
6141   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6142     return FD->isExternC();
6143   if (const auto *VD = dyn_cast<VarDecl>(D))
6144     return VD->isExternC();
6145 
6146   llvm_unreachable("Unknown type of decl!");
6147 }
6148 
6149 NamedDecl *Sema::ActOnVariableDeclarator(
6150     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6151     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6152     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6153   QualType R = TInfo->getType();
6154   DeclarationName Name = GetNameForDeclarator(D).getName();
6155 
6156   IdentifierInfo *II = Name.getAsIdentifierInfo();
6157 
6158   if (D.isDecompositionDeclarator()) {
6159     AddToScope = false;
6160     // Take the name of the first declarator as our name for diagnostic
6161     // purposes.
6162     auto &Decomp = D.getDecompositionDeclarator();
6163     if (!Decomp.bindings().empty()) {
6164       II = Decomp.bindings()[0].Name;
6165       Name = II;
6166     }
6167   } else if (!II) {
6168     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6169     return nullptr;
6170   }
6171 
6172   if (getLangOpts().OpenCL) {
6173     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6174     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6175     // argument.
6176     if (R->isImageType() || R->isPipeType()) {
6177       Diag(D.getIdentifierLoc(),
6178            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6179           << R;
6180       D.setInvalidType();
6181       return nullptr;
6182     }
6183 
6184     // OpenCL v1.2 s6.9.r:
6185     // The event type cannot be used to declare a program scope variable.
6186     // OpenCL v2.0 s6.9.q:
6187     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6188     if (NULL == S->getParent()) {
6189       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6190         Diag(D.getIdentifierLoc(),
6191              diag::err_invalid_type_for_program_scope_var) << R;
6192         D.setInvalidType();
6193         return nullptr;
6194       }
6195     }
6196 
6197     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6198     QualType NR = R;
6199     while (NR->isPointerType()) {
6200       if (NR->isFunctionPointerType()) {
6201         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6202         D.setInvalidType();
6203         break;
6204       }
6205       NR = NR->getPointeeType();
6206     }
6207 
6208     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6209       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6210       // half array type (unless the cl_khr_fp16 extension is enabled).
6211       if (Context.getBaseElementType(R)->isHalfType()) {
6212         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6213         D.setInvalidType();
6214       }
6215     }
6216 
6217     if (R->isSamplerT()) {
6218       // OpenCL v1.2 s6.9.b p4:
6219       // The sampler type cannot be used with the __local and __global address
6220       // space qualifiers.
6221       if (R.getAddressSpace() == LangAS::opencl_local ||
6222           R.getAddressSpace() == LangAS::opencl_global) {
6223         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6224       }
6225 
6226       // OpenCL v1.2 s6.12.14.1:
6227       // A global sampler must be declared with either the constant address
6228       // space qualifier or with the const qualifier.
6229       if (DC->isTranslationUnit() &&
6230           !(R.getAddressSpace() == LangAS::opencl_constant ||
6231           R.isConstQualified())) {
6232         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6233         D.setInvalidType();
6234       }
6235     }
6236 
6237     // OpenCL v1.2 s6.9.r:
6238     // The event type cannot be used with the __local, __constant and __global
6239     // address space qualifiers.
6240     if (R->isEventT()) {
6241       if (R.getAddressSpace()) {
6242         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6243         D.setInvalidType();
6244       }
6245     }
6246   }
6247 
6248   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6249   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6250 
6251   // dllimport globals without explicit storage class are treated as extern. We
6252   // have to change the storage class this early to get the right DeclContext.
6253   if (SC == SC_None && !DC->isRecord() &&
6254       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6255       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6256     SC = SC_Extern;
6257 
6258   DeclContext *OriginalDC = DC;
6259   bool IsLocalExternDecl = SC == SC_Extern &&
6260                            adjustContextForLocalExternDecl(DC);
6261 
6262   if (SCSpec == DeclSpec::SCS_mutable) {
6263     // mutable can only appear on non-static class members, so it's always
6264     // an error here
6265     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6266     D.setInvalidType();
6267     SC = SC_None;
6268   }
6269 
6270   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6271       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6272                               D.getDeclSpec().getStorageClassSpecLoc())) {
6273     // In C++11, the 'register' storage class specifier is deprecated.
6274     // Suppress the warning in system macros, it's used in macros in some
6275     // popular C system headers, such as in glibc's htonl() macro.
6276     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6277          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6278                                    : diag::warn_deprecated_register)
6279       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6280   }
6281 
6282   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6283 
6284   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6285     // C99 6.9p2: The storage-class specifiers auto and register shall not
6286     // appear in the declaration specifiers in an external declaration.
6287     // Global Register+Asm is a GNU extension we support.
6288     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6289       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6290       D.setInvalidType();
6291     }
6292   }
6293 
6294   bool IsMemberSpecialization = false;
6295   bool IsVariableTemplateSpecialization = false;
6296   bool IsPartialSpecialization = false;
6297   bool IsVariableTemplate = false;
6298   VarDecl *NewVD = nullptr;
6299   VarTemplateDecl *NewTemplate = nullptr;
6300   TemplateParameterList *TemplateParams = nullptr;
6301   if (!getLangOpts().CPlusPlus) {
6302     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6303                             D.getIdentifierLoc(), II,
6304                             R, TInfo, SC);
6305 
6306     if (R->getContainedDeducedType())
6307       ParsingInitForAutoVars.insert(NewVD);
6308 
6309     if (D.isInvalidType())
6310       NewVD->setInvalidDecl();
6311   } else {
6312     bool Invalid = false;
6313 
6314     if (DC->isRecord() && !CurContext->isRecord()) {
6315       // This is an out-of-line definition of a static data member.
6316       switch (SC) {
6317       case SC_None:
6318         break;
6319       case SC_Static:
6320         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6321              diag::err_static_out_of_line)
6322           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6323         break;
6324       case SC_Auto:
6325       case SC_Register:
6326       case SC_Extern:
6327         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6328         // to names of variables declared in a block or to function parameters.
6329         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6330         // of class members
6331 
6332         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6333              diag::err_storage_class_for_static_member)
6334           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6335         break;
6336       case SC_PrivateExtern:
6337         llvm_unreachable("C storage class in c++!");
6338       }
6339     }
6340 
6341     if (SC == SC_Static && CurContext->isRecord()) {
6342       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6343         if (RD->isLocalClass())
6344           Diag(D.getIdentifierLoc(),
6345                diag::err_static_data_member_not_allowed_in_local_class)
6346             << Name << RD->getDeclName();
6347 
6348         // C++98 [class.union]p1: If a union contains a static data member,
6349         // the program is ill-formed. C++11 drops this restriction.
6350         if (RD->isUnion())
6351           Diag(D.getIdentifierLoc(),
6352                getLangOpts().CPlusPlus11
6353                  ? diag::warn_cxx98_compat_static_data_member_in_union
6354                  : diag::ext_static_data_member_in_union) << Name;
6355         // We conservatively disallow static data members in anonymous structs.
6356         else if (!RD->getDeclName())
6357           Diag(D.getIdentifierLoc(),
6358                diag::err_static_data_member_not_allowed_in_anon_struct)
6359             << Name << RD->isUnion();
6360       }
6361     }
6362 
6363     // Match up the template parameter lists with the scope specifier, then
6364     // determine whether we have a template or a template specialization.
6365     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6366         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6367         D.getCXXScopeSpec(),
6368         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6369             ? D.getName().TemplateId
6370             : nullptr,
6371         TemplateParamLists,
6372         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6373 
6374     if (TemplateParams) {
6375       if (!TemplateParams->size() &&
6376           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6377         // There is an extraneous 'template<>' for this variable. Complain
6378         // about it, but allow the declaration of the variable.
6379         Diag(TemplateParams->getTemplateLoc(),
6380              diag::err_template_variable_noparams)
6381           << II
6382           << SourceRange(TemplateParams->getTemplateLoc(),
6383                          TemplateParams->getRAngleLoc());
6384         TemplateParams = nullptr;
6385       } else {
6386         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6387           // This is an explicit specialization or a partial specialization.
6388           // FIXME: Check that we can declare a specialization here.
6389           IsVariableTemplateSpecialization = true;
6390           IsPartialSpecialization = TemplateParams->size() > 0;
6391         } else { // if (TemplateParams->size() > 0)
6392           // This is a template declaration.
6393           IsVariableTemplate = true;
6394 
6395           // Check that we can declare a template here.
6396           if (CheckTemplateDeclScope(S, TemplateParams))
6397             return nullptr;
6398 
6399           // Only C++1y supports variable templates (N3651).
6400           Diag(D.getIdentifierLoc(),
6401                getLangOpts().CPlusPlus14
6402                    ? diag::warn_cxx11_compat_variable_template
6403                    : diag::ext_variable_template);
6404         }
6405       }
6406     } else {
6407       assert(
6408           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6409           "should have a 'template<>' for this decl");
6410     }
6411 
6412     if (IsVariableTemplateSpecialization) {
6413       SourceLocation TemplateKWLoc =
6414           TemplateParamLists.size() > 0
6415               ? TemplateParamLists[0]->getTemplateLoc()
6416               : SourceLocation();
6417       DeclResult Res = ActOnVarTemplateSpecialization(
6418           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6419           IsPartialSpecialization);
6420       if (Res.isInvalid())
6421         return nullptr;
6422       NewVD = cast<VarDecl>(Res.get());
6423       AddToScope = false;
6424     } else if (D.isDecompositionDeclarator()) {
6425       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6426                                         D.getIdentifierLoc(), R, TInfo, SC,
6427                                         Bindings);
6428     } else
6429       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6430                               D.getIdentifierLoc(), II, R, TInfo, SC);
6431 
6432     // If this is supposed to be a variable template, create it as such.
6433     if (IsVariableTemplate) {
6434       NewTemplate =
6435           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6436                                   TemplateParams, NewVD);
6437       NewVD->setDescribedVarTemplate(NewTemplate);
6438     }
6439 
6440     // If this decl has an auto type in need of deduction, make a note of the
6441     // Decl so we can diagnose uses of it in its own initializer.
6442     if (R->getContainedDeducedType())
6443       ParsingInitForAutoVars.insert(NewVD);
6444 
6445     if (D.isInvalidType() || Invalid) {
6446       NewVD->setInvalidDecl();
6447       if (NewTemplate)
6448         NewTemplate->setInvalidDecl();
6449     }
6450 
6451     SetNestedNameSpecifier(NewVD, D);
6452 
6453     // If we have any template parameter lists that don't directly belong to
6454     // the variable (matching the scope specifier), store them.
6455     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6456     if (TemplateParamLists.size() > VDTemplateParamLists)
6457       NewVD->setTemplateParameterListsInfo(
6458           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6459 
6460     if (D.getDeclSpec().isConstexprSpecified()) {
6461       NewVD->setConstexpr(true);
6462       // C++1z [dcl.spec.constexpr]p1:
6463       //   A static data member declared with the constexpr specifier is
6464       //   implicitly an inline variable.
6465       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6466         NewVD->setImplicitlyInline();
6467     }
6468 
6469     if (D.getDeclSpec().isConceptSpecified()) {
6470       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6471         VTD->setConcept();
6472 
6473       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6474       // be declared with the thread_local, inline, friend, or constexpr
6475       // specifiers, [...]
6476       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6477         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6478              diag::err_concept_decl_invalid_specifiers)
6479             << 0 << 0;
6480         NewVD->setInvalidDecl(true);
6481       }
6482 
6483       if (D.getDeclSpec().isConstexprSpecified()) {
6484         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6485              diag::err_concept_decl_invalid_specifiers)
6486             << 0 << 3;
6487         NewVD->setInvalidDecl(true);
6488       }
6489 
6490       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6491       // applied only to the definition of a function template or variable
6492       // template, declared in namespace scope.
6493       if (IsVariableTemplateSpecialization) {
6494         Diag(D.getDeclSpec().getConceptSpecLoc(),
6495              diag::err_concept_specified_specialization)
6496             << (IsPartialSpecialization ? 2 : 1);
6497       }
6498 
6499       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6500       // following restrictions:
6501       // - The declared type shall have the type bool.
6502       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6503           !NewVD->isInvalidDecl()) {
6504         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6505         NewVD->setInvalidDecl(true);
6506       }
6507     }
6508   }
6509 
6510   if (D.getDeclSpec().isInlineSpecified()) {
6511     if (!getLangOpts().CPlusPlus) {
6512       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6513           << 0;
6514     } else if (CurContext->isFunctionOrMethod()) {
6515       // 'inline' is not allowed on block scope variable declaration.
6516       Diag(D.getDeclSpec().getInlineSpecLoc(),
6517            diag::err_inline_declaration_block_scope) << Name
6518         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6519     } else {
6520       Diag(D.getDeclSpec().getInlineSpecLoc(),
6521            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6522                                      : diag::ext_inline_variable);
6523       NewVD->setInlineSpecified();
6524     }
6525   }
6526 
6527   // Set the lexical context. If the declarator has a C++ scope specifier, the
6528   // lexical context will be different from the semantic context.
6529   NewVD->setLexicalDeclContext(CurContext);
6530   if (NewTemplate)
6531     NewTemplate->setLexicalDeclContext(CurContext);
6532 
6533   if (IsLocalExternDecl) {
6534     if (D.isDecompositionDeclarator())
6535       for (auto *B : Bindings)
6536         B->setLocalExternDecl();
6537     else
6538       NewVD->setLocalExternDecl();
6539   }
6540 
6541   bool EmitTLSUnsupportedError = false;
6542   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6543     // C++11 [dcl.stc]p4:
6544     //   When thread_local is applied to a variable of block scope the
6545     //   storage-class-specifier static is implied if it does not appear
6546     //   explicitly.
6547     // Core issue: 'static' is not implied if the variable is declared
6548     //   'extern'.
6549     if (NewVD->hasLocalStorage() &&
6550         (SCSpec != DeclSpec::SCS_unspecified ||
6551          TSCS != DeclSpec::TSCS_thread_local ||
6552          !DC->isFunctionOrMethod()))
6553       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6554            diag::err_thread_non_global)
6555         << DeclSpec::getSpecifierName(TSCS);
6556     else if (!Context.getTargetInfo().isTLSSupported()) {
6557       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6558         // Postpone error emission until we've collected attributes required to
6559         // figure out whether it's a host or device variable and whether the
6560         // error should be ignored.
6561         EmitTLSUnsupportedError = true;
6562         // We still need to mark the variable as TLS so it shows up in AST with
6563         // proper storage class for other tools to use even if we're not going
6564         // to emit any code for it.
6565         NewVD->setTSCSpec(TSCS);
6566       } else
6567         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6568              diag::err_thread_unsupported);
6569     } else
6570       NewVD->setTSCSpec(TSCS);
6571   }
6572 
6573   // C99 6.7.4p3
6574   //   An inline definition of a function with external linkage shall
6575   //   not contain a definition of a modifiable object with static or
6576   //   thread storage duration...
6577   // We only apply this when the function is required to be defined
6578   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6579   // that a local variable with thread storage duration still has to
6580   // be marked 'static'.  Also note that it's possible to get these
6581   // semantics in C++ using __attribute__((gnu_inline)).
6582   if (SC == SC_Static && S->getFnParent() != nullptr &&
6583       !NewVD->getType().isConstQualified()) {
6584     FunctionDecl *CurFD = getCurFunctionDecl();
6585     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6586       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6587            diag::warn_static_local_in_extern_inline);
6588       MaybeSuggestAddingStaticToDecl(CurFD);
6589     }
6590   }
6591 
6592   if (D.getDeclSpec().isModulePrivateSpecified()) {
6593     if (IsVariableTemplateSpecialization)
6594       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6595           << (IsPartialSpecialization ? 1 : 0)
6596           << FixItHint::CreateRemoval(
6597                  D.getDeclSpec().getModulePrivateSpecLoc());
6598     else if (IsMemberSpecialization)
6599       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6600         << 2
6601         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6602     else if (NewVD->hasLocalStorage())
6603       Diag(NewVD->getLocation(), diag::err_module_private_local)
6604         << 0 << NewVD->getDeclName()
6605         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6606         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6607     else {
6608       NewVD->setModulePrivate();
6609       if (NewTemplate)
6610         NewTemplate->setModulePrivate();
6611       for (auto *B : Bindings)
6612         B->setModulePrivate();
6613     }
6614   }
6615 
6616   // Handle attributes prior to checking for duplicates in MergeVarDecl
6617   ProcessDeclAttributes(S, NewVD, D);
6618 
6619   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6620     if (EmitTLSUnsupportedError &&
6621         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6622          (getLangOpts().OpenMPIsDevice &&
6623           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6624       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6625            diag::err_thread_unsupported);
6626     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6627     // storage [duration]."
6628     if (SC == SC_None && S->getFnParent() != nullptr &&
6629         (NewVD->hasAttr<CUDASharedAttr>() ||
6630          NewVD->hasAttr<CUDAConstantAttr>())) {
6631       NewVD->setStorageClass(SC_Static);
6632     }
6633   }
6634 
6635   // Ensure that dllimport globals without explicit storage class are treated as
6636   // extern. The storage class is set above using parsed attributes. Now we can
6637   // check the VarDecl itself.
6638   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6639          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6640          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6641 
6642   // In auto-retain/release, infer strong retension for variables of
6643   // retainable type.
6644   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6645     NewVD->setInvalidDecl();
6646 
6647   // Handle GNU asm-label extension (encoded as an attribute).
6648   if (Expr *E = (Expr*)D.getAsmLabel()) {
6649     // The parser guarantees this is a string.
6650     StringLiteral *SE = cast<StringLiteral>(E);
6651     StringRef Label = SE->getString();
6652     if (S->getFnParent() != nullptr) {
6653       switch (SC) {
6654       case SC_None:
6655       case SC_Auto:
6656         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6657         break;
6658       case SC_Register:
6659         // Local Named register
6660         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6661             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6662           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6663         break;
6664       case SC_Static:
6665       case SC_Extern:
6666       case SC_PrivateExtern:
6667         break;
6668       }
6669     } else if (SC == SC_Register) {
6670       // Global Named register
6671       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6672         const auto &TI = Context.getTargetInfo();
6673         bool HasSizeMismatch;
6674 
6675         if (!TI.isValidGCCRegisterName(Label))
6676           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6677         else if (!TI.validateGlobalRegisterVariable(Label,
6678                                                     Context.getTypeSize(R),
6679                                                     HasSizeMismatch))
6680           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6681         else if (HasSizeMismatch)
6682           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6683       }
6684 
6685       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6686         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6687         NewVD->setInvalidDecl(true);
6688       }
6689     }
6690 
6691     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6692                                                 Context, Label, 0));
6693   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6694     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6695       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6696     if (I != ExtnameUndeclaredIdentifiers.end()) {
6697       if (isDeclExternC(NewVD)) {
6698         NewVD->addAttr(I->second);
6699         ExtnameUndeclaredIdentifiers.erase(I);
6700       } else
6701         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6702             << /*Variable*/1 << NewVD;
6703     }
6704   }
6705 
6706   // Find the shadowed declaration before filtering for scope.
6707   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6708                                 ? getShadowedDeclaration(NewVD, Previous)
6709                                 : nullptr;
6710 
6711   // Don't consider existing declarations that are in a different
6712   // scope and are out-of-semantic-context declarations (if the new
6713   // declaration has linkage).
6714   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6715                        D.getCXXScopeSpec().isNotEmpty() ||
6716                        IsMemberSpecialization ||
6717                        IsVariableTemplateSpecialization);
6718 
6719   // Check whether the previous declaration is in the same block scope. This
6720   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6721   if (getLangOpts().CPlusPlus &&
6722       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6723     NewVD->setPreviousDeclInSameBlockScope(
6724         Previous.isSingleResult() && !Previous.isShadowed() &&
6725         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6726 
6727   if (!getLangOpts().CPlusPlus) {
6728     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6729   } else {
6730     // If this is an explicit specialization of a static data member, check it.
6731     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6732         CheckMemberSpecialization(NewVD, Previous))
6733       NewVD->setInvalidDecl();
6734 
6735     // Merge the decl with the existing one if appropriate.
6736     if (!Previous.empty()) {
6737       if (Previous.isSingleResult() &&
6738           isa<FieldDecl>(Previous.getFoundDecl()) &&
6739           D.getCXXScopeSpec().isSet()) {
6740         // The user tried to define a non-static data member
6741         // out-of-line (C++ [dcl.meaning]p1).
6742         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6743           << D.getCXXScopeSpec().getRange();
6744         Previous.clear();
6745         NewVD->setInvalidDecl();
6746       }
6747     } else if (D.getCXXScopeSpec().isSet()) {
6748       // No previous declaration in the qualifying scope.
6749       Diag(D.getIdentifierLoc(), diag::err_no_member)
6750         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6751         << D.getCXXScopeSpec().getRange();
6752       NewVD->setInvalidDecl();
6753     }
6754 
6755     if (!IsVariableTemplateSpecialization)
6756       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6757 
6758     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6759     // an explicit specialization (14.8.3) or a partial specialization of a
6760     // concept definition.
6761     if (IsVariableTemplateSpecialization &&
6762         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6763         Previous.isSingleResult()) {
6764       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6765       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6766         if (VarTmpl->isConcept()) {
6767           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6768               << 1                            /*variable*/
6769               << (IsPartialSpecialization ? 2 /*partially specialized*/
6770                                           : 1 /*explicitly specialized*/);
6771           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6772           NewVD->setInvalidDecl();
6773         }
6774       }
6775     }
6776 
6777     if (NewTemplate) {
6778       VarTemplateDecl *PrevVarTemplate =
6779           NewVD->getPreviousDecl()
6780               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6781               : nullptr;
6782 
6783       // Check the template parameter list of this declaration, possibly
6784       // merging in the template parameter list from the previous variable
6785       // template declaration.
6786       if (CheckTemplateParameterList(
6787               TemplateParams,
6788               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6789                               : nullptr,
6790               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6791                DC->isDependentContext())
6792                   ? TPC_ClassTemplateMember
6793                   : TPC_VarTemplate))
6794         NewVD->setInvalidDecl();
6795 
6796       // If we are providing an explicit specialization of a static variable
6797       // template, make a note of that.
6798       if (PrevVarTemplate &&
6799           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6800         PrevVarTemplate->setMemberSpecialization();
6801     }
6802   }
6803 
6804   // Diagnose shadowed variables iff this isn't a redeclaration.
6805   if (ShadowedDecl && !D.isRedeclaration())
6806     CheckShadow(NewVD, ShadowedDecl, Previous);
6807 
6808   ProcessPragmaWeak(S, NewVD);
6809 
6810   // If this is the first declaration of an extern C variable, update
6811   // the map of such variables.
6812   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6813       isIncompleteDeclExternC(*this, NewVD))
6814     RegisterLocallyScopedExternCDecl(NewVD, S);
6815 
6816   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6817     Decl *ManglingContextDecl;
6818     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6819             NewVD->getDeclContext(), ManglingContextDecl)) {
6820       Context.setManglingNumber(
6821           NewVD, MCtx->getManglingNumber(
6822                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6823       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6824     }
6825   }
6826 
6827   // Special handling of variable named 'main'.
6828   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6829       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6830       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6831 
6832     // C++ [basic.start.main]p3
6833     // A program that declares a variable main at global scope is ill-formed.
6834     if (getLangOpts().CPlusPlus)
6835       Diag(D.getLocStart(), diag::err_main_global_variable);
6836 
6837     // In C, and external-linkage variable named main results in undefined
6838     // behavior.
6839     else if (NewVD->hasExternalFormalLinkage())
6840       Diag(D.getLocStart(), diag::warn_main_redefined);
6841   }
6842 
6843   if (D.isRedeclaration() && !Previous.empty()) {
6844     checkDLLAttributeRedeclaration(
6845         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6846         IsMemberSpecialization, D.isFunctionDefinition());
6847   }
6848 
6849   if (NewTemplate) {
6850     if (NewVD->isInvalidDecl())
6851       NewTemplate->setInvalidDecl();
6852     ActOnDocumentableDecl(NewTemplate);
6853     return NewTemplate;
6854   }
6855 
6856   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6857     CompleteMemberSpecialization(NewVD, Previous);
6858 
6859   return NewVD;
6860 }
6861 
6862 /// Enum describing the %select options in diag::warn_decl_shadow.
6863 enum ShadowedDeclKind {
6864   SDK_Local,
6865   SDK_Global,
6866   SDK_StaticMember,
6867   SDK_Field,
6868   SDK_Typedef,
6869   SDK_Using
6870 };
6871 
6872 /// Determine what kind of declaration we're shadowing.
6873 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6874                                                 const DeclContext *OldDC) {
6875   if (isa<TypeAliasDecl>(ShadowedDecl))
6876     return SDK_Using;
6877   else if (isa<TypedefDecl>(ShadowedDecl))
6878     return SDK_Typedef;
6879   else if (isa<RecordDecl>(OldDC))
6880     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6881 
6882   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6883 }
6884 
6885 /// Return the location of the capture if the given lambda captures the given
6886 /// variable \p VD, or an invalid source location otherwise.
6887 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6888                                          const VarDecl *VD) {
6889   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6890     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6891       return Capture.getLocation();
6892   }
6893   return SourceLocation();
6894 }
6895 
6896 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6897                                      const LookupResult &R) {
6898   // Only diagnose if we're shadowing an unambiguous field or variable.
6899   if (R.getResultKind() != LookupResult::Found)
6900     return false;
6901 
6902   // Return false if warning is ignored.
6903   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6904 }
6905 
6906 /// \brief Return the declaration shadowed by the given variable \p D, or null
6907 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6908 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6909                                         const LookupResult &R) {
6910   if (!shouldWarnIfShadowedDecl(Diags, R))
6911     return nullptr;
6912 
6913   // Don't diagnose declarations at file scope.
6914   if (D->hasGlobalStorage())
6915     return nullptr;
6916 
6917   NamedDecl *ShadowedDecl = R.getFoundDecl();
6918   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6919              ? ShadowedDecl
6920              : nullptr;
6921 }
6922 
6923 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6924 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6925 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6926                                         const LookupResult &R) {
6927   // Don't warn if typedef declaration is part of a class
6928   if (D->getDeclContext()->isRecord())
6929     return nullptr;
6930 
6931   if (!shouldWarnIfShadowedDecl(Diags, R))
6932     return nullptr;
6933 
6934   NamedDecl *ShadowedDecl = R.getFoundDecl();
6935   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6936 }
6937 
6938 /// \brief Diagnose variable or built-in function shadowing.  Implements
6939 /// -Wshadow.
6940 ///
6941 /// This method is called whenever a VarDecl is added to a "useful"
6942 /// scope.
6943 ///
6944 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6945 /// \param R the lookup of the name
6946 ///
6947 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6948                        const LookupResult &R) {
6949   DeclContext *NewDC = D->getDeclContext();
6950 
6951   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6952     // Fields are not shadowed by variables in C++ static methods.
6953     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6954       if (MD->isStatic())
6955         return;
6956 
6957     // Fields shadowed by constructor parameters are a special case. Usually
6958     // the constructor initializes the field with the parameter.
6959     if (isa<CXXConstructorDecl>(NewDC))
6960       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6961         // Remember that this was shadowed so we can either warn about its
6962         // modification or its existence depending on warning settings.
6963         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6964         return;
6965       }
6966   }
6967 
6968   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6969     if (shadowedVar->isExternC()) {
6970       // For shadowing external vars, make sure that we point to the global
6971       // declaration, not a locally scoped extern declaration.
6972       for (auto I : shadowedVar->redecls())
6973         if (I->isFileVarDecl()) {
6974           ShadowedDecl = I;
6975           break;
6976         }
6977     }
6978 
6979   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6980 
6981   unsigned WarningDiag = diag::warn_decl_shadow;
6982   SourceLocation CaptureLoc;
6983   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6984       isa<CXXMethodDecl>(NewDC)) {
6985     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6986       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6987         if (RD->getLambdaCaptureDefault() == LCD_None) {
6988           // Try to avoid warnings for lambdas with an explicit capture list.
6989           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6990           // Warn only when the lambda captures the shadowed decl explicitly.
6991           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6992           if (CaptureLoc.isInvalid())
6993             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6994         } else {
6995           // Remember that this was shadowed so we can avoid the warning if the
6996           // shadowed decl isn't captured and the warning settings allow it.
6997           cast<LambdaScopeInfo>(getCurFunction())
6998               ->ShadowingDecls.push_back(
6999                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7000           return;
7001         }
7002       }
7003     }
7004   }
7005 
7006   // Only warn about certain kinds of shadowing for class members.
7007   if (NewDC && NewDC->isRecord()) {
7008     // In particular, don't warn about shadowing non-class members.
7009     if (!OldDC->isRecord())
7010       return;
7011 
7012     // TODO: should we warn about static data members shadowing
7013     // static data members from base classes?
7014 
7015     // TODO: don't diagnose for inaccessible shadowed members.
7016     // This is hard to do perfectly because we might friend the
7017     // shadowing context, but that's just a false negative.
7018   }
7019 
7020 
7021   DeclarationName Name = R.getLookupName();
7022 
7023   // Emit warning and note.
7024   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7025     return;
7026   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7027   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7028   if (!CaptureLoc.isInvalid())
7029     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7030         << Name << /*explicitly*/ 1;
7031   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7032 }
7033 
7034 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7035 /// when these variables are captured by the lambda.
7036 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7037   for (const auto &Shadow : LSI->ShadowingDecls) {
7038     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7039     // Try to avoid the warning when the shadowed decl isn't captured.
7040     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7041     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7042     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7043                                        ? diag::warn_decl_shadow_uncaptured_local
7044                                        : diag::warn_decl_shadow)
7045         << Shadow.VD->getDeclName()
7046         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7047     if (!CaptureLoc.isInvalid())
7048       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7049           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7050     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7051   }
7052 }
7053 
7054 /// \brief Check -Wshadow without the advantage of a previous lookup.
7055 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7056   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7057     return;
7058 
7059   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7060                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7061   LookupName(R, S);
7062   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7063     CheckShadow(D, ShadowedDecl, R);
7064 }
7065 
7066 /// Check if 'E', which is an expression that is about to be modified, refers
7067 /// to a constructor parameter that shadows a field.
7068 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7069   // Quickly ignore expressions that can't be shadowing ctor parameters.
7070   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7071     return;
7072   E = E->IgnoreParenImpCasts();
7073   auto *DRE = dyn_cast<DeclRefExpr>(E);
7074   if (!DRE)
7075     return;
7076   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7077   auto I = ShadowingDecls.find(D);
7078   if (I == ShadowingDecls.end())
7079     return;
7080   const NamedDecl *ShadowedDecl = I->second;
7081   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7082   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7083   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7084   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7085 
7086   // Avoid issuing multiple warnings about the same decl.
7087   ShadowingDecls.erase(I);
7088 }
7089 
7090 /// Check for conflict between this global or extern "C" declaration and
7091 /// previous global or extern "C" declarations. This is only used in C++.
7092 template<typename T>
7093 static bool checkGlobalOrExternCConflict(
7094     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7095   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7096   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7097 
7098   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7099     // The common case: this global doesn't conflict with any extern "C"
7100     // declaration.
7101     return false;
7102   }
7103 
7104   if (Prev) {
7105     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7106       // Both the old and new declarations have C language linkage. This is a
7107       // redeclaration.
7108       Previous.clear();
7109       Previous.addDecl(Prev);
7110       return true;
7111     }
7112 
7113     // This is a global, non-extern "C" declaration, and there is a previous
7114     // non-global extern "C" declaration. Diagnose if this is a variable
7115     // declaration.
7116     if (!isa<VarDecl>(ND))
7117       return false;
7118   } else {
7119     // The declaration is extern "C". Check for any declaration in the
7120     // translation unit which might conflict.
7121     if (IsGlobal) {
7122       // We have already performed the lookup into the translation unit.
7123       IsGlobal = false;
7124       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7125            I != E; ++I) {
7126         if (isa<VarDecl>(*I)) {
7127           Prev = *I;
7128           break;
7129         }
7130       }
7131     } else {
7132       DeclContext::lookup_result R =
7133           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7134       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7135            I != E; ++I) {
7136         if (isa<VarDecl>(*I)) {
7137           Prev = *I;
7138           break;
7139         }
7140         // FIXME: If we have any other entity with this name in global scope,
7141         // the declaration is ill-formed, but that is a defect: it breaks the
7142         // 'stat' hack, for instance. Only variables can have mangled name
7143         // clashes with extern "C" declarations, so only they deserve a
7144         // diagnostic.
7145       }
7146     }
7147 
7148     if (!Prev)
7149       return false;
7150   }
7151 
7152   // Use the first declaration's location to ensure we point at something which
7153   // is lexically inside an extern "C" linkage-spec.
7154   assert(Prev && "should have found a previous declaration to diagnose");
7155   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7156     Prev = FD->getFirstDecl();
7157   else
7158     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7159 
7160   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7161     << IsGlobal << ND;
7162   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7163     << IsGlobal;
7164   return false;
7165 }
7166 
7167 /// Apply special rules for handling extern "C" declarations. Returns \c true
7168 /// if we have found that this is a redeclaration of some prior entity.
7169 ///
7170 /// Per C++ [dcl.link]p6:
7171 ///   Two declarations [for a function or variable] with C language linkage
7172 ///   with the same name that appear in different scopes refer to the same
7173 ///   [entity]. An entity with C language linkage shall not be declared with
7174 ///   the same name as an entity in global scope.
7175 template<typename T>
7176 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7177                                                   LookupResult &Previous) {
7178   if (!S.getLangOpts().CPlusPlus) {
7179     // In C, when declaring a global variable, look for a corresponding 'extern'
7180     // variable declared in function scope. We don't need this in C++, because
7181     // we find local extern decls in the surrounding file-scope DeclContext.
7182     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7183       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7184         Previous.clear();
7185         Previous.addDecl(Prev);
7186         return true;
7187       }
7188     }
7189     return false;
7190   }
7191 
7192   // A declaration in the translation unit can conflict with an extern "C"
7193   // declaration.
7194   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7195     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7196 
7197   // An extern "C" declaration can conflict with a declaration in the
7198   // translation unit or can be a redeclaration of an extern "C" declaration
7199   // in another scope.
7200   if (isIncompleteDeclExternC(S,ND))
7201     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7202 
7203   // Neither global nor extern "C": nothing to do.
7204   return false;
7205 }
7206 
7207 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7208   // If the decl is already known invalid, don't check it.
7209   if (NewVD->isInvalidDecl())
7210     return;
7211 
7212   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7213   QualType T = TInfo->getType();
7214 
7215   // Defer checking an 'auto' type until its initializer is attached.
7216   if (T->isUndeducedType())
7217     return;
7218 
7219   if (NewVD->hasAttrs())
7220     CheckAlignasUnderalignment(NewVD);
7221 
7222   if (T->isObjCObjectType()) {
7223     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7224       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7225     T = Context.getObjCObjectPointerType(T);
7226     NewVD->setType(T);
7227   }
7228 
7229   // Emit an error if an address space was applied to decl with local storage.
7230   // This includes arrays of objects with address space qualifiers, but not
7231   // automatic variables that point to other address spaces.
7232   // ISO/IEC TR 18037 S5.1.2
7233   if (!getLangOpts().OpenCL
7234       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7235     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7236     NewVD->setInvalidDecl();
7237     return;
7238   }
7239 
7240   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7241   // scope.
7242   if (getLangOpts().OpenCLVersion == 120 &&
7243       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7244       NewVD->isStaticLocal()) {
7245     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7246     NewVD->setInvalidDecl();
7247     return;
7248   }
7249 
7250   if (getLangOpts().OpenCL) {
7251     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7252     if (NewVD->hasAttr<BlocksAttr>()) {
7253       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7254       return;
7255     }
7256 
7257     if (T->isBlockPointerType()) {
7258       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7259       // can't use 'extern' storage class.
7260       if (!T.isConstQualified()) {
7261         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7262             << 0 /*const*/;
7263         NewVD->setInvalidDecl();
7264         return;
7265       }
7266       if (NewVD->hasExternalStorage()) {
7267         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7268         NewVD->setInvalidDecl();
7269         return;
7270       }
7271     }
7272     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7273     // __constant address space.
7274     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7275     // variables inside a function can also be declared in the global
7276     // address space.
7277     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7278         NewVD->hasExternalStorage()) {
7279       if (!T->isSamplerT() &&
7280           !(T.getAddressSpace() == LangAS::opencl_constant ||
7281             (T.getAddressSpace() == LangAS::opencl_global &&
7282              getLangOpts().OpenCLVersion == 200))) {
7283         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7284         if (getLangOpts().OpenCLVersion == 200)
7285           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7286               << Scope << "global or constant";
7287         else
7288           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7289               << Scope << "constant";
7290         NewVD->setInvalidDecl();
7291         return;
7292       }
7293     } else {
7294       if (T.getAddressSpace() == LangAS::opencl_global) {
7295         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7296             << 1 /*is any function*/ << "global";
7297         NewVD->setInvalidDecl();
7298         return;
7299       }
7300       if (T.getAddressSpace() == LangAS::opencl_constant ||
7301           T.getAddressSpace() == LangAS::opencl_local) {
7302         FunctionDecl *FD = getCurFunctionDecl();
7303         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7304         // in functions.
7305         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7306           if (T.getAddressSpace() == LangAS::opencl_constant)
7307             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7308                 << 0 /*non-kernel only*/ << "constant";
7309           else
7310             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7311                 << 0 /*non-kernel only*/ << "local";
7312           NewVD->setInvalidDecl();
7313           return;
7314         }
7315         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7316         // in the outermost scope of a kernel function.
7317         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7318           if (!getCurScope()->isFunctionScope()) {
7319             if (T.getAddressSpace() == LangAS::opencl_constant)
7320               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7321                   << "constant";
7322             else
7323               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7324                   << "local";
7325             NewVD->setInvalidDecl();
7326             return;
7327           }
7328         }
7329       } else if (T.getAddressSpace() != LangAS::Default) {
7330         // Do not allow other address spaces on automatic variable.
7331         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7332         NewVD->setInvalidDecl();
7333         return;
7334       }
7335     }
7336   }
7337 
7338   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7339       && !NewVD->hasAttr<BlocksAttr>()) {
7340     if (getLangOpts().getGC() != LangOptions::NonGC)
7341       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7342     else {
7343       assert(!getLangOpts().ObjCAutoRefCount);
7344       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7345     }
7346   }
7347 
7348   bool isVM = T->isVariablyModifiedType();
7349   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7350       NewVD->hasAttr<BlocksAttr>())
7351     getCurFunction()->setHasBranchProtectedScope();
7352 
7353   if ((isVM && NewVD->hasLinkage()) ||
7354       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7355     bool SizeIsNegative;
7356     llvm::APSInt Oversized;
7357     TypeSourceInfo *FixedTInfo =
7358       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7359                                                     SizeIsNegative, Oversized);
7360     if (!FixedTInfo && T->isVariableArrayType()) {
7361       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7362       // FIXME: This won't give the correct result for
7363       // int a[10][n];
7364       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7365 
7366       if (NewVD->isFileVarDecl())
7367         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7368         << SizeRange;
7369       else if (NewVD->isStaticLocal())
7370         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7371         << SizeRange;
7372       else
7373         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7374         << SizeRange;
7375       NewVD->setInvalidDecl();
7376       return;
7377     }
7378 
7379     if (!FixedTInfo) {
7380       if (NewVD->isFileVarDecl())
7381         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7382       else
7383         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7384       NewVD->setInvalidDecl();
7385       return;
7386     }
7387 
7388     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7389     NewVD->setType(FixedTInfo->getType());
7390     NewVD->setTypeSourceInfo(FixedTInfo);
7391   }
7392 
7393   if (T->isVoidType()) {
7394     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7395     //                    of objects and functions.
7396     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7397       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7398         << T;
7399       NewVD->setInvalidDecl();
7400       return;
7401     }
7402   }
7403 
7404   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7405     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7406     NewVD->setInvalidDecl();
7407     return;
7408   }
7409 
7410   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7411     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7412     NewVD->setInvalidDecl();
7413     return;
7414   }
7415 
7416   if (NewVD->isConstexpr() && !T->isDependentType() &&
7417       RequireLiteralType(NewVD->getLocation(), T,
7418                          diag::err_constexpr_var_non_literal)) {
7419     NewVD->setInvalidDecl();
7420     return;
7421   }
7422 }
7423 
7424 /// \brief Perform semantic checking on a newly-created variable
7425 /// declaration.
7426 ///
7427 /// This routine performs all of the type-checking required for a
7428 /// variable declaration once it has been built. It is used both to
7429 /// check variables after they have been parsed and their declarators
7430 /// have been translated into a declaration, and to check variables
7431 /// that have been instantiated from a template.
7432 ///
7433 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7434 ///
7435 /// Returns true if the variable declaration is a redeclaration.
7436 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7437   CheckVariableDeclarationType(NewVD);
7438 
7439   // If the decl is already known invalid, don't check it.
7440   if (NewVD->isInvalidDecl())
7441     return false;
7442 
7443   // If we did not find anything by this name, look for a non-visible
7444   // extern "C" declaration with the same name.
7445   if (Previous.empty() &&
7446       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7447     Previous.setShadowed();
7448 
7449   if (!Previous.empty()) {
7450     MergeVarDecl(NewVD, Previous);
7451     return true;
7452   }
7453   return false;
7454 }
7455 
7456 namespace {
7457 struct FindOverriddenMethod {
7458   Sema *S;
7459   CXXMethodDecl *Method;
7460 
7461   /// Member lookup function that determines whether a given C++
7462   /// method overrides a method in a base class, to be used with
7463   /// CXXRecordDecl::lookupInBases().
7464   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7465     RecordDecl *BaseRecord =
7466         Specifier->getType()->getAs<RecordType>()->getDecl();
7467 
7468     DeclarationName Name = Method->getDeclName();
7469 
7470     // FIXME: Do we care about other names here too?
7471     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7472       // We really want to find the base class destructor here.
7473       QualType T = S->Context.getTypeDeclType(BaseRecord);
7474       CanQualType CT = S->Context.getCanonicalType(T);
7475 
7476       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7477     }
7478 
7479     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7480          Path.Decls = Path.Decls.slice(1)) {
7481       NamedDecl *D = Path.Decls.front();
7482       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7483         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7484           return true;
7485       }
7486     }
7487 
7488     return false;
7489   }
7490 };
7491 
7492 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7493 } // end anonymous namespace
7494 
7495 /// \brief Report an error regarding overriding, along with any relevant
7496 /// overriden methods.
7497 ///
7498 /// \param DiagID the primary error to report.
7499 /// \param MD the overriding method.
7500 /// \param OEK which overrides to include as notes.
7501 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7502                             OverrideErrorKind OEK = OEK_All) {
7503   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7504   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7505                                       E = MD->end_overridden_methods();
7506        I != E; ++I) {
7507     // This check (& the OEK parameter) could be replaced by a predicate, but
7508     // without lambdas that would be overkill. This is still nicer than writing
7509     // out the diag loop 3 times.
7510     if ((OEK == OEK_All) ||
7511         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7512         (OEK == OEK_Deleted && (*I)->isDeleted()))
7513       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7514   }
7515 }
7516 
7517 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7518 /// and if so, check that it's a valid override and remember it.
7519 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7520   // Look for methods in base classes that this method might override.
7521   CXXBasePaths Paths;
7522   FindOverriddenMethod FOM;
7523   FOM.Method = MD;
7524   FOM.S = this;
7525   bool hasDeletedOverridenMethods = false;
7526   bool hasNonDeletedOverridenMethods = false;
7527   bool AddedAny = false;
7528   if (DC->lookupInBases(FOM, Paths)) {
7529     for (auto *I : Paths.found_decls()) {
7530       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7531         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7532         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7533             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7534             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7535             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7536           hasDeletedOverridenMethods |= OldMD->isDeleted();
7537           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7538           AddedAny = true;
7539         }
7540       }
7541     }
7542   }
7543 
7544   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7545     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7546   }
7547   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7548     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7549   }
7550 
7551   return AddedAny;
7552 }
7553 
7554 namespace {
7555   // Struct for holding all of the extra arguments needed by
7556   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7557   struct ActOnFDArgs {
7558     Scope *S;
7559     Declarator &D;
7560     MultiTemplateParamsArg TemplateParamLists;
7561     bool AddToScope;
7562   };
7563 } // end anonymous namespace
7564 
7565 namespace {
7566 
7567 // Callback to only accept typo corrections that have a non-zero edit distance.
7568 // Also only accept corrections that have the same parent decl.
7569 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7570  public:
7571   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7572                             CXXRecordDecl *Parent)
7573       : Context(Context), OriginalFD(TypoFD),
7574         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7575 
7576   bool ValidateCandidate(const TypoCorrection &candidate) override {
7577     if (candidate.getEditDistance() == 0)
7578       return false;
7579 
7580     SmallVector<unsigned, 1> MismatchedParams;
7581     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7582                                           CDeclEnd = candidate.end();
7583          CDecl != CDeclEnd; ++CDecl) {
7584       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7585 
7586       if (FD && !FD->hasBody() &&
7587           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7588         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7589           CXXRecordDecl *Parent = MD->getParent();
7590           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7591             return true;
7592         } else if (!ExpectedParent) {
7593           return true;
7594         }
7595       }
7596     }
7597 
7598     return false;
7599   }
7600 
7601  private:
7602   ASTContext &Context;
7603   FunctionDecl *OriginalFD;
7604   CXXRecordDecl *ExpectedParent;
7605 };
7606 
7607 } // end anonymous namespace
7608 
7609 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7610   TypoCorrectedFunctionDefinitions.insert(F);
7611 }
7612 
7613 /// \brief Generate diagnostics for an invalid function redeclaration.
7614 ///
7615 /// This routine handles generating the diagnostic messages for an invalid
7616 /// function redeclaration, including finding possible similar declarations
7617 /// or performing typo correction if there are no previous declarations with
7618 /// the same name.
7619 ///
7620 /// Returns a NamedDecl iff typo correction was performed and substituting in
7621 /// the new declaration name does not cause new errors.
7622 static NamedDecl *DiagnoseInvalidRedeclaration(
7623     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7624     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7625   DeclarationName Name = NewFD->getDeclName();
7626   DeclContext *NewDC = NewFD->getDeclContext();
7627   SmallVector<unsigned, 1> MismatchedParams;
7628   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7629   TypoCorrection Correction;
7630   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7631   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7632                                    : diag::err_member_decl_does_not_match;
7633   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7634                     IsLocalFriend ? Sema::LookupLocalFriendName
7635                                   : Sema::LookupOrdinaryName,
7636                     Sema::ForRedeclaration);
7637 
7638   NewFD->setInvalidDecl();
7639   if (IsLocalFriend)
7640     SemaRef.LookupName(Prev, S);
7641   else
7642     SemaRef.LookupQualifiedName(Prev, NewDC);
7643   assert(!Prev.isAmbiguous() &&
7644          "Cannot have an ambiguity in previous-declaration lookup");
7645   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7646   if (!Prev.empty()) {
7647     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7648          Func != FuncEnd; ++Func) {
7649       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7650       if (FD &&
7651           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7652         // Add 1 to the index so that 0 can mean the mismatch didn't
7653         // involve a parameter
7654         unsigned ParamNum =
7655             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7656         NearMatches.push_back(std::make_pair(FD, ParamNum));
7657       }
7658     }
7659   // If the qualified name lookup yielded nothing, try typo correction
7660   } else if ((Correction = SemaRef.CorrectTypo(
7661                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7662                   &ExtraArgs.D.getCXXScopeSpec(),
7663                   llvm::make_unique<DifferentNameValidatorCCC>(
7664                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7665                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7666     // Set up everything for the call to ActOnFunctionDeclarator
7667     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7668                               ExtraArgs.D.getIdentifierLoc());
7669     Previous.clear();
7670     Previous.setLookupName(Correction.getCorrection());
7671     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7672                                     CDeclEnd = Correction.end();
7673          CDecl != CDeclEnd; ++CDecl) {
7674       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7675       if (FD && !FD->hasBody() &&
7676           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7677         Previous.addDecl(FD);
7678       }
7679     }
7680     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7681 
7682     NamedDecl *Result;
7683     // Retry building the function declaration with the new previous
7684     // declarations, and with errors suppressed.
7685     {
7686       // Trap errors.
7687       Sema::SFINAETrap Trap(SemaRef);
7688 
7689       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7690       // pieces need to verify the typo-corrected C++ declaration and hopefully
7691       // eliminate the need for the parameter pack ExtraArgs.
7692       Result = SemaRef.ActOnFunctionDeclarator(
7693           ExtraArgs.S, ExtraArgs.D,
7694           Correction.getCorrectionDecl()->getDeclContext(),
7695           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7696           ExtraArgs.AddToScope);
7697 
7698       if (Trap.hasErrorOccurred())
7699         Result = nullptr;
7700     }
7701 
7702     if (Result) {
7703       // Determine which correction we picked.
7704       Decl *Canonical = Result->getCanonicalDecl();
7705       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7706            I != E; ++I)
7707         if ((*I)->getCanonicalDecl() == Canonical)
7708           Correction.setCorrectionDecl(*I);
7709 
7710       // Let Sema know about the correction.
7711       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7712       SemaRef.diagnoseTypo(
7713           Correction,
7714           SemaRef.PDiag(IsLocalFriend
7715                           ? diag::err_no_matching_local_friend_suggest
7716                           : diag::err_member_decl_does_not_match_suggest)
7717             << Name << NewDC << IsDefinition);
7718       return Result;
7719     }
7720 
7721     // Pretend the typo correction never occurred
7722     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7723                               ExtraArgs.D.getIdentifierLoc());
7724     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7725     Previous.clear();
7726     Previous.setLookupName(Name);
7727   }
7728 
7729   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7730       << Name << NewDC << IsDefinition << NewFD->getLocation();
7731 
7732   bool NewFDisConst = false;
7733   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7734     NewFDisConst = NewMD->isConst();
7735 
7736   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7737        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7738        NearMatch != NearMatchEnd; ++NearMatch) {
7739     FunctionDecl *FD = NearMatch->first;
7740     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7741     bool FDisConst = MD && MD->isConst();
7742     bool IsMember = MD || !IsLocalFriend;
7743 
7744     // FIXME: These notes are poorly worded for the local friend case.
7745     if (unsigned Idx = NearMatch->second) {
7746       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7747       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7748       if (Loc.isInvalid()) Loc = FD->getLocation();
7749       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7750                                  : diag::note_local_decl_close_param_match)
7751         << Idx << FDParam->getType()
7752         << NewFD->getParamDecl(Idx - 1)->getType();
7753     } else if (FDisConst != NewFDisConst) {
7754       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7755           << NewFDisConst << FD->getSourceRange().getEnd();
7756     } else
7757       SemaRef.Diag(FD->getLocation(),
7758                    IsMember ? diag::note_member_def_close_match
7759                             : diag::note_local_decl_close_match);
7760   }
7761   return nullptr;
7762 }
7763 
7764 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7765   switch (D.getDeclSpec().getStorageClassSpec()) {
7766   default: llvm_unreachable("Unknown storage class!");
7767   case DeclSpec::SCS_auto:
7768   case DeclSpec::SCS_register:
7769   case DeclSpec::SCS_mutable:
7770     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7771                  diag::err_typecheck_sclass_func);
7772     D.getMutableDeclSpec().ClearStorageClassSpecs();
7773     D.setInvalidType();
7774     break;
7775   case DeclSpec::SCS_unspecified: break;
7776   case DeclSpec::SCS_extern:
7777     if (D.getDeclSpec().isExternInLinkageSpec())
7778       return SC_None;
7779     return SC_Extern;
7780   case DeclSpec::SCS_static: {
7781     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7782       // C99 6.7.1p5:
7783       //   The declaration of an identifier for a function that has
7784       //   block scope shall have no explicit storage-class specifier
7785       //   other than extern
7786       // See also (C++ [dcl.stc]p4).
7787       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7788                    diag::err_static_block_func);
7789       break;
7790     } else
7791       return SC_Static;
7792   }
7793   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7794   }
7795 
7796   // No explicit storage class has already been returned
7797   return SC_None;
7798 }
7799 
7800 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7801                                            DeclContext *DC, QualType &R,
7802                                            TypeSourceInfo *TInfo,
7803                                            StorageClass SC,
7804                                            bool &IsVirtualOkay) {
7805   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7806   DeclarationName Name = NameInfo.getName();
7807 
7808   FunctionDecl *NewFD = nullptr;
7809   bool isInline = D.getDeclSpec().isInlineSpecified();
7810 
7811   if (!SemaRef.getLangOpts().CPlusPlus) {
7812     // Determine whether the function was written with a
7813     // prototype. This true when:
7814     //   - there is a prototype in the declarator, or
7815     //   - the type R of the function is some kind of typedef or other non-
7816     //     attributed reference to a type name (which eventually refers to a
7817     //     function type).
7818     bool HasPrototype =
7819       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7820       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7821 
7822     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7823                                  D.getLocStart(), NameInfo, R,
7824                                  TInfo, SC, isInline,
7825                                  HasPrototype, false);
7826     if (D.isInvalidType())
7827       NewFD->setInvalidDecl();
7828 
7829     return NewFD;
7830   }
7831 
7832   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7833   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7834 
7835   // Check that the return type is not an abstract class type.
7836   // For record types, this is done by the AbstractClassUsageDiagnoser once
7837   // the class has been completely parsed.
7838   if (!DC->isRecord() &&
7839       SemaRef.RequireNonAbstractType(
7840           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7841           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7842     D.setInvalidType();
7843 
7844   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7845     // This is a C++ constructor declaration.
7846     assert(DC->isRecord() &&
7847            "Constructors can only be declared in a member context");
7848 
7849     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7850     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7851                                       D.getLocStart(), NameInfo,
7852                                       R, TInfo, isExplicit, isInline,
7853                                       /*isImplicitlyDeclared=*/false,
7854                                       isConstexpr);
7855 
7856   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7857     // This is a C++ destructor declaration.
7858     if (DC->isRecord()) {
7859       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7860       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7861       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7862                                         SemaRef.Context, Record,
7863                                         D.getLocStart(),
7864                                         NameInfo, R, TInfo, isInline,
7865                                         /*isImplicitlyDeclared=*/false);
7866 
7867       // If the class is complete, then we now create the implicit exception
7868       // specification. If the class is incomplete or dependent, we can't do
7869       // it yet.
7870       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7871           Record->getDefinition() && !Record->isBeingDefined() &&
7872           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7873         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7874       }
7875 
7876       IsVirtualOkay = true;
7877       return NewDD;
7878 
7879     } else {
7880       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7881       D.setInvalidType();
7882 
7883       // Create a FunctionDecl to satisfy the function definition parsing
7884       // code path.
7885       return FunctionDecl::Create(SemaRef.Context, DC,
7886                                   D.getLocStart(),
7887                                   D.getIdentifierLoc(), Name, R, TInfo,
7888                                   SC, isInline,
7889                                   /*hasPrototype=*/true, isConstexpr);
7890     }
7891 
7892   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7893     if (!DC->isRecord()) {
7894       SemaRef.Diag(D.getIdentifierLoc(),
7895            diag::err_conv_function_not_member);
7896       return nullptr;
7897     }
7898 
7899     SemaRef.CheckConversionDeclarator(D, R, SC);
7900     IsVirtualOkay = true;
7901     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7902                                      D.getLocStart(), NameInfo,
7903                                      R, TInfo, isInline, isExplicit,
7904                                      isConstexpr, SourceLocation());
7905 
7906   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7907     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7908 
7909     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7910                                          isExplicit, NameInfo, R, TInfo,
7911                                          D.getLocEnd());
7912   } else if (DC->isRecord()) {
7913     // If the name of the function is the same as the name of the record,
7914     // then this must be an invalid constructor that has a return type.
7915     // (The parser checks for a return type and makes the declarator a
7916     // constructor if it has no return type).
7917     if (Name.getAsIdentifierInfo() &&
7918         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7919       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7920         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7921         << SourceRange(D.getIdentifierLoc());
7922       return nullptr;
7923     }
7924 
7925     // This is a C++ method declaration.
7926     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7927                                                cast<CXXRecordDecl>(DC),
7928                                                D.getLocStart(), NameInfo, R,
7929                                                TInfo, SC, isInline,
7930                                                isConstexpr, SourceLocation());
7931     IsVirtualOkay = !Ret->isStatic();
7932     return Ret;
7933   } else {
7934     bool isFriend =
7935         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7936     if (!isFriend && SemaRef.CurContext->isRecord())
7937       return nullptr;
7938 
7939     // Determine whether the function was written with a
7940     // prototype. This true when:
7941     //   - we're in C++ (where every function has a prototype),
7942     return FunctionDecl::Create(SemaRef.Context, DC,
7943                                 D.getLocStart(),
7944                                 NameInfo, R, TInfo, SC, isInline,
7945                                 true/*HasPrototype*/, isConstexpr);
7946   }
7947 }
7948 
7949 enum OpenCLParamType {
7950   ValidKernelParam,
7951   PtrPtrKernelParam,
7952   PtrKernelParam,
7953   InvalidAddrSpacePtrKernelParam,
7954   InvalidKernelParam,
7955   RecordKernelParam
7956 };
7957 
7958 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7959   if (PT->isPointerType()) {
7960     QualType PointeeType = PT->getPointeeType();
7961     if (PointeeType->isPointerType())
7962       return PtrPtrKernelParam;
7963     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7964         PointeeType.getAddressSpace() == 0)
7965       return InvalidAddrSpacePtrKernelParam;
7966     return PtrKernelParam;
7967   }
7968 
7969   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7970   // be used as builtin types.
7971 
7972   if (PT->isImageType())
7973     return PtrKernelParam;
7974 
7975   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7976     return InvalidKernelParam;
7977 
7978   // OpenCL extension spec v1.2 s9.5:
7979   // This extension adds support for half scalar and vector types as built-in
7980   // types that can be used for arithmetic operations, conversions etc.
7981   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7982     return InvalidKernelParam;
7983 
7984   if (PT->isRecordType())
7985     return RecordKernelParam;
7986 
7987   return ValidKernelParam;
7988 }
7989 
7990 static void checkIsValidOpenCLKernelParameter(
7991   Sema &S,
7992   Declarator &D,
7993   ParmVarDecl *Param,
7994   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7995   QualType PT = Param->getType();
7996 
7997   // Cache the valid types we encounter to avoid rechecking structs that are
7998   // used again
7999   if (ValidTypes.count(PT.getTypePtr()))
8000     return;
8001 
8002   switch (getOpenCLKernelParameterType(S, PT)) {
8003   case PtrPtrKernelParam:
8004     // OpenCL v1.2 s6.9.a:
8005     // A kernel function argument cannot be declared as a
8006     // pointer to a pointer type.
8007     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8008     D.setInvalidType();
8009     return;
8010 
8011   case InvalidAddrSpacePtrKernelParam:
8012     // OpenCL v1.0 s6.5:
8013     // __kernel function arguments declared to be a pointer of a type can point
8014     // to one of the following address spaces only : __global, __local or
8015     // __constant.
8016     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8017     D.setInvalidType();
8018     return;
8019 
8020     // OpenCL v1.2 s6.9.k:
8021     // Arguments to kernel functions in a program cannot be declared with the
8022     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8023     // uintptr_t or a struct and/or union that contain fields declared to be
8024     // one of these built-in scalar types.
8025 
8026   case InvalidKernelParam:
8027     // OpenCL v1.2 s6.8 n:
8028     // A kernel function argument cannot be declared
8029     // of event_t type.
8030     // Do not diagnose half type since it is diagnosed as invalid argument
8031     // type for any function elsewhere.
8032     if (!PT->isHalfType())
8033       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8034     D.setInvalidType();
8035     return;
8036 
8037   case PtrKernelParam:
8038   case ValidKernelParam:
8039     ValidTypes.insert(PT.getTypePtr());
8040     return;
8041 
8042   case RecordKernelParam:
8043     break;
8044   }
8045 
8046   // Track nested structs we will inspect
8047   SmallVector<const Decl *, 4> VisitStack;
8048 
8049   // Track where we are in the nested structs. Items will migrate from
8050   // VisitStack to HistoryStack as we do the DFS for bad field.
8051   SmallVector<const FieldDecl *, 4> HistoryStack;
8052   HistoryStack.push_back(nullptr);
8053 
8054   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8055   VisitStack.push_back(PD);
8056 
8057   assert(VisitStack.back() && "First decl null?");
8058 
8059   do {
8060     const Decl *Next = VisitStack.pop_back_val();
8061     if (!Next) {
8062       assert(!HistoryStack.empty());
8063       // Found a marker, we have gone up a level
8064       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8065         ValidTypes.insert(Hist->getType().getTypePtr());
8066 
8067       continue;
8068     }
8069 
8070     // Adds everything except the original parameter declaration (which is not a
8071     // field itself) to the history stack.
8072     const RecordDecl *RD;
8073     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8074       HistoryStack.push_back(Field);
8075       RD = Field->getType()->castAs<RecordType>()->getDecl();
8076     } else {
8077       RD = cast<RecordDecl>(Next);
8078     }
8079 
8080     // Add a null marker so we know when we've gone back up a level
8081     VisitStack.push_back(nullptr);
8082 
8083     for (const auto *FD : RD->fields()) {
8084       QualType QT = FD->getType();
8085 
8086       if (ValidTypes.count(QT.getTypePtr()))
8087         continue;
8088 
8089       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8090       if (ParamType == ValidKernelParam)
8091         continue;
8092 
8093       if (ParamType == RecordKernelParam) {
8094         VisitStack.push_back(FD);
8095         continue;
8096       }
8097 
8098       // OpenCL v1.2 s6.9.p:
8099       // Arguments to kernel functions that are declared to be a struct or union
8100       // do not allow OpenCL objects to be passed as elements of the struct or
8101       // union.
8102       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8103           ParamType == InvalidAddrSpacePtrKernelParam) {
8104         S.Diag(Param->getLocation(),
8105                diag::err_record_with_pointers_kernel_param)
8106           << PT->isUnionType()
8107           << PT;
8108       } else {
8109         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8110       }
8111 
8112       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8113         << PD->getDeclName();
8114 
8115       // We have an error, now let's go back up through history and show where
8116       // the offending field came from
8117       for (ArrayRef<const FieldDecl *>::const_iterator
8118                I = HistoryStack.begin() + 1,
8119                E = HistoryStack.end();
8120            I != E; ++I) {
8121         const FieldDecl *OuterField = *I;
8122         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8123           << OuterField->getType();
8124       }
8125 
8126       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8127         << QT->isPointerType()
8128         << QT;
8129       D.setInvalidType();
8130       return;
8131     }
8132   } while (!VisitStack.empty());
8133 }
8134 
8135 /// Find the DeclContext in which a tag is implicitly declared if we see an
8136 /// elaborated type specifier in the specified context, and lookup finds
8137 /// nothing.
8138 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8139   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8140     DC = DC->getParent();
8141   return DC;
8142 }
8143 
8144 /// Find the Scope in which a tag is implicitly declared if we see an
8145 /// elaborated type specifier in the specified context, and lookup finds
8146 /// nothing.
8147 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8148   while (S->isClassScope() ||
8149          (LangOpts.CPlusPlus &&
8150           S->isFunctionPrototypeScope()) ||
8151          ((S->getFlags() & Scope::DeclScope) == 0) ||
8152          (S->getEntity() && S->getEntity()->isTransparentContext()))
8153     S = S->getParent();
8154   return S;
8155 }
8156 
8157 NamedDecl*
8158 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8159                               TypeSourceInfo *TInfo, LookupResult &Previous,
8160                               MultiTemplateParamsArg TemplateParamLists,
8161                               bool &AddToScope) {
8162   QualType R = TInfo->getType();
8163 
8164   assert(R.getTypePtr()->isFunctionType());
8165 
8166   // TODO: consider using NameInfo for diagnostic.
8167   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8168   DeclarationName Name = NameInfo.getName();
8169   StorageClass SC = getFunctionStorageClass(*this, D);
8170 
8171   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8172     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8173          diag::err_invalid_thread)
8174       << DeclSpec::getSpecifierName(TSCS);
8175 
8176   if (D.isFirstDeclarationOfMember())
8177     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8178                            D.getIdentifierLoc());
8179 
8180   bool isFriend = false;
8181   FunctionTemplateDecl *FunctionTemplate = nullptr;
8182   bool isMemberSpecialization = false;
8183   bool isFunctionTemplateSpecialization = false;
8184 
8185   bool isDependentClassScopeExplicitSpecialization = false;
8186   bool HasExplicitTemplateArgs = false;
8187   TemplateArgumentListInfo TemplateArgs;
8188 
8189   bool isVirtualOkay = false;
8190 
8191   DeclContext *OriginalDC = DC;
8192   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8193 
8194   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8195                                               isVirtualOkay);
8196   if (!NewFD) return nullptr;
8197 
8198   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8199     NewFD->setTopLevelDeclInObjCContainer();
8200 
8201   // Set the lexical context. If this is a function-scope declaration, or has a
8202   // C++ scope specifier, or is the object of a friend declaration, the lexical
8203   // context will be different from the semantic context.
8204   NewFD->setLexicalDeclContext(CurContext);
8205 
8206   if (IsLocalExternDecl)
8207     NewFD->setLocalExternDecl();
8208 
8209   if (getLangOpts().CPlusPlus) {
8210     bool isInline = D.getDeclSpec().isInlineSpecified();
8211     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8212     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8213     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8214     bool isConcept = D.getDeclSpec().isConceptSpecified();
8215     isFriend = D.getDeclSpec().isFriendSpecified();
8216     if (isFriend && !isInline && D.isFunctionDefinition()) {
8217       // C++ [class.friend]p5
8218       //   A function can be defined in a friend declaration of a
8219       //   class . . . . Such a function is implicitly inline.
8220       NewFD->setImplicitlyInline();
8221     }
8222 
8223     // If this is a method defined in an __interface, and is not a constructor
8224     // or an overloaded operator, then set the pure flag (isVirtual will already
8225     // return true).
8226     if (const CXXRecordDecl *Parent =
8227           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8228       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8229         NewFD->setPure(true);
8230 
8231       // C++ [class.union]p2
8232       //   A union can have member functions, but not virtual functions.
8233       if (isVirtual && Parent->isUnion())
8234         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8235     }
8236 
8237     SetNestedNameSpecifier(NewFD, D);
8238     isMemberSpecialization = false;
8239     isFunctionTemplateSpecialization = false;
8240     if (D.isInvalidType())
8241       NewFD->setInvalidDecl();
8242 
8243     // Match up the template parameter lists with the scope specifier, then
8244     // determine whether we have a template or a template specialization.
8245     bool Invalid = false;
8246     if (TemplateParameterList *TemplateParams =
8247             MatchTemplateParametersToScopeSpecifier(
8248                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8249                 D.getCXXScopeSpec(),
8250                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8251                     ? D.getName().TemplateId
8252                     : nullptr,
8253                 TemplateParamLists, isFriend, isMemberSpecialization,
8254                 Invalid)) {
8255       if (TemplateParams->size() > 0) {
8256         // This is a function template
8257 
8258         // Check that we can declare a template here.
8259         if (CheckTemplateDeclScope(S, TemplateParams))
8260           NewFD->setInvalidDecl();
8261 
8262         // A destructor cannot be a template.
8263         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8264           Diag(NewFD->getLocation(), diag::err_destructor_template);
8265           NewFD->setInvalidDecl();
8266         }
8267 
8268         // If we're adding a template to a dependent context, we may need to
8269         // rebuilding some of the types used within the template parameter list,
8270         // now that we know what the current instantiation is.
8271         if (DC->isDependentContext()) {
8272           ContextRAII SavedContext(*this, DC);
8273           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8274             Invalid = true;
8275         }
8276 
8277         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8278                                                         NewFD->getLocation(),
8279                                                         Name, TemplateParams,
8280                                                         NewFD);
8281         FunctionTemplate->setLexicalDeclContext(CurContext);
8282         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8283 
8284         // For source fidelity, store the other template param lists.
8285         if (TemplateParamLists.size() > 1) {
8286           NewFD->setTemplateParameterListsInfo(Context,
8287                                                TemplateParamLists.drop_back(1));
8288         }
8289       } else {
8290         // This is a function template specialization.
8291         isFunctionTemplateSpecialization = true;
8292         // For source fidelity, store all the template param lists.
8293         if (TemplateParamLists.size() > 0)
8294           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8295 
8296         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8297         if (isFriend) {
8298           // We want to remove the "template<>", found here.
8299           SourceRange RemoveRange = TemplateParams->getSourceRange();
8300 
8301           // If we remove the template<> and the name is not a
8302           // template-id, we're actually silently creating a problem:
8303           // the friend declaration will refer to an untemplated decl,
8304           // and clearly the user wants a template specialization.  So
8305           // we need to insert '<>' after the name.
8306           SourceLocation InsertLoc;
8307           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8308             InsertLoc = D.getName().getSourceRange().getEnd();
8309             InsertLoc = getLocForEndOfToken(InsertLoc);
8310           }
8311 
8312           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8313             << Name << RemoveRange
8314             << FixItHint::CreateRemoval(RemoveRange)
8315             << FixItHint::CreateInsertion(InsertLoc, "<>");
8316         }
8317       }
8318     }
8319     else {
8320       // All template param lists were matched against the scope specifier:
8321       // this is NOT (an explicit specialization of) a template.
8322       if (TemplateParamLists.size() > 0)
8323         // For source fidelity, store all the template param lists.
8324         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8325     }
8326 
8327     if (Invalid) {
8328       NewFD->setInvalidDecl();
8329       if (FunctionTemplate)
8330         FunctionTemplate->setInvalidDecl();
8331     }
8332 
8333     // C++ [dcl.fct.spec]p5:
8334     //   The virtual specifier shall only be used in declarations of
8335     //   nonstatic class member functions that appear within a
8336     //   member-specification of a class declaration; see 10.3.
8337     //
8338     if (isVirtual && !NewFD->isInvalidDecl()) {
8339       if (!isVirtualOkay) {
8340         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8341              diag::err_virtual_non_function);
8342       } else if (!CurContext->isRecord()) {
8343         // 'virtual' was specified outside of the class.
8344         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8345              diag::err_virtual_out_of_class)
8346           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8347       } else if (NewFD->getDescribedFunctionTemplate()) {
8348         // C++ [temp.mem]p3:
8349         //  A member function template shall not be virtual.
8350         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8351              diag::err_virtual_member_function_template)
8352           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8353       } else {
8354         // Okay: Add virtual to the method.
8355         NewFD->setVirtualAsWritten(true);
8356       }
8357 
8358       if (getLangOpts().CPlusPlus14 &&
8359           NewFD->getReturnType()->isUndeducedType())
8360         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8361     }
8362 
8363     if (getLangOpts().CPlusPlus14 &&
8364         (NewFD->isDependentContext() ||
8365          (isFriend && CurContext->isDependentContext())) &&
8366         NewFD->getReturnType()->isUndeducedType()) {
8367       // If the function template is referenced directly (for instance, as a
8368       // member of the current instantiation), pretend it has a dependent type.
8369       // This is not really justified by the standard, but is the only sane
8370       // thing to do.
8371       // FIXME: For a friend function, we have not marked the function as being
8372       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8373       const FunctionProtoType *FPT =
8374           NewFD->getType()->castAs<FunctionProtoType>();
8375       QualType Result =
8376           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8377       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8378                                              FPT->getExtProtoInfo()));
8379     }
8380 
8381     // C++ [dcl.fct.spec]p3:
8382     //  The inline specifier shall not appear on a block scope function
8383     //  declaration.
8384     if (isInline && !NewFD->isInvalidDecl()) {
8385       if (CurContext->isFunctionOrMethod()) {
8386         // 'inline' is not allowed on block scope function declaration.
8387         Diag(D.getDeclSpec().getInlineSpecLoc(),
8388              diag::err_inline_declaration_block_scope) << Name
8389           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8390       }
8391     }
8392 
8393     // C++ [dcl.fct.spec]p6:
8394     //  The explicit specifier shall be used only in the declaration of a
8395     //  constructor or conversion function within its class definition;
8396     //  see 12.3.1 and 12.3.2.
8397     if (isExplicit && !NewFD->isInvalidDecl() &&
8398         !isa<CXXDeductionGuideDecl>(NewFD)) {
8399       if (!CurContext->isRecord()) {
8400         // 'explicit' was specified outside of the class.
8401         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8402              diag::err_explicit_out_of_class)
8403           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8404       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8405                  !isa<CXXConversionDecl>(NewFD)) {
8406         // 'explicit' was specified on a function that wasn't a constructor
8407         // or conversion function.
8408         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8409              diag::err_explicit_non_ctor_or_conv_function)
8410           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8411       }
8412     }
8413 
8414     if (isConstexpr) {
8415       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8416       // are implicitly inline.
8417       NewFD->setImplicitlyInline();
8418 
8419       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8420       // be either constructors or to return a literal type. Therefore,
8421       // destructors cannot be declared constexpr.
8422       if (isa<CXXDestructorDecl>(NewFD))
8423         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8424     }
8425 
8426     if (isConcept) {
8427       // This is a function concept.
8428       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8429         FTD->setConcept();
8430 
8431       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8432       // applied only to the definition of a function template [...]
8433       if (!D.isFunctionDefinition()) {
8434         Diag(D.getDeclSpec().getConceptSpecLoc(),
8435              diag::err_function_concept_not_defined);
8436         NewFD->setInvalidDecl();
8437       }
8438 
8439       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8440       // have no exception-specification and is treated as if it were specified
8441       // with noexcept(true) (15.4). [...]
8442       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8443         if (FPT->hasExceptionSpec()) {
8444           SourceRange Range;
8445           if (D.isFunctionDeclarator())
8446             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8447           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8448               << FixItHint::CreateRemoval(Range);
8449           NewFD->setInvalidDecl();
8450         } else {
8451           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8452         }
8453 
8454         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8455         // following restrictions:
8456         // - The declared return type shall have the type bool.
8457         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8458           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8459           NewFD->setInvalidDecl();
8460         }
8461 
8462         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8463         // following restrictions:
8464         // - The declaration's parameter list shall be equivalent to an empty
8465         //   parameter list.
8466         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8467           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8468       }
8469 
8470       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8471       // implicity defined to be a constexpr declaration (implicitly inline)
8472       NewFD->setImplicitlyInline();
8473 
8474       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8475       // be declared with the thread_local, inline, friend, or constexpr
8476       // specifiers, [...]
8477       if (isInline) {
8478         Diag(D.getDeclSpec().getInlineSpecLoc(),
8479              diag::err_concept_decl_invalid_specifiers)
8480             << 1 << 1;
8481         NewFD->setInvalidDecl(true);
8482       }
8483 
8484       if (isFriend) {
8485         Diag(D.getDeclSpec().getFriendSpecLoc(),
8486              diag::err_concept_decl_invalid_specifiers)
8487             << 1 << 2;
8488         NewFD->setInvalidDecl(true);
8489       }
8490 
8491       if (isConstexpr) {
8492         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8493              diag::err_concept_decl_invalid_specifiers)
8494             << 1 << 3;
8495         NewFD->setInvalidDecl(true);
8496       }
8497 
8498       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8499       // applied only to the definition of a function template or variable
8500       // template, declared in namespace scope.
8501       if (isFunctionTemplateSpecialization) {
8502         Diag(D.getDeclSpec().getConceptSpecLoc(),
8503              diag::err_concept_specified_specialization) << 1;
8504         NewFD->setInvalidDecl(true);
8505         return NewFD;
8506       }
8507     }
8508 
8509     // If __module_private__ was specified, mark the function accordingly.
8510     if (D.getDeclSpec().isModulePrivateSpecified()) {
8511       if (isFunctionTemplateSpecialization) {
8512         SourceLocation ModulePrivateLoc
8513           = D.getDeclSpec().getModulePrivateSpecLoc();
8514         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8515           << 0
8516           << FixItHint::CreateRemoval(ModulePrivateLoc);
8517       } else {
8518         NewFD->setModulePrivate();
8519         if (FunctionTemplate)
8520           FunctionTemplate->setModulePrivate();
8521       }
8522     }
8523 
8524     if (isFriend) {
8525       if (FunctionTemplate) {
8526         FunctionTemplate->setObjectOfFriendDecl();
8527         FunctionTemplate->setAccess(AS_public);
8528       }
8529       NewFD->setObjectOfFriendDecl();
8530       NewFD->setAccess(AS_public);
8531     }
8532 
8533     // If a function is defined as defaulted or deleted, mark it as such now.
8534     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8535     // definition kind to FDK_Definition.
8536     switch (D.getFunctionDefinitionKind()) {
8537       case FDK_Declaration:
8538       case FDK_Definition:
8539         break;
8540 
8541       case FDK_Defaulted:
8542         NewFD->setDefaulted();
8543         break;
8544 
8545       case FDK_Deleted:
8546         NewFD->setDeletedAsWritten();
8547         break;
8548     }
8549 
8550     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8551         D.isFunctionDefinition()) {
8552       // C++ [class.mfct]p2:
8553       //   A member function may be defined (8.4) in its class definition, in
8554       //   which case it is an inline member function (7.1.2)
8555       NewFD->setImplicitlyInline();
8556     }
8557 
8558     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8559         !CurContext->isRecord()) {
8560       // C++ [class.static]p1:
8561       //   A data or function member of a class may be declared static
8562       //   in a class definition, in which case it is a static member of
8563       //   the class.
8564 
8565       // Complain about the 'static' specifier if it's on an out-of-line
8566       // member function definition.
8567       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8568            diag::err_static_out_of_line)
8569         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8570     }
8571 
8572     // C++11 [except.spec]p15:
8573     //   A deallocation function with no exception-specification is treated
8574     //   as if it were specified with noexcept(true).
8575     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8576     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8577          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8578         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8579       NewFD->setType(Context.getFunctionType(
8580           FPT->getReturnType(), FPT->getParamTypes(),
8581           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8582   }
8583 
8584   // Filter out previous declarations that don't match the scope.
8585   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8586                        D.getCXXScopeSpec().isNotEmpty() ||
8587                        isMemberSpecialization ||
8588                        isFunctionTemplateSpecialization);
8589 
8590   // Handle GNU asm-label extension (encoded as an attribute).
8591   if (Expr *E = (Expr*) D.getAsmLabel()) {
8592     // The parser guarantees this is a string.
8593     StringLiteral *SE = cast<StringLiteral>(E);
8594     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8595                                                 SE->getString(), 0));
8596   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8597     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8598       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8599     if (I != ExtnameUndeclaredIdentifiers.end()) {
8600       if (isDeclExternC(NewFD)) {
8601         NewFD->addAttr(I->second);
8602         ExtnameUndeclaredIdentifiers.erase(I);
8603       } else
8604         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8605             << /*Variable*/0 << NewFD;
8606     }
8607   }
8608 
8609   // Copy the parameter declarations from the declarator D to the function
8610   // declaration NewFD, if they are available.  First scavenge them into Params.
8611   SmallVector<ParmVarDecl*, 16> Params;
8612   unsigned FTIIdx;
8613   if (D.isFunctionDeclarator(FTIIdx)) {
8614     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8615 
8616     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8617     // function that takes no arguments, not a function that takes a
8618     // single void argument.
8619     // We let through "const void" here because Sema::GetTypeForDeclarator
8620     // already checks for that case.
8621     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8622       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8623         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8624         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8625         Param->setDeclContext(NewFD);
8626         Params.push_back(Param);
8627 
8628         if (Param->isInvalidDecl())
8629           NewFD->setInvalidDecl();
8630       }
8631     }
8632 
8633     if (!getLangOpts().CPlusPlus) {
8634       // In C, find all the tag declarations from the prototype and move them
8635       // into the function DeclContext. Remove them from the surrounding tag
8636       // injection context of the function, which is typically but not always
8637       // the TU.
8638       DeclContext *PrototypeTagContext =
8639           getTagInjectionContext(NewFD->getLexicalDeclContext());
8640       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8641         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8642 
8643         // We don't want to reparent enumerators. Look at their parent enum
8644         // instead.
8645         if (!TD) {
8646           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8647             TD = cast<EnumDecl>(ECD->getDeclContext());
8648         }
8649         if (!TD)
8650           continue;
8651         DeclContext *TagDC = TD->getLexicalDeclContext();
8652         if (!TagDC->containsDecl(TD))
8653           continue;
8654         TagDC->removeDecl(TD);
8655         TD->setDeclContext(NewFD);
8656         NewFD->addDecl(TD);
8657 
8658         // Preserve the lexical DeclContext if it is not the surrounding tag
8659         // injection context of the FD. In this example, the semantic context of
8660         // E will be f and the lexical context will be S, while both the
8661         // semantic and lexical contexts of S will be f:
8662         //   void f(struct S { enum E { a } f; } s);
8663         if (TagDC != PrototypeTagContext)
8664           TD->setLexicalDeclContext(TagDC);
8665       }
8666     }
8667   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8668     // When we're declaring a function with a typedef, typeof, etc as in the
8669     // following example, we'll need to synthesize (unnamed)
8670     // parameters for use in the declaration.
8671     //
8672     // @code
8673     // typedef void fn(int);
8674     // fn f;
8675     // @endcode
8676 
8677     // Synthesize a parameter for each argument type.
8678     for (const auto &AI : FT->param_types()) {
8679       ParmVarDecl *Param =
8680           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8681       Param->setScopeInfo(0, Params.size());
8682       Params.push_back(Param);
8683     }
8684   } else {
8685     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8686            "Should not need args for typedef of non-prototype fn");
8687   }
8688 
8689   // Finally, we know we have the right number of parameters, install them.
8690   NewFD->setParams(Params);
8691 
8692   if (D.getDeclSpec().isNoreturnSpecified())
8693     NewFD->addAttr(
8694         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8695                                        Context, 0));
8696 
8697   // Functions returning a variably modified type violate C99 6.7.5.2p2
8698   // because all functions have linkage.
8699   if (!NewFD->isInvalidDecl() &&
8700       NewFD->getReturnType()->isVariablyModifiedType()) {
8701     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8702     NewFD->setInvalidDecl();
8703   }
8704 
8705   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8706   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8707       !NewFD->hasAttr<SectionAttr>()) {
8708     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8709                                                  PragmaClangTextSection.SectionName,
8710                                                  PragmaClangTextSection.PragmaLocation));
8711   }
8712 
8713   // Apply an implicit SectionAttr if #pragma code_seg is active.
8714   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8715       !NewFD->hasAttr<SectionAttr>()) {
8716     NewFD->addAttr(
8717         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8718                                     CodeSegStack.CurrentValue->getString(),
8719                                     CodeSegStack.CurrentPragmaLocation));
8720     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8721                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8722                          ASTContext::PSF_Read,
8723                      NewFD))
8724       NewFD->dropAttr<SectionAttr>();
8725   }
8726 
8727   // Handle attributes.
8728   ProcessDeclAttributes(S, NewFD, D);
8729 
8730   if (getLangOpts().OpenCL) {
8731     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8732     // type declaration will generate a compilation error.
8733     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8734     if (AddressSpace == LangAS::opencl_local ||
8735         AddressSpace == LangAS::opencl_global ||
8736         AddressSpace == LangAS::opencl_constant) {
8737       Diag(NewFD->getLocation(),
8738            diag::err_opencl_return_value_with_address_space);
8739       NewFD->setInvalidDecl();
8740     }
8741   }
8742 
8743   if (!getLangOpts().CPlusPlus) {
8744     // Perform semantic checking on the function declaration.
8745     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8746       CheckMain(NewFD, D.getDeclSpec());
8747 
8748     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8749       CheckMSVCRTEntryPoint(NewFD);
8750 
8751     if (!NewFD->isInvalidDecl())
8752       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8753                                                   isMemberSpecialization));
8754     else if (!Previous.empty())
8755       // Recover gracefully from an invalid redeclaration.
8756       D.setRedeclaration(true);
8757     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8758             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8759            "previous declaration set still overloaded");
8760 
8761     // Diagnose no-prototype function declarations with calling conventions that
8762     // don't support variadic calls. Only do this in C and do it after merging
8763     // possibly prototyped redeclarations.
8764     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8765     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8766       CallingConv CC = FT->getExtInfo().getCC();
8767       if (!supportsVariadicCall(CC)) {
8768         // Windows system headers sometimes accidentally use stdcall without
8769         // (void) parameters, so we relax this to a warning.
8770         int DiagID =
8771             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8772         Diag(NewFD->getLocation(), DiagID)
8773             << FunctionType::getNameForCallConv(CC);
8774       }
8775     }
8776   } else {
8777     // C++11 [replacement.functions]p3:
8778     //  The program's definitions shall not be specified as inline.
8779     //
8780     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8781     //
8782     // Suppress the diagnostic if the function is __attribute__((used)), since
8783     // that forces an external definition to be emitted.
8784     if (D.getDeclSpec().isInlineSpecified() &&
8785         NewFD->isReplaceableGlobalAllocationFunction() &&
8786         !NewFD->hasAttr<UsedAttr>())
8787       Diag(D.getDeclSpec().getInlineSpecLoc(),
8788            diag::ext_operator_new_delete_declared_inline)
8789         << NewFD->getDeclName();
8790 
8791     // If the declarator is a template-id, translate the parser's template
8792     // argument list into our AST format.
8793     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8794       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8795       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8796       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8797       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8798                                          TemplateId->NumArgs);
8799       translateTemplateArguments(TemplateArgsPtr,
8800                                  TemplateArgs);
8801 
8802       HasExplicitTemplateArgs = true;
8803 
8804       if (NewFD->isInvalidDecl()) {
8805         HasExplicitTemplateArgs = false;
8806       } else if (FunctionTemplate) {
8807         // Function template with explicit template arguments.
8808         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8809           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8810 
8811         HasExplicitTemplateArgs = false;
8812       } else {
8813         assert((isFunctionTemplateSpecialization ||
8814                 D.getDeclSpec().isFriendSpecified()) &&
8815                "should have a 'template<>' for this decl");
8816         // "friend void foo<>(int);" is an implicit specialization decl.
8817         isFunctionTemplateSpecialization = true;
8818       }
8819     } else if (isFriend && isFunctionTemplateSpecialization) {
8820       // This combination is only possible in a recovery case;  the user
8821       // wrote something like:
8822       //   template <> friend void foo(int);
8823       // which we're recovering from as if the user had written:
8824       //   friend void foo<>(int);
8825       // Go ahead and fake up a template id.
8826       HasExplicitTemplateArgs = true;
8827       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8828       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8829     }
8830 
8831     // We do not add HD attributes to specializations here because
8832     // they may have different constexpr-ness compared to their
8833     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8834     // may end up with different effective targets. Instead, a
8835     // specialization inherits its target attributes from its template
8836     // in the CheckFunctionTemplateSpecialization() call below.
8837     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8838       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8839 
8840     // If it's a friend (and only if it's a friend), it's possible
8841     // that either the specialized function type or the specialized
8842     // template is dependent, and therefore matching will fail.  In
8843     // this case, don't check the specialization yet.
8844     bool InstantiationDependent = false;
8845     if (isFunctionTemplateSpecialization && isFriend &&
8846         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8847          TemplateSpecializationType::anyDependentTemplateArguments(
8848             TemplateArgs,
8849             InstantiationDependent))) {
8850       assert(HasExplicitTemplateArgs &&
8851              "friend function specialization without template args");
8852       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8853                                                        Previous))
8854         NewFD->setInvalidDecl();
8855     } else if (isFunctionTemplateSpecialization) {
8856       if (CurContext->isDependentContext() && CurContext->isRecord()
8857           && !isFriend) {
8858         isDependentClassScopeExplicitSpecialization = true;
8859         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8860           diag::ext_function_specialization_in_class :
8861           diag::err_function_specialization_in_class)
8862           << NewFD->getDeclName();
8863       } else if (CheckFunctionTemplateSpecialization(NewFD,
8864                                   (HasExplicitTemplateArgs ? &TemplateArgs
8865                                                            : nullptr),
8866                                                      Previous))
8867         NewFD->setInvalidDecl();
8868 
8869       // C++ [dcl.stc]p1:
8870       //   A storage-class-specifier shall not be specified in an explicit
8871       //   specialization (14.7.3)
8872       FunctionTemplateSpecializationInfo *Info =
8873           NewFD->getTemplateSpecializationInfo();
8874       if (Info && SC != SC_None) {
8875         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8876           Diag(NewFD->getLocation(),
8877                diag::err_explicit_specialization_inconsistent_storage_class)
8878             << SC
8879             << FixItHint::CreateRemoval(
8880                                       D.getDeclSpec().getStorageClassSpecLoc());
8881 
8882         else
8883           Diag(NewFD->getLocation(),
8884                diag::ext_explicit_specialization_storage_class)
8885             << FixItHint::CreateRemoval(
8886                                       D.getDeclSpec().getStorageClassSpecLoc());
8887       }
8888     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8889       if (CheckMemberSpecialization(NewFD, Previous))
8890           NewFD->setInvalidDecl();
8891     }
8892 
8893     // Perform semantic checking on the function declaration.
8894     if (!isDependentClassScopeExplicitSpecialization) {
8895       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8896         CheckMain(NewFD, D.getDeclSpec());
8897 
8898       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8899         CheckMSVCRTEntryPoint(NewFD);
8900 
8901       if (!NewFD->isInvalidDecl())
8902         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8903                                                     isMemberSpecialization));
8904       else if (!Previous.empty())
8905         // Recover gracefully from an invalid redeclaration.
8906         D.setRedeclaration(true);
8907     }
8908 
8909     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8910             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8911            "previous declaration set still overloaded");
8912 
8913     NamedDecl *PrincipalDecl = (FunctionTemplate
8914                                 ? cast<NamedDecl>(FunctionTemplate)
8915                                 : NewFD);
8916 
8917     if (isFriend && NewFD->getPreviousDecl()) {
8918       AccessSpecifier Access = AS_public;
8919       if (!NewFD->isInvalidDecl())
8920         Access = NewFD->getPreviousDecl()->getAccess();
8921 
8922       NewFD->setAccess(Access);
8923       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8924     }
8925 
8926     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8927         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8928       PrincipalDecl->setNonMemberOperator();
8929 
8930     // If we have a function template, check the template parameter
8931     // list. This will check and merge default template arguments.
8932     if (FunctionTemplate) {
8933       FunctionTemplateDecl *PrevTemplate =
8934                                      FunctionTemplate->getPreviousDecl();
8935       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8936                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8937                                     : nullptr,
8938                             D.getDeclSpec().isFriendSpecified()
8939                               ? (D.isFunctionDefinition()
8940                                    ? TPC_FriendFunctionTemplateDefinition
8941                                    : TPC_FriendFunctionTemplate)
8942                               : (D.getCXXScopeSpec().isSet() &&
8943                                  DC && DC->isRecord() &&
8944                                  DC->isDependentContext())
8945                                   ? TPC_ClassTemplateMember
8946                                   : TPC_FunctionTemplate);
8947     }
8948 
8949     if (NewFD->isInvalidDecl()) {
8950       // Ignore all the rest of this.
8951     } else if (!D.isRedeclaration()) {
8952       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8953                                        AddToScope };
8954       // Fake up an access specifier if it's supposed to be a class member.
8955       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8956         NewFD->setAccess(AS_public);
8957 
8958       // Qualified decls generally require a previous declaration.
8959       if (D.getCXXScopeSpec().isSet()) {
8960         // ...with the major exception of templated-scope or
8961         // dependent-scope friend declarations.
8962 
8963         // TODO: we currently also suppress this check in dependent
8964         // contexts because (1) the parameter depth will be off when
8965         // matching friend templates and (2) we might actually be
8966         // selecting a friend based on a dependent factor.  But there
8967         // are situations where these conditions don't apply and we
8968         // can actually do this check immediately.
8969         if (isFriend &&
8970             (TemplateParamLists.size() ||
8971              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8972              CurContext->isDependentContext())) {
8973           // ignore these
8974         } else {
8975           // The user tried to provide an out-of-line definition for a
8976           // function that is a member of a class or namespace, but there
8977           // was no such member function declared (C++ [class.mfct]p2,
8978           // C++ [namespace.memdef]p2). For example:
8979           //
8980           // class X {
8981           //   void f() const;
8982           // };
8983           //
8984           // void X::f() { } // ill-formed
8985           //
8986           // Complain about this problem, and attempt to suggest close
8987           // matches (e.g., those that differ only in cv-qualifiers and
8988           // whether the parameter types are references).
8989 
8990           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8991                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8992             AddToScope = ExtraArgs.AddToScope;
8993             return Result;
8994           }
8995         }
8996 
8997         // Unqualified local friend declarations are required to resolve
8998         // to something.
8999       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9000         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9001                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9002           AddToScope = ExtraArgs.AddToScope;
9003           return Result;
9004         }
9005       }
9006     } else if (!D.isFunctionDefinition() &&
9007                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9008                !isFriend && !isFunctionTemplateSpecialization &&
9009                !isMemberSpecialization) {
9010       // An out-of-line member function declaration must also be a
9011       // definition (C++ [class.mfct]p2).
9012       // Note that this is not the case for explicit specializations of
9013       // function templates or member functions of class templates, per
9014       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9015       // extension for compatibility with old SWIG code which likes to
9016       // generate them.
9017       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9018         << D.getCXXScopeSpec().getRange();
9019     }
9020   }
9021 
9022   ProcessPragmaWeak(S, NewFD);
9023   checkAttributesAfterMerging(*this, *NewFD);
9024 
9025   AddKnownFunctionAttributes(NewFD);
9026 
9027   if (NewFD->hasAttr<OverloadableAttr>() &&
9028       !NewFD->getType()->getAs<FunctionProtoType>()) {
9029     Diag(NewFD->getLocation(),
9030          diag::err_attribute_overloadable_no_prototype)
9031       << NewFD;
9032 
9033     // Turn this into a variadic function with no parameters.
9034     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9035     FunctionProtoType::ExtProtoInfo EPI(
9036         Context.getDefaultCallingConvention(true, false));
9037     EPI.Variadic = true;
9038     EPI.ExtInfo = FT->getExtInfo();
9039 
9040     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9041     NewFD->setType(R);
9042   }
9043 
9044   // If there's a #pragma GCC visibility in scope, and this isn't a class
9045   // member, set the visibility of this function.
9046   if (!DC->isRecord() && NewFD->isExternallyVisible())
9047     AddPushedVisibilityAttribute(NewFD);
9048 
9049   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9050   // marking the function.
9051   AddCFAuditedAttribute(NewFD);
9052 
9053   // If this is a function definition, check if we have to apply optnone due to
9054   // a pragma.
9055   if(D.isFunctionDefinition())
9056     AddRangeBasedOptnone(NewFD);
9057 
9058   // If this is the first declaration of an extern C variable, update
9059   // the map of such variables.
9060   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9061       isIncompleteDeclExternC(*this, NewFD))
9062     RegisterLocallyScopedExternCDecl(NewFD, S);
9063 
9064   // Set this FunctionDecl's range up to the right paren.
9065   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9066 
9067   if (D.isRedeclaration() && !Previous.empty()) {
9068     checkDLLAttributeRedeclaration(
9069         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9070         isMemberSpecialization || isFunctionTemplateSpecialization,
9071         D.isFunctionDefinition());
9072   }
9073 
9074   if (getLangOpts().CUDA) {
9075     IdentifierInfo *II = NewFD->getIdentifier();
9076     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9077         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9078       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9079         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9080 
9081       Context.setcudaConfigureCallDecl(NewFD);
9082     }
9083 
9084     // Variadic functions, other than a *declaration* of printf, are not allowed
9085     // in device-side CUDA code, unless someone passed
9086     // -fcuda-allow-variadic-functions.
9087     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9088         (NewFD->hasAttr<CUDADeviceAttr>() ||
9089          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9090         !(II && II->isStr("printf") && NewFD->isExternC() &&
9091           !D.isFunctionDefinition())) {
9092       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9093     }
9094   }
9095 
9096   MarkUnusedFileScopedDecl(NewFD);
9097 
9098   if (getLangOpts().CPlusPlus) {
9099     if (FunctionTemplate) {
9100       if (NewFD->isInvalidDecl())
9101         FunctionTemplate->setInvalidDecl();
9102       return FunctionTemplate;
9103     }
9104 
9105     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9106       CompleteMemberSpecialization(NewFD, Previous);
9107   }
9108 
9109   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9110     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9111     if ((getLangOpts().OpenCLVersion >= 120)
9112         && (SC == SC_Static)) {
9113       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9114       D.setInvalidType();
9115     }
9116 
9117     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9118     if (!NewFD->getReturnType()->isVoidType()) {
9119       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9120       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9121           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9122                                 : FixItHint());
9123       D.setInvalidType();
9124     }
9125 
9126     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9127     for (auto Param : NewFD->parameters())
9128       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9129   }
9130   for (const ParmVarDecl *Param : NewFD->parameters()) {
9131     QualType PT = Param->getType();
9132 
9133     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9134     // types.
9135     if (getLangOpts().OpenCLVersion >= 200) {
9136       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9137         QualType ElemTy = PipeTy->getElementType();
9138           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9139             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9140             D.setInvalidType();
9141           }
9142       }
9143     }
9144   }
9145 
9146   // Here we have an function template explicit specialization at class scope.
9147   // The actually specialization will be postponed to template instatiation
9148   // time via the ClassScopeFunctionSpecializationDecl node.
9149   if (isDependentClassScopeExplicitSpecialization) {
9150     ClassScopeFunctionSpecializationDecl *NewSpec =
9151                          ClassScopeFunctionSpecializationDecl::Create(
9152                                 Context, CurContext, SourceLocation(),
9153                                 cast<CXXMethodDecl>(NewFD),
9154                                 HasExplicitTemplateArgs, TemplateArgs);
9155     CurContext->addDecl(NewSpec);
9156     AddToScope = false;
9157   }
9158 
9159   return NewFD;
9160 }
9161 
9162 /// \brief Checks if the new declaration declared in dependent context must be
9163 /// put in the same redeclaration chain as the specified declaration.
9164 ///
9165 /// \param D Declaration that is checked.
9166 /// \param PrevDecl Previous declaration found with proper lookup method for the
9167 ///                 same declaration name.
9168 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9169 ///          belongs to.
9170 ///
9171 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9172   // Any declarations should be put into redeclaration chains except for
9173   // friend declaration in a dependent context that names a function in
9174   // namespace scope.
9175   //
9176   // This allows to compile code like:
9177   //
9178   //       void func();
9179   //       template<typename T> class C1 { friend void func() { } };
9180   //       template<typename T> class C2 { friend void func() { } };
9181   //
9182   // This code snippet is a valid code unless both templates are instantiated.
9183   return !(D->getLexicalDeclContext()->isDependentContext() &&
9184            D->getDeclContext()->isFileContext() &&
9185            D->getFriendObjectKind() != Decl::FOK_None);
9186 }
9187 
9188 /// \brief Perform semantic checking of a new function declaration.
9189 ///
9190 /// Performs semantic analysis of the new function declaration
9191 /// NewFD. This routine performs all semantic checking that does not
9192 /// require the actual declarator involved in the declaration, and is
9193 /// used both for the declaration of functions as they are parsed
9194 /// (called via ActOnDeclarator) and for the declaration of functions
9195 /// that have been instantiated via C++ template instantiation (called
9196 /// via InstantiateDecl).
9197 ///
9198 /// \param IsMemberSpecialization whether this new function declaration is
9199 /// a member specialization (that replaces any definition provided by the
9200 /// previous declaration).
9201 ///
9202 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9203 ///
9204 /// \returns true if the function declaration is a redeclaration.
9205 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9206                                     LookupResult &Previous,
9207                                     bool IsMemberSpecialization) {
9208   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9209          "Variably modified return types are not handled here");
9210 
9211   // Determine whether the type of this function should be merged with
9212   // a previous visible declaration. This never happens for functions in C++,
9213   // and always happens in C if the previous declaration was visible.
9214   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9215                                !Previous.isShadowed();
9216 
9217   bool Redeclaration = false;
9218   NamedDecl *OldDecl = nullptr;
9219   bool MayNeedOverloadableChecks = false;
9220 
9221   // Merge or overload the declaration with an existing declaration of
9222   // the same name, if appropriate.
9223   if (!Previous.empty()) {
9224     // Determine whether NewFD is an overload of PrevDecl or
9225     // a declaration that requires merging. If it's an overload,
9226     // there's no more work to do here; we'll just add the new
9227     // function to the scope.
9228     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9229       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9230       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9231         Redeclaration = true;
9232         OldDecl = Candidate;
9233       }
9234     } else {
9235       MayNeedOverloadableChecks = true;
9236       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9237                             /*NewIsUsingDecl*/ false)) {
9238       case Ovl_Match:
9239         Redeclaration = true;
9240         break;
9241 
9242       case Ovl_NonFunction:
9243         Redeclaration = true;
9244         break;
9245 
9246       case Ovl_Overload:
9247         Redeclaration = false;
9248         break;
9249       }
9250     }
9251   }
9252 
9253   // Check for a previous extern "C" declaration with this name.
9254   if (!Redeclaration &&
9255       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9256     if (!Previous.empty()) {
9257       // This is an extern "C" declaration with the same name as a previous
9258       // declaration, and thus redeclares that entity...
9259       Redeclaration = true;
9260       OldDecl = Previous.getFoundDecl();
9261       MergeTypeWithPrevious = false;
9262 
9263       // ... except in the presence of __attribute__((overloadable)).
9264       if (OldDecl->hasAttr<OverloadableAttr>() ||
9265           NewFD->hasAttr<OverloadableAttr>()) {
9266         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9267           MayNeedOverloadableChecks = true;
9268           Redeclaration = false;
9269           OldDecl = nullptr;
9270         }
9271       }
9272     }
9273   }
9274 
9275   // C++11 [dcl.constexpr]p8:
9276   //   A constexpr specifier for a non-static member function that is not
9277   //   a constructor declares that member function to be const.
9278   //
9279   // This needs to be delayed until we know whether this is an out-of-line
9280   // definition of a static member function.
9281   //
9282   // This rule is not present in C++1y, so we produce a backwards
9283   // compatibility warning whenever it happens in C++11.
9284   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9285   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9286       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9287       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9288     CXXMethodDecl *OldMD = nullptr;
9289     if (OldDecl)
9290       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9291     if (!OldMD || !OldMD->isStatic()) {
9292       const FunctionProtoType *FPT =
9293         MD->getType()->castAs<FunctionProtoType>();
9294       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9295       EPI.TypeQuals |= Qualifiers::Const;
9296       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9297                                           FPT->getParamTypes(), EPI));
9298 
9299       // Warn that we did this, if we're not performing template instantiation.
9300       // In that case, we'll have warned already when the template was defined.
9301       if (!inTemplateInstantiation()) {
9302         SourceLocation AddConstLoc;
9303         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9304                 .IgnoreParens().getAs<FunctionTypeLoc>())
9305           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9306 
9307         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9308           << FixItHint::CreateInsertion(AddConstLoc, " const");
9309       }
9310     }
9311   }
9312 
9313   if (Redeclaration) {
9314     // NewFD and OldDecl represent declarations that need to be
9315     // merged.
9316     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9317       NewFD->setInvalidDecl();
9318       return Redeclaration;
9319     }
9320 
9321     Previous.clear();
9322     Previous.addDecl(OldDecl);
9323 
9324     if (FunctionTemplateDecl *OldTemplateDecl
9325                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9326       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9327       FunctionTemplateDecl *NewTemplateDecl
9328         = NewFD->getDescribedFunctionTemplate();
9329       assert(NewTemplateDecl && "Template/non-template mismatch");
9330       if (CXXMethodDecl *Method
9331             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9332         Method->setAccess(OldTemplateDecl->getAccess());
9333         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9334       }
9335 
9336       // If this is an explicit specialization of a member that is a function
9337       // template, mark it as a member specialization.
9338       if (IsMemberSpecialization &&
9339           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9340         NewTemplateDecl->setMemberSpecialization();
9341         assert(OldTemplateDecl->isMemberSpecialization());
9342         // Explicit specializations of a member template do not inherit deleted
9343         // status from the parent member template that they are specializing.
9344         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9345           FunctionDecl *const OldTemplatedDecl =
9346               OldTemplateDecl->getTemplatedDecl();
9347           // FIXME: This assert will not hold in the presence of modules.
9348           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9349           // FIXME: We need an update record for this AST mutation.
9350           OldTemplatedDecl->setDeletedAsWritten(false);
9351         }
9352       }
9353 
9354     } else {
9355       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9356         // This needs to happen first so that 'inline' propagates.
9357         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9358         if (isa<CXXMethodDecl>(NewFD))
9359           NewFD->setAccess(OldDecl->getAccess());
9360       }
9361     }
9362   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9363              !NewFD->getAttr<OverloadableAttr>()) {
9364     assert((Previous.empty() ||
9365             llvm::any_of(Previous,
9366                          [](const NamedDecl *ND) {
9367                            return ND->hasAttr<OverloadableAttr>();
9368                          })) &&
9369            "Non-redecls shouldn't happen without overloadable present");
9370 
9371     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9372       const auto *FD = dyn_cast<FunctionDecl>(ND);
9373       return FD && !FD->hasAttr<OverloadableAttr>();
9374     });
9375 
9376     if (OtherUnmarkedIter != Previous.end()) {
9377       Diag(NewFD->getLocation(),
9378            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9379       Diag((*OtherUnmarkedIter)->getLocation(),
9380            diag::note_attribute_overloadable_prev_overload)
9381           << false;
9382 
9383       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9384     }
9385   }
9386 
9387   // Semantic checking for this function declaration (in isolation).
9388 
9389   if (getLangOpts().CPlusPlus) {
9390     // C++-specific checks.
9391     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9392       CheckConstructor(Constructor);
9393     } else if (CXXDestructorDecl *Destructor =
9394                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9395       CXXRecordDecl *Record = Destructor->getParent();
9396       QualType ClassType = Context.getTypeDeclType(Record);
9397 
9398       // FIXME: Shouldn't we be able to perform this check even when the class
9399       // type is dependent? Both gcc and edg can handle that.
9400       if (!ClassType->isDependentType()) {
9401         DeclarationName Name
9402           = Context.DeclarationNames.getCXXDestructorName(
9403                                         Context.getCanonicalType(ClassType));
9404         if (NewFD->getDeclName() != Name) {
9405           Diag(NewFD->getLocation(), diag::err_destructor_name);
9406           NewFD->setInvalidDecl();
9407           return Redeclaration;
9408         }
9409       }
9410     } else if (CXXConversionDecl *Conversion
9411                = dyn_cast<CXXConversionDecl>(NewFD)) {
9412       ActOnConversionDeclarator(Conversion);
9413     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9414       if (auto *TD = Guide->getDescribedFunctionTemplate())
9415         CheckDeductionGuideTemplate(TD);
9416 
9417       // A deduction guide is not on the list of entities that can be
9418       // explicitly specialized.
9419       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9420         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9421             << /*explicit specialization*/ 1;
9422     }
9423 
9424     // Find any virtual functions that this function overrides.
9425     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9426       if (!Method->isFunctionTemplateSpecialization() &&
9427           !Method->getDescribedFunctionTemplate() &&
9428           Method->isCanonicalDecl()) {
9429         if (AddOverriddenMethods(Method->getParent(), Method)) {
9430           // If the function was marked as "static", we have a problem.
9431           if (NewFD->getStorageClass() == SC_Static) {
9432             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9433           }
9434         }
9435       }
9436 
9437       if (Method->isStatic())
9438         checkThisInStaticMemberFunctionType(Method);
9439     }
9440 
9441     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9442     if (NewFD->isOverloadedOperator() &&
9443         CheckOverloadedOperatorDeclaration(NewFD)) {
9444       NewFD->setInvalidDecl();
9445       return Redeclaration;
9446     }
9447 
9448     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9449     if (NewFD->getLiteralIdentifier() &&
9450         CheckLiteralOperatorDeclaration(NewFD)) {
9451       NewFD->setInvalidDecl();
9452       return Redeclaration;
9453     }
9454 
9455     // In C++, check default arguments now that we have merged decls. Unless
9456     // the lexical context is the class, because in this case this is done
9457     // during delayed parsing anyway.
9458     if (!CurContext->isRecord())
9459       CheckCXXDefaultArguments(NewFD);
9460 
9461     // If this function declares a builtin function, check the type of this
9462     // declaration against the expected type for the builtin.
9463     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9464       ASTContext::GetBuiltinTypeError Error;
9465       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9466       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9467       // If the type of the builtin differs only in its exception
9468       // specification, that's OK.
9469       // FIXME: If the types do differ in this way, it would be better to
9470       // retain the 'noexcept' form of the type.
9471       if (!T.isNull() &&
9472           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9473                                                             NewFD->getType()))
9474         // The type of this function differs from the type of the builtin,
9475         // so forget about the builtin entirely.
9476         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9477     }
9478 
9479     // If this function is declared as being extern "C", then check to see if
9480     // the function returns a UDT (class, struct, or union type) that is not C
9481     // compatible, and if it does, warn the user.
9482     // But, issue any diagnostic on the first declaration only.
9483     if (Previous.empty() && NewFD->isExternC()) {
9484       QualType R = NewFD->getReturnType();
9485       if (R->isIncompleteType() && !R->isVoidType())
9486         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9487             << NewFD << R;
9488       else if (!R.isPODType(Context) && !R->isVoidType() &&
9489                !R->isObjCObjectPointerType())
9490         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9491     }
9492 
9493     // C++1z [dcl.fct]p6:
9494     //   [...] whether the function has a non-throwing exception-specification
9495     //   [is] part of the function type
9496     //
9497     // This results in an ABI break between C++14 and C++17 for functions whose
9498     // declared type includes an exception-specification in a parameter or
9499     // return type. (Exception specifications on the function itself are OK in
9500     // most cases, and exception specifications are not permitted in most other
9501     // contexts where they could make it into a mangling.)
9502     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9503       auto HasNoexcept = [&](QualType T) -> bool {
9504         // Strip off declarator chunks that could be between us and a function
9505         // type. We don't need to look far, exception specifications are very
9506         // restricted prior to C++17.
9507         if (auto *RT = T->getAs<ReferenceType>())
9508           T = RT->getPointeeType();
9509         else if (T->isAnyPointerType())
9510           T = T->getPointeeType();
9511         else if (auto *MPT = T->getAs<MemberPointerType>())
9512           T = MPT->getPointeeType();
9513         if (auto *FPT = T->getAs<FunctionProtoType>())
9514           if (FPT->isNothrow(Context))
9515             return true;
9516         return false;
9517       };
9518 
9519       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9520       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9521       for (QualType T : FPT->param_types())
9522         AnyNoexcept |= HasNoexcept(T);
9523       if (AnyNoexcept)
9524         Diag(NewFD->getLocation(),
9525              diag::warn_cxx1z_compat_exception_spec_in_signature)
9526             << NewFD;
9527     }
9528 
9529     if (!Redeclaration && LangOpts.CUDA)
9530       checkCUDATargetOverload(NewFD, Previous);
9531   }
9532   return Redeclaration;
9533 }
9534 
9535 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9536   // C++11 [basic.start.main]p3:
9537   //   A program that [...] declares main to be inline, static or
9538   //   constexpr is ill-formed.
9539   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9540   //   appear in a declaration of main.
9541   // static main is not an error under C99, but we should warn about it.
9542   // We accept _Noreturn main as an extension.
9543   if (FD->getStorageClass() == SC_Static)
9544     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9545          ? diag::err_static_main : diag::warn_static_main)
9546       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9547   if (FD->isInlineSpecified())
9548     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9549       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9550   if (DS.isNoreturnSpecified()) {
9551     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9552     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9553     Diag(NoreturnLoc, diag::ext_noreturn_main);
9554     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9555       << FixItHint::CreateRemoval(NoreturnRange);
9556   }
9557   if (FD->isConstexpr()) {
9558     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9559       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9560     FD->setConstexpr(false);
9561   }
9562 
9563   if (getLangOpts().OpenCL) {
9564     Diag(FD->getLocation(), diag::err_opencl_no_main)
9565         << FD->hasAttr<OpenCLKernelAttr>();
9566     FD->setInvalidDecl();
9567     return;
9568   }
9569 
9570   QualType T = FD->getType();
9571   assert(T->isFunctionType() && "function decl is not of function type");
9572   const FunctionType* FT = T->castAs<FunctionType>();
9573 
9574   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9575     // In C with GNU extensions we allow main() to have non-integer return
9576     // type, but we should warn about the extension, and we disable the
9577     // implicit-return-zero rule.
9578 
9579     // GCC in C mode accepts qualified 'int'.
9580     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9581       FD->setHasImplicitReturnZero(true);
9582     else {
9583       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9584       SourceRange RTRange = FD->getReturnTypeSourceRange();
9585       if (RTRange.isValid())
9586         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9587             << FixItHint::CreateReplacement(RTRange, "int");
9588     }
9589   } else {
9590     // In C and C++, main magically returns 0 if you fall off the end;
9591     // set the flag which tells us that.
9592     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9593 
9594     // All the standards say that main() should return 'int'.
9595     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9596       FD->setHasImplicitReturnZero(true);
9597     else {
9598       // Otherwise, this is just a flat-out error.
9599       SourceRange RTRange = FD->getReturnTypeSourceRange();
9600       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9601           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9602                                 : FixItHint());
9603       FD->setInvalidDecl(true);
9604     }
9605   }
9606 
9607   // Treat protoless main() as nullary.
9608   if (isa<FunctionNoProtoType>(FT)) return;
9609 
9610   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9611   unsigned nparams = FTP->getNumParams();
9612   assert(FD->getNumParams() == nparams);
9613 
9614   bool HasExtraParameters = (nparams > 3);
9615 
9616   if (FTP->isVariadic()) {
9617     Diag(FD->getLocation(), diag::ext_variadic_main);
9618     // FIXME: if we had information about the location of the ellipsis, we
9619     // could add a FixIt hint to remove it as a parameter.
9620   }
9621 
9622   // Darwin passes an undocumented fourth argument of type char**.  If
9623   // other platforms start sprouting these, the logic below will start
9624   // getting shifty.
9625   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9626     HasExtraParameters = false;
9627 
9628   if (HasExtraParameters) {
9629     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9630     FD->setInvalidDecl(true);
9631     nparams = 3;
9632   }
9633 
9634   // FIXME: a lot of the following diagnostics would be improved
9635   // if we had some location information about types.
9636 
9637   QualType CharPP =
9638     Context.getPointerType(Context.getPointerType(Context.CharTy));
9639   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9640 
9641   for (unsigned i = 0; i < nparams; ++i) {
9642     QualType AT = FTP->getParamType(i);
9643 
9644     bool mismatch = true;
9645 
9646     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9647       mismatch = false;
9648     else if (Expected[i] == CharPP) {
9649       // As an extension, the following forms are okay:
9650       //   char const **
9651       //   char const * const *
9652       //   char * const *
9653 
9654       QualifierCollector qs;
9655       const PointerType* PT;
9656       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9657           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9658           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9659                               Context.CharTy)) {
9660         qs.removeConst();
9661         mismatch = !qs.empty();
9662       }
9663     }
9664 
9665     if (mismatch) {
9666       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9667       // TODO: suggest replacing given type with expected type
9668       FD->setInvalidDecl(true);
9669     }
9670   }
9671 
9672   if (nparams == 1 && !FD->isInvalidDecl()) {
9673     Diag(FD->getLocation(), diag::warn_main_one_arg);
9674   }
9675 
9676   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9677     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9678     FD->setInvalidDecl();
9679   }
9680 }
9681 
9682 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9683   QualType T = FD->getType();
9684   assert(T->isFunctionType() && "function decl is not of function type");
9685   const FunctionType *FT = T->castAs<FunctionType>();
9686 
9687   // Set an implicit return of 'zero' if the function can return some integral,
9688   // enumeration, pointer or nullptr type.
9689   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9690       FT->getReturnType()->isAnyPointerType() ||
9691       FT->getReturnType()->isNullPtrType())
9692     // DllMain is exempt because a return value of zero means it failed.
9693     if (FD->getName() != "DllMain")
9694       FD->setHasImplicitReturnZero(true);
9695 
9696   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9697     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9698     FD->setInvalidDecl();
9699   }
9700 }
9701 
9702 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9703   // FIXME: Need strict checking.  In C89, we need to check for
9704   // any assignment, increment, decrement, function-calls, or
9705   // commas outside of a sizeof.  In C99, it's the same list,
9706   // except that the aforementioned are allowed in unevaluated
9707   // expressions.  Everything else falls under the
9708   // "may accept other forms of constant expressions" exception.
9709   // (We never end up here for C++, so the constant expression
9710   // rules there don't matter.)
9711   const Expr *Culprit;
9712   if (Init->isConstantInitializer(Context, false, &Culprit))
9713     return false;
9714   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9715     << Culprit->getSourceRange();
9716   return true;
9717 }
9718 
9719 namespace {
9720   // Visits an initialization expression to see if OrigDecl is evaluated in
9721   // its own initialization and throws a warning if it does.
9722   class SelfReferenceChecker
9723       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9724     Sema &S;
9725     Decl *OrigDecl;
9726     bool isRecordType;
9727     bool isPODType;
9728     bool isReferenceType;
9729 
9730     bool isInitList;
9731     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9732 
9733   public:
9734     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9735 
9736     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9737                                                     S(S), OrigDecl(OrigDecl) {
9738       isPODType = false;
9739       isRecordType = false;
9740       isReferenceType = false;
9741       isInitList = false;
9742       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9743         isPODType = VD->getType().isPODType(S.Context);
9744         isRecordType = VD->getType()->isRecordType();
9745         isReferenceType = VD->getType()->isReferenceType();
9746       }
9747     }
9748 
9749     // For most expressions, just call the visitor.  For initializer lists,
9750     // track the index of the field being initialized since fields are
9751     // initialized in order allowing use of previously initialized fields.
9752     void CheckExpr(Expr *E) {
9753       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9754       if (!InitList) {
9755         Visit(E);
9756         return;
9757       }
9758 
9759       // Track and increment the index here.
9760       isInitList = true;
9761       InitFieldIndex.push_back(0);
9762       for (auto Child : InitList->children()) {
9763         CheckExpr(cast<Expr>(Child));
9764         ++InitFieldIndex.back();
9765       }
9766       InitFieldIndex.pop_back();
9767     }
9768 
9769     // Returns true if MemberExpr is checked and no further checking is needed.
9770     // Returns false if additional checking is required.
9771     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9772       llvm::SmallVector<FieldDecl*, 4> Fields;
9773       Expr *Base = E;
9774       bool ReferenceField = false;
9775 
9776       // Get the field memebers used.
9777       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9778         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9779         if (!FD)
9780           return false;
9781         Fields.push_back(FD);
9782         if (FD->getType()->isReferenceType())
9783           ReferenceField = true;
9784         Base = ME->getBase()->IgnoreParenImpCasts();
9785       }
9786 
9787       // Keep checking only if the base Decl is the same.
9788       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9789       if (!DRE || DRE->getDecl() != OrigDecl)
9790         return false;
9791 
9792       // A reference field can be bound to an unininitialized field.
9793       if (CheckReference && !ReferenceField)
9794         return true;
9795 
9796       // Convert FieldDecls to their index number.
9797       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9798       for (const FieldDecl *I : llvm::reverse(Fields))
9799         UsedFieldIndex.push_back(I->getFieldIndex());
9800 
9801       // See if a warning is needed by checking the first difference in index
9802       // numbers.  If field being used has index less than the field being
9803       // initialized, then the use is safe.
9804       for (auto UsedIter = UsedFieldIndex.begin(),
9805                 UsedEnd = UsedFieldIndex.end(),
9806                 OrigIter = InitFieldIndex.begin(),
9807                 OrigEnd = InitFieldIndex.end();
9808            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9809         if (*UsedIter < *OrigIter)
9810           return true;
9811         if (*UsedIter > *OrigIter)
9812           break;
9813       }
9814 
9815       // TODO: Add a different warning which will print the field names.
9816       HandleDeclRefExpr(DRE);
9817       return true;
9818     }
9819 
9820     // For most expressions, the cast is directly above the DeclRefExpr.
9821     // For conditional operators, the cast can be outside the conditional
9822     // operator if both expressions are DeclRefExpr's.
9823     void HandleValue(Expr *E) {
9824       E = E->IgnoreParens();
9825       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9826         HandleDeclRefExpr(DRE);
9827         return;
9828       }
9829 
9830       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9831         Visit(CO->getCond());
9832         HandleValue(CO->getTrueExpr());
9833         HandleValue(CO->getFalseExpr());
9834         return;
9835       }
9836 
9837       if (BinaryConditionalOperator *BCO =
9838               dyn_cast<BinaryConditionalOperator>(E)) {
9839         Visit(BCO->getCond());
9840         HandleValue(BCO->getFalseExpr());
9841         return;
9842       }
9843 
9844       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9845         HandleValue(OVE->getSourceExpr());
9846         return;
9847       }
9848 
9849       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9850         if (BO->getOpcode() == BO_Comma) {
9851           Visit(BO->getLHS());
9852           HandleValue(BO->getRHS());
9853           return;
9854         }
9855       }
9856 
9857       if (isa<MemberExpr>(E)) {
9858         if (isInitList) {
9859           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9860                                       false /*CheckReference*/))
9861             return;
9862         }
9863 
9864         Expr *Base = E->IgnoreParenImpCasts();
9865         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9866           // Check for static member variables and don't warn on them.
9867           if (!isa<FieldDecl>(ME->getMemberDecl()))
9868             return;
9869           Base = ME->getBase()->IgnoreParenImpCasts();
9870         }
9871         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9872           HandleDeclRefExpr(DRE);
9873         return;
9874       }
9875 
9876       Visit(E);
9877     }
9878 
9879     // Reference types not handled in HandleValue are handled here since all
9880     // uses of references are bad, not just r-value uses.
9881     void VisitDeclRefExpr(DeclRefExpr *E) {
9882       if (isReferenceType)
9883         HandleDeclRefExpr(E);
9884     }
9885 
9886     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9887       if (E->getCastKind() == CK_LValueToRValue) {
9888         HandleValue(E->getSubExpr());
9889         return;
9890       }
9891 
9892       Inherited::VisitImplicitCastExpr(E);
9893     }
9894 
9895     void VisitMemberExpr(MemberExpr *E) {
9896       if (isInitList) {
9897         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9898           return;
9899       }
9900 
9901       // Don't warn on arrays since they can be treated as pointers.
9902       if (E->getType()->canDecayToPointerType()) return;
9903 
9904       // Warn when a non-static method call is followed by non-static member
9905       // field accesses, which is followed by a DeclRefExpr.
9906       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9907       bool Warn = (MD && !MD->isStatic());
9908       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9909       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9910         if (!isa<FieldDecl>(ME->getMemberDecl()))
9911           Warn = false;
9912         Base = ME->getBase()->IgnoreParenImpCasts();
9913       }
9914 
9915       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9916         if (Warn)
9917           HandleDeclRefExpr(DRE);
9918         return;
9919       }
9920 
9921       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9922       // Visit that expression.
9923       Visit(Base);
9924     }
9925 
9926     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9927       Expr *Callee = E->getCallee();
9928 
9929       if (isa<UnresolvedLookupExpr>(Callee))
9930         return Inherited::VisitCXXOperatorCallExpr(E);
9931 
9932       Visit(Callee);
9933       for (auto Arg: E->arguments())
9934         HandleValue(Arg->IgnoreParenImpCasts());
9935     }
9936 
9937     void VisitUnaryOperator(UnaryOperator *E) {
9938       // For POD record types, addresses of its own members are well-defined.
9939       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9940           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9941         if (!isPODType)
9942           HandleValue(E->getSubExpr());
9943         return;
9944       }
9945 
9946       if (E->isIncrementDecrementOp()) {
9947         HandleValue(E->getSubExpr());
9948         return;
9949       }
9950 
9951       Inherited::VisitUnaryOperator(E);
9952     }
9953 
9954     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9955 
9956     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9957       if (E->getConstructor()->isCopyConstructor()) {
9958         Expr *ArgExpr = E->getArg(0);
9959         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9960           if (ILE->getNumInits() == 1)
9961             ArgExpr = ILE->getInit(0);
9962         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9963           if (ICE->getCastKind() == CK_NoOp)
9964             ArgExpr = ICE->getSubExpr();
9965         HandleValue(ArgExpr);
9966         return;
9967       }
9968       Inherited::VisitCXXConstructExpr(E);
9969     }
9970 
9971     void VisitCallExpr(CallExpr *E) {
9972       // Treat std::move as a use.
9973       if (E->getNumArgs() == 1) {
9974         if (FunctionDecl *FD = E->getDirectCallee()) {
9975           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9976               FD->getIdentifier()->isStr("move")) {
9977             HandleValue(E->getArg(0));
9978             return;
9979           }
9980         }
9981       }
9982 
9983       Inherited::VisitCallExpr(E);
9984     }
9985 
9986     void VisitBinaryOperator(BinaryOperator *E) {
9987       if (E->isCompoundAssignmentOp()) {
9988         HandleValue(E->getLHS());
9989         Visit(E->getRHS());
9990         return;
9991       }
9992 
9993       Inherited::VisitBinaryOperator(E);
9994     }
9995 
9996     // A custom visitor for BinaryConditionalOperator is needed because the
9997     // regular visitor would check the condition and true expression separately
9998     // but both point to the same place giving duplicate diagnostics.
9999     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10000       Visit(E->getCond());
10001       Visit(E->getFalseExpr());
10002     }
10003 
10004     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10005       Decl* ReferenceDecl = DRE->getDecl();
10006       if (OrigDecl != ReferenceDecl) return;
10007       unsigned diag;
10008       if (isReferenceType) {
10009         diag = diag::warn_uninit_self_reference_in_reference_init;
10010       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10011         diag = diag::warn_static_self_reference_in_init;
10012       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10013                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10014                  DRE->getDecl()->getType()->isRecordType()) {
10015         diag = diag::warn_uninit_self_reference_in_init;
10016       } else {
10017         // Local variables will be handled by the CFG analysis.
10018         return;
10019       }
10020 
10021       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10022                             S.PDiag(diag)
10023                               << DRE->getNameInfo().getName()
10024                               << OrigDecl->getLocation()
10025                               << DRE->getSourceRange());
10026     }
10027   };
10028 
10029   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10030   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10031                                  bool DirectInit) {
10032     // Parameters arguments are occassionially constructed with itself,
10033     // for instance, in recursive functions.  Skip them.
10034     if (isa<ParmVarDecl>(OrigDecl))
10035       return;
10036 
10037     E = E->IgnoreParens();
10038 
10039     // Skip checking T a = a where T is not a record or reference type.
10040     // Doing so is a way to silence uninitialized warnings.
10041     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10042       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10043         if (ICE->getCastKind() == CK_LValueToRValue)
10044           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10045             if (DRE->getDecl() == OrigDecl)
10046               return;
10047 
10048     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10049   }
10050 } // end anonymous namespace
10051 
10052 namespace {
10053   // Simple wrapper to add the name of a variable or (if no variable is
10054   // available) a DeclarationName into a diagnostic.
10055   struct VarDeclOrName {
10056     VarDecl *VDecl;
10057     DeclarationName Name;
10058 
10059     friend const Sema::SemaDiagnosticBuilder &
10060     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10061       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10062     }
10063   };
10064 } // end anonymous namespace
10065 
10066 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10067                                             DeclarationName Name, QualType Type,
10068                                             TypeSourceInfo *TSI,
10069                                             SourceRange Range, bool DirectInit,
10070                                             Expr *Init) {
10071   bool IsInitCapture = !VDecl;
10072   assert((!VDecl || !VDecl->isInitCapture()) &&
10073          "init captures are expected to be deduced prior to initialization");
10074 
10075   VarDeclOrName VN{VDecl, Name};
10076 
10077   DeducedType *Deduced = Type->getContainedDeducedType();
10078   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10079 
10080   // C++11 [dcl.spec.auto]p3
10081   if (!Init) {
10082     assert(VDecl && "no init for init capture deduction?");
10083     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10084       << VDecl->getDeclName() << Type;
10085     return QualType();
10086   }
10087 
10088   ArrayRef<Expr*> DeduceInits = Init;
10089   if (DirectInit) {
10090     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10091       DeduceInits = PL->exprs();
10092   }
10093 
10094   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10095     assert(VDecl && "non-auto type for init capture deduction?");
10096     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10097     InitializationKind Kind = InitializationKind::CreateForInit(
10098         VDecl->getLocation(), DirectInit, Init);
10099     // FIXME: Initialization should not be taking a mutable list of inits.
10100     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10101     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10102                                                        InitsCopy);
10103   }
10104 
10105   if (DirectInit) {
10106     if (auto *IL = dyn_cast<InitListExpr>(Init))
10107       DeduceInits = IL->inits();
10108   }
10109 
10110   // Deduction only works if we have exactly one source expression.
10111   if (DeduceInits.empty()) {
10112     // It isn't possible to write this directly, but it is possible to
10113     // end up in this situation with "auto x(some_pack...);"
10114     Diag(Init->getLocStart(), IsInitCapture
10115                                   ? diag::err_init_capture_no_expression
10116                                   : diag::err_auto_var_init_no_expression)
10117         << VN << Type << Range;
10118     return QualType();
10119   }
10120 
10121   if (DeduceInits.size() > 1) {
10122     Diag(DeduceInits[1]->getLocStart(),
10123          IsInitCapture ? diag::err_init_capture_multiple_expressions
10124                        : diag::err_auto_var_init_multiple_expressions)
10125         << VN << Type << Range;
10126     return QualType();
10127   }
10128 
10129   Expr *DeduceInit = DeduceInits[0];
10130   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10131     Diag(Init->getLocStart(), IsInitCapture
10132                                   ? diag::err_init_capture_paren_braces
10133                                   : diag::err_auto_var_init_paren_braces)
10134         << isa<InitListExpr>(Init) << VN << Type << Range;
10135     return QualType();
10136   }
10137 
10138   // Expressions default to 'id' when we're in a debugger.
10139   bool DefaultedAnyToId = false;
10140   if (getLangOpts().DebuggerCastResultToId &&
10141       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10142     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10143     if (Result.isInvalid()) {
10144       return QualType();
10145     }
10146     Init = Result.get();
10147     DefaultedAnyToId = true;
10148   }
10149 
10150   // C++ [dcl.decomp]p1:
10151   //   If the assignment-expression [...] has array type A and no ref-qualifier
10152   //   is present, e has type cv A
10153   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10154       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10155       DeduceInit->getType()->isConstantArrayType())
10156     return Context.getQualifiedType(DeduceInit->getType(),
10157                                     Type.getQualifiers());
10158 
10159   QualType DeducedType;
10160   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10161     if (!IsInitCapture)
10162       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10163     else if (isa<InitListExpr>(Init))
10164       Diag(Range.getBegin(),
10165            diag::err_init_capture_deduction_failure_from_init_list)
10166           << VN
10167           << (DeduceInit->getType().isNull() ? TSI->getType()
10168                                              : DeduceInit->getType())
10169           << DeduceInit->getSourceRange();
10170     else
10171       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10172           << VN << TSI->getType()
10173           << (DeduceInit->getType().isNull() ? TSI->getType()
10174                                              : DeduceInit->getType())
10175           << DeduceInit->getSourceRange();
10176   }
10177 
10178   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10179   // 'id' instead of a specific object type prevents most of our usual
10180   // checks.
10181   // We only want to warn outside of template instantiations, though:
10182   // inside a template, the 'id' could have come from a parameter.
10183   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10184       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10185     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10186     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10187   }
10188 
10189   return DeducedType;
10190 }
10191 
10192 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10193                                          Expr *Init) {
10194   QualType DeducedType = deduceVarTypeFromInitializer(
10195       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10196       VDecl->getSourceRange(), DirectInit, Init);
10197   if (DeducedType.isNull()) {
10198     VDecl->setInvalidDecl();
10199     return true;
10200   }
10201 
10202   VDecl->setType(DeducedType);
10203   assert(VDecl->isLinkageValid());
10204 
10205   // In ARC, infer lifetime.
10206   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10207     VDecl->setInvalidDecl();
10208 
10209   // If this is a redeclaration, check that the type we just deduced matches
10210   // the previously declared type.
10211   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10212     // We never need to merge the type, because we cannot form an incomplete
10213     // array of auto, nor deduce such a type.
10214     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10215   }
10216 
10217   // Check the deduced type is valid for a variable declaration.
10218   CheckVariableDeclarationType(VDecl);
10219   return VDecl->isInvalidDecl();
10220 }
10221 
10222 /// AddInitializerToDecl - Adds the initializer Init to the
10223 /// declaration dcl. If DirectInit is true, this is C++ direct
10224 /// initialization rather than copy initialization.
10225 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10226   // If there is no declaration, there was an error parsing it.  Just ignore
10227   // the initializer.
10228   if (!RealDecl || RealDecl->isInvalidDecl()) {
10229     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10230     return;
10231   }
10232 
10233   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10234     // Pure-specifiers are handled in ActOnPureSpecifier.
10235     Diag(Method->getLocation(), diag::err_member_function_initialization)
10236       << Method->getDeclName() << Init->getSourceRange();
10237     Method->setInvalidDecl();
10238     return;
10239   }
10240 
10241   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10242   if (!VDecl) {
10243     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10244     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10245     RealDecl->setInvalidDecl();
10246     return;
10247   }
10248 
10249   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10250   if (VDecl->getType()->isUndeducedType()) {
10251     // Attempt typo correction early so that the type of the init expression can
10252     // be deduced based on the chosen correction if the original init contains a
10253     // TypoExpr.
10254     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10255     if (!Res.isUsable()) {
10256       RealDecl->setInvalidDecl();
10257       return;
10258     }
10259     Init = Res.get();
10260 
10261     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10262       return;
10263   }
10264 
10265   // dllimport cannot be used on variable definitions.
10266   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10267     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10268     VDecl->setInvalidDecl();
10269     return;
10270   }
10271 
10272   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10273     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10274     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10275     VDecl->setInvalidDecl();
10276     return;
10277   }
10278 
10279   if (!VDecl->getType()->isDependentType()) {
10280     // A definition must end up with a complete type, which means it must be
10281     // complete with the restriction that an array type might be completed by
10282     // the initializer; note that later code assumes this restriction.
10283     QualType BaseDeclType = VDecl->getType();
10284     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10285       BaseDeclType = Array->getElementType();
10286     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10287                             diag::err_typecheck_decl_incomplete_type)) {
10288       RealDecl->setInvalidDecl();
10289       return;
10290     }
10291 
10292     // The variable can not have an abstract class type.
10293     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10294                                diag::err_abstract_type_in_decl,
10295                                AbstractVariableType))
10296       VDecl->setInvalidDecl();
10297   }
10298 
10299   // If adding the initializer will turn this declaration into a definition,
10300   // and we already have a definition for this variable, diagnose or otherwise
10301   // handle the situation.
10302   VarDecl *Def;
10303   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10304       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10305       !VDecl->isThisDeclarationADemotedDefinition() &&
10306       checkVarDeclRedefinition(Def, VDecl))
10307     return;
10308 
10309   if (getLangOpts().CPlusPlus) {
10310     // C++ [class.static.data]p4
10311     //   If a static data member is of const integral or const
10312     //   enumeration type, its declaration in the class definition can
10313     //   specify a constant-initializer which shall be an integral
10314     //   constant expression (5.19). In that case, the member can appear
10315     //   in integral constant expressions. The member shall still be
10316     //   defined in a namespace scope if it is used in the program and the
10317     //   namespace scope definition shall not contain an initializer.
10318     //
10319     // We already performed a redefinition check above, but for static
10320     // data members we also need to check whether there was an in-class
10321     // declaration with an initializer.
10322     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10323       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10324           << VDecl->getDeclName();
10325       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10326            diag::note_previous_initializer)
10327           << 0;
10328       return;
10329     }
10330 
10331     if (VDecl->hasLocalStorage())
10332       getCurFunction()->setHasBranchProtectedScope();
10333 
10334     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10335       VDecl->setInvalidDecl();
10336       return;
10337     }
10338   }
10339 
10340   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10341   // a kernel function cannot be initialized."
10342   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10343     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10344     VDecl->setInvalidDecl();
10345     return;
10346   }
10347 
10348   // Get the decls type and save a reference for later, since
10349   // CheckInitializerTypes may change it.
10350   QualType DclT = VDecl->getType(), SavT = DclT;
10351 
10352   // Expressions default to 'id' when we're in a debugger
10353   // and we are assigning it to a variable of Objective-C pointer type.
10354   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10355       Init->getType() == Context.UnknownAnyTy) {
10356     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10357     if (Result.isInvalid()) {
10358       VDecl->setInvalidDecl();
10359       return;
10360     }
10361     Init = Result.get();
10362   }
10363 
10364   // Perform the initialization.
10365   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10366   if (!VDecl->isInvalidDecl()) {
10367     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10368     InitializationKind Kind = InitializationKind::CreateForInit(
10369         VDecl->getLocation(), DirectInit, Init);
10370 
10371     MultiExprArg Args = Init;
10372     if (CXXDirectInit)
10373       Args = MultiExprArg(CXXDirectInit->getExprs(),
10374                           CXXDirectInit->getNumExprs());
10375 
10376     // Try to correct any TypoExprs in the initialization arguments.
10377     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10378       ExprResult Res = CorrectDelayedTyposInExpr(
10379           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10380             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10381             return Init.Failed() ? ExprError() : E;
10382           });
10383       if (Res.isInvalid()) {
10384         VDecl->setInvalidDecl();
10385       } else if (Res.get() != Args[Idx]) {
10386         Args[Idx] = Res.get();
10387       }
10388     }
10389     if (VDecl->isInvalidDecl())
10390       return;
10391 
10392     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10393                                    /*TopLevelOfInitList=*/false,
10394                                    /*TreatUnavailableAsInvalid=*/false);
10395     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10396     if (Result.isInvalid()) {
10397       VDecl->setInvalidDecl();
10398       return;
10399     }
10400 
10401     Init = Result.getAs<Expr>();
10402   }
10403 
10404   // Check for self-references within variable initializers.
10405   // Variables declared within a function/method body (except for references)
10406   // are handled by a dataflow analysis.
10407   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10408       VDecl->getType()->isReferenceType()) {
10409     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10410   }
10411 
10412   // If the type changed, it means we had an incomplete type that was
10413   // completed by the initializer. For example:
10414   //   int ary[] = { 1, 3, 5 };
10415   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10416   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10417     VDecl->setType(DclT);
10418 
10419   if (!VDecl->isInvalidDecl()) {
10420     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10421 
10422     if (VDecl->hasAttr<BlocksAttr>())
10423       checkRetainCycles(VDecl, Init);
10424 
10425     // It is safe to assign a weak reference into a strong variable.
10426     // Although this code can still have problems:
10427     //   id x = self.weakProp;
10428     //   id y = self.weakProp;
10429     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10430     // paths through the function. This should be revisited if
10431     // -Wrepeated-use-of-weak is made flow-sensitive.
10432     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10433          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10434         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10435                          Init->getLocStart()))
10436       getCurFunction()->markSafeWeakUse(Init);
10437   }
10438 
10439   // The initialization is usually a full-expression.
10440   //
10441   // FIXME: If this is a braced initialization of an aggregate, it is not
10442   // an expression, and each individual field initializer is a separate
10443   // full-expression. For instance, in:
10444   //
10445   //   struct Temp { ~Temp(); };
10446   //   struct S { S(Temp); };
10447   //   struct T { S a, b; } t = { Temp(), Temp() }
10448   //
10449   // we should destroy the first Temp before constructing the second.
10450   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10451                                           false,
10452                                           VDecl->isConstexpr());
10453   if (Result.isInvalid()) {
10454     VDecl->setInvalidDecl();
10455     return;
10456   }
10457   Init = Result.get();
10458 
10459   // Attach the initializer to the decl.
10460   VDecl->setInit(Init);
10461 
10462   if (VDecl->isLocalVarDecl()) {
10463     // Don't check the initializer if the declaration is malformed.
10464     if (VDecl->isInvalidDecl()) {
10465       // do nothing
10466 
10467     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10468     // This is true even in OpenCL C++.
10469     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10470       CheckForConstantInitializer(Init, DclT);
10471 
10472     // Otherwise, C++ does not restrict the initializer.
10473     } else if (getLangOpts().CPlusPlus) {
10474       // do nothing
10475 
10476     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10477     // static storage duration shall be constant expressions or string literals.
10478     } else if (VDecl->getStorageClass() == SC_Static) {
10479       CheckForConstantInitializer(Init, DclT);
10480 
10481     // C89 is stricter than C99 for aggregate initializers.
10482     // C89 6.5.7p3: All the expressions [...] in an initializer list
10483     // for an object that has aggregate or union type shall be
10484     // constant expressions.
10485     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10486                isa<InitListExpr>(Init)) {
10487       const Expr *Culprit;
10488       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10489         Diag(Culprit->getExprLoc(),
10490              diag::ext_aggregate_init_not_constant)
10491           << Culprit->getSourceRange();
10492       }
10493     }
10494   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10495              VDecl->getLexicalDeclContext()->isRecord()) {
10496     // This is an in-class initialization for a static data member, e.g.,
10497     //
10498     // struct S {
10499     //   static const int value = 17;
10500     // };
10501 
10502     // C++ [class.mem]p4:
10503     //   A member-declarator can contain a constant-initializer only
10504     //   if it declares a static member (9.4) of const integral or
10505     //   const enumeration type, see 9.4.2.
10506     //
10507     // C++11 [class.static.data]p3:
10508     //   If a non-volatile non-inline const static data member is of integral
10509     //   or enumeration type, its declaration in the class definition can
10510     //   specify a brace-or-equal-initializer in which every initializer-clause
10511     //   that is an assignment-expression is a constant expression. A static
10512     //   data member of literal type can be declared in the class definition
10513     //   with the constexpr specifier; if so, its declaration shall specify a
10514     //   brace-or-equal-initializer in which every initializer-clause that is
10515     //   an assignment-expression is a constant expression.
10516 
10517     // Do nothing on dependent types.
10518     if (DclT->isDependentType()) {
10519 
10520     // Allow any 'static constexpr' members, whether or not they are of literal
10521     // type. We separately check that every constexpr variable is of literal
10522     // type.
10523     } else if (VDecl->isConstexpr()) {
10524 
10525     // Require constness.
10526     } else if (!DclT.isConstQualified()) {
10527       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10528         << Init->getSourceRange();
10529       VDecl->setInvalidDecl();
10530 
10531     // We allow integer constant expressions in all cases.
10532     } else if (DclT->isIntegralOrEnumerationType()) {
10533       // Check whether the expression is a constant expression.
10534       SourceLocation Loc;
10535       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10536         // In C++11, a non-constexpr const static data member with an
10537         // in-class initializer cannot be volatile.
10538         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10539       else if (Init->isValueDependent())
10540         ; // Nothing to check.
10541       else if (Init->isIntegerConstantExpr(Context, &Loc))
10542         ; // Ok, it's an ICE!
10543       else if (Init->isEvaluatable(Context)) {
10544         // If we can constant fold the initializer through heroics, accept it,
10545         // but report this as a use of an extension for -pedantic.
10546         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10547           << Init->getSourceRange();
10548       } else {
10549         // Otherwise, this is some crazy unknown case.  Report the issue at the
10550         // location provided by the isIntegerConstantExpr failed check.
10551         Diag(Loc, diag::err_in_class_initializer_non_constant)
10552           << Init->getSourceRange();
10553         VDecl->setInvalidDecl();
10554       }
10555 
10556     // We allow foldable floating-point constants as an extension.
10557     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10558       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10559       // it anyway and provide a fixit to add the 'constexpr'.
10560       if (getLangOpts().CPlusPlus11) {
10561         Diag(VDecl->getLocation(),
10562              diag::ext_in_class_initializer_float_type_cxx11)
10563             << DclT << Init->getSourceRange();
10564         Diag(VDecl->getLocStart(),
10565              diag::note_in_class_initializer_float_type_cxx11)
10566             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10567       } else {
10568         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10569           << DclT << Init->getSourceRange();
10570 
10571         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10572           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10573             << Init->getSourceRange();
10574           VDecl->setInvalidDecl();
10575         }
10576       }
10577 
10578     // Suggest adding 'constexpr' in C++11 for literal types.
10579     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10580       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10581         << DclT << Init->getSourceRange()
10582         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10583       VDecl->setConstexpr(true);
10584 
10585     } else {
10586       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10587         << DclT << Init->getSourceRange();
10588       VDecl->setInvalidDecl();
10589     }
10590   } else if (VDecl->isFileVarDecl()) {
10591     // In C, extern is typically used to avoid tentative definitions when
10592     // declaring variables in headers, but adding an intializer makes it a
10593     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10594     // In C++, extern is often used to give implictly static const variables
10595     // external linkage, so don't warn in that case. If selectany is present,
10596     // this might be header code intended for C and C++ inclusion, so apply the
10597     // C++ rules.
10598     if (VDecl->getStorageClass() == SC_Extern &&
10599         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10600          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10601         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10602         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10603       Diag(VDecl->getLocation(), diag::warn_extern_init);
10604 
10605     // C99 6.7.8p4. All file scoped initializers need to be constant.
10606     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10607       CheckForConstantInitializer(Init, DclT);
10608   }
10609 
10610   // We will represent direct-initialization similarly to copy-initialization:
10611   //    int x(1);  -as-> int x = 1;
10612   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10613   //
10614   // Clients that want to distinguish between the two forms, can check for
10615   // direct initializer using VarDecl::getInitStyle().
10616   // A major benefit is that clients that don't particularly care about which
10617   // exactly form was it (like the CodeGen) can handle both cases without
10618   // special case code.
10619 
10620   // C++ 8.5p11:
10621   // The form of initialization (using parentheses or '=') is generally
10622   // insignificant, but does matter when the entity being initialized has a
10623   // class type.
10624   if (CXXDirectInit) {
10625     assert(DirectInit && "Call-style initializer must be direct init.");
10626     VDecl->setInitStyle(VarDecl::CallInit);
10627   } else if (DirectInit) {
10628     // This must be list-initialization. No other way is direct-initialization.
10629     VDecl->setInitStyle(VarDecl::ListInit);
10630   }
10631 
10632   CheckCompleteVariableDeclaration(VDecl);
10633 }
10634 
10635 /// ActOnInitializerError - Given that there was an error parsing an
10636 /// initializer for the given declaration, try to return to some form
10637 /// of sanity.
10638 void Sema::ActOnInitializerError(Decl *D) {
10639   // Our main concern here is re-establishing invariants like "a
10640   // variable's type is either dependent or complete".
10641   if (!D || D->isInvalidDecl()) return;
10642 
10643   VarDecl *VD = dyn_cast<VarDecl>(D);
10644   if (!VD) return;
10645 
10646   // Bindings are not usable if we can't make sense of the initializer.
10647   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10648     for (auto *BD : DD->bindings())
10649       BD->setInvalidDecl();
10650 
10651   // Auto types are meaningless if we can't make sense of the initializer.
10652   if (ParsingInitForAutoVars.count(D)) {
10653     D->setInvalidDecl();
10654     return;
10655   }
10656 
10657   QualType Ty = VD->getType();
10658   if (Ty->isDependentType()) return;
10659 
10660   // Require a complete type.
10661   if (RequireCompleteType(VD->getLocation(),
10662                           Context.getBaseElementType(Ty),
10663                           diag::err_typecheck_decl_incomplete_type)) {
10664     VD->setInvalidDecl();
10665     return;
10666   }
10667 
10668   // Require a non-abstract type.
10669   if (RequireNonAbstractType(VD->getLocation(), Ty,
10670                              diag::err_abstract_type_in_decl,
10671                              AbstractVariableType)) {
10672     VD->setInvalidDecl();
10673     return;
10674   }
10675 
10676   // Don't bother complaining about constructors or destructors,
10677   // though.
10678 }
10679 
10680 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10681   // If there is no declaration, there was an error parsing it. Just ignore it.
10682   if (!RealDecl)
10683     return;
10684 
10685   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10686     QualType Type = Var->getType();
10687 
10688     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10689     if (isa<DecompositionDecl>(RealDecl)) {
10690       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10691       Var->setInvalidDecl();
10692       return;
10693     }
10694 
10695     if (Type->isUndeducedType() &&
10696         DeduceVariableDeclarationType(Var, false, nullptr))
10697       return;
10698 
10699     // C++11 [class.static.data]p3: A static data member can be declared with
10700     // the constexpr specifier; if so, its declaration shall specify
10701     // a brace-or-equal-initializer.
10702     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10703     // the definition of a variable [...] or the declaration of a static data
10704     // member.
10705     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10706         !Var->isThisDeclarationADemotedDefinition()) {
10707       if (Var->isStaticDataMember()) {
10708         // C++1z removes the relevant rule; the in-class declaration is always
10709         // a definition there.
10710         if (!getLangOpts().CPlusPlus1z) {
10711           Diag(Var->getLocation(),
10712                diag::err_constexpr_static_mem_var_requires_init)
10713             << Var->getDeclName();
10714           Var->setInvalidDecl();
10715           return;
10716         }
10717       } else {
10718         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10719         Var->setInvalidDecl();
10720         return;
10721       }
10722     }
10723 
10724     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10725     // definition having the concept specifier is called a variable concept. A
10726     // concept definition refers to [...] a variable concept and its initializer.
10727     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10728       if (VTD->isConcept()) {
10729         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10730         Var->setInvalidDecl();
10731         return;
10732       }
10733     }
10734 
10735     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10736     // be initialized.
10737     if (!Var->isInvalidDecl() &&
10738         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10739         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10740       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10741       Var->setInvalidDecl();
10742       return;
10743     }
10744 
10745     switch (Var->isThisDeclarationADefinition()) {
10746     case VarDecl::Definition:
10747       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10748         break;
10749 
10750       // We have an out-of-line definition of a static data member
10751       // that has an in-class initializer, so we type-check this like
10752       // a declaration.
10753       //
10754       // Fall through
10755 
10756     case VarDecl::DeclarationOnly:
10757       // It's only a declaration.
10758 
10759       // Block scope. C99 6.7p7: If an identifier for an object is
10760       // declared with no linkage (C99 6.2.2p6), the type for the
10761       // object shall be complete.
10762       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10763           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10764           RequireCompleteType(Var->getLocation(), Type,
10765                               diag::err_typecheck_decl_incomplete_type))
10766         Var->setInvalidDecl();
10767 
10768       // Make sure that the type is not abstract.
10769       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10770           RequireNonAbstractType(Var->getLocation(), Type,
10771                                  diag::err_abstract_type_in_decl,
10772                                  AbstractVariableType))
10773         Var->setInvalidDecl();
10774       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10775           Var->getStorageClass() == SC_PrivateExtern) {
10776         Diag(Var->getLocation(), diag::warn_private_extern);
10777         Diag(Var->getLocation(), diag::note_private_extern);
10778       }
10779 
10780       return;
10781 
10782     case VarDecl::TentativeDefinition:
10783       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10784       // object that has file scope without an initializer, and without a
10785       // storage-class specifier or with the storage-class specifier "static",
10786       // constitutes a tentative definition. Note: A tentative definition with
10787       // external linkage is valid (C99 6.2.2p5).
10788       if (!Var->isInvalidDecl()) {
10789         if (const IncompleteArrayType *ArrayT
10790                                     = Context.getAsIncompleteArrayType(Type)) {
10791           if (RequireCompleteType(Var->getLocation(),
10792                                   ArrayT->getElementType(),
10793                                   diag::err_illegal_decl_array_incomplete_type))
10794             Var->setInvalidDecl();
10795         } else if (Var->getStorageClass() == SC_Static) {
10796           // C99 6.9.2p3: If the declaration of an identifier for an object is
10797           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10798           // declared type shall not be an incomplete type.
10799           // NOTE: code such as the following
10800           //     static struct s;
10801           //     struct s { int a; };
10802           // is accepted by gcc. Hence here we issue a warning instead of
10803           // an error and we do not invalidate the static declaration.
10804           // NOTE: to avoid multiple warnings, only check the first declaration.
10805           if (Var->isFirstDecl())
10806             RequireCompleteType(Var->getLocation(), Type,
10807                                 diag::ext_typecheck_decl_incomplete_type);
10808         }
10809       }
10810 
10811       // Record the tentative definition; we're done.
10812       if (!Var->isInvalidDecl())
10813         TentativeDefinitions.push_back(Var);
10814       return;
10815     }
10816 
10817     // Provide a specific diagnostic for uninitialized variable
10818     // definitions with incomplete array type.
10819     if (Type->isIncompleteArrayType()) {
10820       Diag(Var->getLocation(),
10821            diag::err_typecheck_incomplete_array_needs_initializer);
10822       Var->setInvalidDecl();
10823       return;
10824     }
10825 
10826     // Provide a specific diagnostic for uninitialized variable
10827     // definitions with reference type.
10828     if (Type->isReferenceType()) {
10829       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10830         << Var->getDeclName()
10831         << SourceRange(Var->getLocation(), Var->getLocation());
10832       Var->setInvalidDecl();
10833       return;
10834     }
10835 
10836     // Do not attempt to type-check the default initializer for a
10837     // variable with dependent type.
10838     if (Type->isDependentType())
10839       return;
10840 
10841     if (Var->isInvalidDecl())
10842       return;
10843 
10844     if (!Var->hasAttr<AliasAttr>()) {
10845       if (RequireCompleteType(Var->getLocation(),
10846                               Context.getBaseElementType(Type),
10847                               diag::err_typecheck_decl_incomplete_type)) {
10848         Var->setInvalidDecl();
10849         return;
10850       }
10851     } else {
10852       return;
10853     }
10854 
10855     // The variable can not have an abstract class type.
10856     if (RequireNonAbstractType(Var->getLocation(), Type,
10857                                diag::err_abstract_type_in_decl,
10858                                AbstractVariableType)) {
10859       Var->setInvalidDecl();
10860       return;
10861     }
10862 
10863     // Check for jumps past the implicit initializer.  C++0x
10864     // clarifies that this applies to a "variable with automatic
10865     // storage duration", not a "local variable".
10866     // C++11 [stmt.dcl]p3
10867     //   A program that jumps from a point where a variable with automatic
10868     //   storage duration is not in scope to a point where it is in scope is
10869     //   ill-formed unless the variable has scalar type, class type with a
10870     //   trivial default constructor and a trivial destructor, a cv-qualified
10871     //   version of one of these types, or an array of one of the preceding
10872     //   types and is declared without an initializer.
10873     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10874       if (const RecordType *Record
10875             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10876         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10877         // Mark the function for further checking even if the looser rules of
10878         // C++11 do not require such checks, so that we can diagnose
10879         // incompatibilities with C++98.
10880         if (!CXXRecord->isPOD())
10881           getCurFunction()->setHasBranchProtectedScope();
10882       }
10883     }
10884 
10885     // C++03 [dcl.init]p9:
10886     //   If no initializer is specified for an object, and the
10887     //   object is of (possibly cv-qualified) non-POD class type (or
10888     //   array thereof), the object shall be default-initialized; if
10889     //   the object is of const-qualified type, the underlying class
10890     //   type shall have a user-declared default
10891     //   constructor. Otherwise, if no initializer is specified for
10892     //   a non- static object, the object and its subobjects, if
10893     //   any, have an indeterminate initial value); if the object
10894     //   or any of its subobjects are of const-qualified type, the
10895     //   program is ill-formed.
10896     // C++0x [dcl.init]p11:
10897     //   If no initializer is specified for an object, the object is
10898     //   default-initialized; [...].
10899     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10900     InitializationKind Kind
10901       = InitializationKind::CreateDefault(Var->getLocation());
10902 
10903     InitializationSequence InitSeq(*this, Entity, Kind, None);
10904     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10905     if (Init.isInvalid())
10906       Var->setInvalidDecl();
10907     else if (Init.get()) {
10908       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10909       // This is important for template substitution.
10910       Var->setInitStyle(VarDecl::CallInit);
10911     }
10912 
10913     CheckCompleteVariableDeclaration(Var);
10914   }
10915 }
10916 
10917 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10918   // If there is no declaration, there was an error parsing it. Ignore it.
10919   if (!D)
10920     return;
10921 
10922   VarDecl *VD = dyn_cast<VarDecl>(D);
10923   if (!VD) {
10924     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10925     D->setInvalidDecl();
10926     return;
10927   }
10928 
10929   VD->setCXXForRangeDecl(true);
10930 
10931   // for-range-declaration cannot be given a storage class specifier.
10932   int Error = -1;
10933   switch (VD->getStorageClass()) {
10934   case SC_None:
10935     break;
10936   case SC_Extern:
10937     Error = 0;
10938     break;
10939   case SC_Static:
10940     Error = 1;
10941     break;
10942   case SC_PrivateExtern:
10943     Error = 2;
10944     break;
10945   case SC_Auto:
10946     Error = 3;
10947     break;
10948   case SC_Register:
10949     Error = 4;
10950     break;
10951   }
10952   if (Error != -1) {
10953     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10954       << VD->getDeclName() << Error;
10955     D->setInvalidDecl();
10956   }
10957 }
10958 
10959 StmtResult
10960 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10961                                  IdentifierInfo *Ident,
10962                                  ParsedAttributes &Attrs,
10963                                  SourceLocation AttrEnd) {
10964   // C++1y [stmt.iter]p1:
10965   //   A range-based for statement of the form
10966   //      for ( for-range-identifier : for-range-initializer ) statement
10967   //   is equivalent to
10968   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10969   DeclSpec DS(Attrs.getPool().getFactory());
10970 
10971   const char *PrevSpec;
10972   unsigned DiagID;
10973   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10974                      getPrintingPolicy());
10975 
10976   Declarator D(DS, Declarator::ForContext);
10977   D.SetIdentifier(Ident, IdentLoc);
10978   D.takeAttributes(Attrs, AttrEnd);
10979 
10980   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10981   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10982                 EmptyAttrs, IdentLoc);
10983   Decl *Var = ActOnDeclarator(S, D);
10984   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10985   FinalizeDeclaration(Var);
10986   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10987                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10988 }
10989 
10990 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10991   if (var->isInvalidDecl()) return;
10992 
10993   if (getLangOpts().OpenCL) {
10994     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10995     // initialiser
10996     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10997         !var->hasInit()) {
10998       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10999           << 1 /*Init*/;
11000       var->setInvalidDecl();
11001       return;
11002     }
11003   }
11004 
11005   // In Objective-C, don't allow jumps past the implicit initialization of a
11006   // local retaining variable.
11007   if (getLangOpts().ObjC1 &&
11008       var->hasLocalStorage()) {
11009     switch (var->getType().getObjCLifetime()) {
11010     case Qualifiers::OCL_None:
11011     case Qualifiers::OCL_ExplicitNone:
11012     case Qualifiers::OCL_Autoreleasing:
11013       break;
11014 
11015     case Qualifiers::OCL_Weak:
11016     case Qualifiers::OCL_Strong:
11017       getCurFunction()->setHasBranchProtectedScope();
11018       break;
11019     }
11020   }
11021 
11022   // Warn about externally-visible variables being defined without a
11023   // prior declaration.  We only want to do this for global
11024   // declarations, but we also specifically need to avoid doing it for
11025   // class members because the linkage of an anonymous class can
11026   // change if it's later given a typedef name.
11027   if (var->isThisDeclarationADefinition() &&
11028       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11029       var->isExternallyVisible() && var->hasLinkage() &&
11030       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11031                                   var->getLocation())) {
11032     // Find a previous declaration that's not a definition.
11033     VarDecl *prev = var->getPreviousDecl();
11034     while (prev && prev->isThisDeclarationADefinition())
11035       prev = prev->getPreviousDecl();
11036 
11037     if (!prev)
11038       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11039   }
11040 
11041   // Cache the result of checking for constant initialization.
11042   Optional<bool> CacheHasConstInit;
11043   const Expr *CacheCulprit;
11044   auto checkConstInit = [&]() mutable {
11045     if (!CacheHasConstInit)
11046       CacheHasConstInit = var->getInit()->isConstantInitializer(
11047             Context, var->getType()->isReferenceType(), &CacheCulprit);
11048     return *CacheHasConstInit;
11049   };
11050 
11051   if (var->getTLSKind() == VarDecl::TLS_Static) {
11052     if (var->getType().isDestructedType()) {
11053       // GNU C++98 edits for __thread, [basic.start.term]p3:
11054       //   The type of an object with thread storage duration shall not
11055       //   have a non-trivial destructor.
11056       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11057       if (getLangOpts().CPlusPlus11)
11058         Diag(var->getLocation(), diag::note_use_thread_local);
11059     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11060       if (!checkConstInit()) {
11061         // GNU C++98 edits for __thread, [basic.start.init]p4:
11062         //   An object of thread storage duration shall not require dynamic
11063         //   initialization.
11064         // FIXME: Need strict checking here.
11065         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11066           << CacheCulprit->getSourceRange();
11067         if (getLangOpts().CPlusPlus11)
11068           Diag(var->getLocation(), diag::note_use_thread_local);
11069       }
11070     }
11071   }
11072 
11073   // Apply section attributes and pragmas to global variables.
11074   bool GlobalStorage = var->hasGlobalStorage();
11075   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11076       !inTemplateInstantiation()) {
11077     PragmaStack<StringLiteral *> *Stack = nullptr;
11078     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11079     if (var->getType().isConstQualified())
11080       Stack = &ConstSegStack;
11081     else if (!var->getInit()) {
11082       Stack = &BSSSegStack;
11083       SectionFlags |= ASTContext::PSF_Write;
11084     } else {
11085       Stack = &DataSegStack;
11086       SectionFlags |= ASTContext::PSF_Write;
11087     }
11088     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11089       var->addAttr(SectionAttr::CreateImplicit(
11090           Context, SectionAttr::Declspec_allocate,
11091           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11092     }
11093     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11094       if (UnifySection(SA->getName(), SectionFlags, var))
11095         var->dropAttr<SectionAttr>();
11096 
11097     // Apply the init_seg attribute if this has an initializer.  If the
11098     // initializer turns out to not be dynamic, we'll end up ignoring this
11099     // attribute.
11100     if (CurInitSeg && var->getInit())
11101       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11102                                                CurInitSegLoc));
11103   }
11104 
11105   // All the following checks are C++ only.
11106   if (!getLangOpts().CPlusPlus) {
11107       // If this variable must be emitted, add it as an initializer for the
11108       // current module.
11109      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11110        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11111      return;
11112   }
11113 
11114   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11115     CheckCompleteDecompositionDeclaration(DD);
11116 
11117   QualType type = var->getType();
11118   if (type->isDependentType()) return;
11119 
11120   // __block variables might require us to capture a copy-initializer.
11121   if (var->hasAttr<BlocksAttr>()) {
11122     // It's currently invalid to ever have a __block variable with an
11123     // array type; should we diagnose that here?
11124 
11125     // Regardless, we don't want to ignore array nesting when
11126     // constructing this copy.
11127     if (type->isStructureOrClassType()) {
11128       EnterExpressionEvaluationContext scope(
11129           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11130       SourceLocation poi = var->getLocation();
11131       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11132       ExprResult result
11133         = PerformMoveOrCopyInitialization(
11134             InitializedEntity::InitializeBlock(poi, type, false),
11135             var, var->getType(), varRef, /*AllowNRVO=*/true);
11136       if (!result.isInvalid()) {
11137         result = MaybeCreateExprWithCleanups(result);
11138         Expr *init = result.getAs<Expr>();
11139         Context.setBlockVarCopyInits(var, init);
11140       }
11141     }
11142   }
11143 
11144   Expr *Init = var->getInit();
11145   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11146   QualType baseType = Context.getBaseElementType(type);
11147 
11148   if (Init && !Init->isValueDependent()) {
11149     if (var->isConstexpr()) {
11150       SmallVector<PartialDiagnosticAt, 8> Notes;
11151       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11152         SourceLocation DiagLoc = var->getLocation();
11153         // If the note doesn't add any useful information other than a source
11154         // location, fold it into the primary diagnostic.
11155         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11156               diag::note_invalid_subexpr_in_const_expr) {
11157           DiagLoc = Notes[0].first;
11158           Notes.clear();
11159         }
11160         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11161           << var << Init->getSourceRange();
11162         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11163           Diag(Notes[I].first, Notes[I].second);
11164       }
11165     } else if (var->isUsableInConstantExpressions(Context)) {
11166       // Check whether the initializer of a const variable of integral or
11167       // enumeration type is an ICE now, since we can't tell whether it was
11168       // initialized by a constant expression if we check later.
11169       var->checkInitIsICE();
11170     }
11171 
11172     // Don't emit further diagnostics about constexpr globals since they
11173     // were just diagnosed.
11174     if (!var->isConstexpr() && GlobalStorage &&
11175             var->hasAttr<RequireConstantInitAttr>()) {
11176       // FIXME: Need strict checking in C++03 here.
11177       bool DiagErr = getLangOpts().CPlusPlus11
11178           ? !var->checkInitIsICE() : !checkConstInit();
11179       if (DiagErr) {
11180         auto attr = var->getAttr<RequireConstantInitAttr>();
11181         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11182           << Init->getSourceRange();
11183         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11184           << attr->getRange();
11185         if (getLangOpts().CPlusPlus11) {
11186           APValue Value;
11187           SmallVector<PartialDiagnosticAt, 8> Notes;
11188           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11189           for (auto &it : Notes)
11190             Diag(it.first, it.second);
11191         } else {
11192           Diag(CacheCulprit->getExprLoc(),
11193                diag::note_invalid_subexpr_in_const_expr)
11194               << CacheCulprit->getSourceRange();
11195         }
11196       }
11197     }
11198     else if (!var->isConstexpr() && IsGlobal &&
11199              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11200                                     var->getLocation())) {
11201       // Warn about globals which don't have a constant initializer.  Don't
11202       // warn about globals with a non-trivial destructor because we already
11203       // warned about them.
11204       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11205       if (!(RD && !RD->hasTrivialDestructor())) {
11206         if (!checkConstInit())
11207           Diag(var->getLocation(), diag::warn_global_constructor)
11208             << Init->getSourceRange();
11209       }
11210     }
11211   }
11212 
11213   // Require the destructor.
11214   if (const RecordType *recordType = baseType->getAs<RecordType>())
11215     FinalizeVarWithDestructor(var, recordType);
11216 
11217   // If this variable must be emitted, add it as an initializer for the current
11218   // module.
11219   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11220     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11221 }
11222 
11223 /// \brief Determines if a variable's alignment is dependent.
11224 static bool hasDependentAlignment(VarDecl *VD) {
11225   if (VD->getType()->isDependentType())
11226     return true;
11227   for (auto *I : VD->specific_attrs<AlignedAttr>())
11228     if (I->isAlignmentDependent())
11229       return true;
11230   return false;
11231 }
11232 
11233 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11234 /// any semantic actions necessary after any initializer has been attached.
11235 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11236   // Note that we are no longer parsing the initializer for this declaration.
11237   ParsingInitForAutoVars.erase(ThisDecl);
11238 
11239   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11240   if (!VD)
11241     return;
11242 
11243   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11244   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11245       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11246     if (PragmaClangBSSSection.Valid)
11247       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11248                                                             PragmaClangBSSSection.SectionName,
11249                                                             PragmaClangBSSSection.PragmaLocation));
11250     if (PragmaClangDataSection.Valid)
11251       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11252                                                              PragmaClangDataSection.SectionName,
11253                                                              PragmaClangDataSection.PragmaLocation));
11254     if (PragmaClangRodataSection.Valid)
11255       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11256                                                                PragmaClangRodataSection.SectionName,
11257                                                                PragmaClangRodataSection.PragmaLocation));
11258   }
11259 
11260   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11261     for (auto *BD : DD->bindings()) {
11262       FinalizeDeclaration(BD);
11263     }
11264   }
11265 
11266   checkAttributesAfterMerging(*this, *VD);
11267 
11268   // Perform TLS alignment check here after attributes attached to the variable
11269   // which may affect the alignment have been processed. Only perform the check
11270   // if the target has a maximum TLS alignment (zero means no constraints).
11271   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11272     // Protect the check so that it's not performed on dependent types and
11273     // dependent alignments (we can't determine the alignment in that case).
11274     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11275         !VD->isInvalidDecl()) {
11276       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11277       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11278         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11279           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11280           << (unsigned)MaxAlignChars.getQuantity();
11281       }
11282     }
11283   }
11284 
11285   if (VD->isStaticLocal()) {
11286     if (FunctionDecl *FD =
11287             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11288       // Static locals inherit dll attributes from their function.
11289       if (Attr *A = getDLLAttr(FD)) {
11290         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11291         NewAttr->setInherited(true);
11292         VD->addAttr(NewAttr);
11293       }
11294       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11295       // function, only __shared__ variables may be declared with
11296       // static storage class.
11297       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11298           CUDADiagIfDeviceCode(VD->getLocation(),
11299                                diag::err_device_static_local_var)
11300               << CurrentCUDATarget())
11301         VD->setInvalidDecl();
11302     }
11303   }
11304 
11305   // Perform check for initializers of device-side global variables.
11306   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11307   // 7.5). We must also apply the same checks to all __shared__
11308   // variables whether they are local or not. CUDA also allows
11309   // constant initializers for __constant__ and __device__ variables.
11310   if (getLangOpts().CUDA) {
11311     const Expr *Init = VD->getInit();
11312     if (Init && VD->hasGlobalStorage()) {
11313       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11314           VD->hasAttr<CUDASharedAttr>()) {
11315         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11316         bool AllowedInit = false;
11317         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11318           AllowedInit =
11319               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11320         // We'll allow constant initializers even if it's a non-empty
11321         // constructor according to CUDA rules. This deviates from NVCC,
11322         // but allows us to handle things like constexpr constructors.
11323         if (!AllowedInit &&
11324             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11325           AllowedInit = VD->getInit()->isConstantInitializer(
11326               Context, VD->getType()->isReferenceType());
11327 
11328         // Also make sure that destructor, if there is one, is empty.
11329         if (AllowedInit)
11330           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11331             AllowedInit =
11332                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11333 
11334         if (!AllowedInit) {
11335           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11336                                       ? diag::err_shared_var_init
11337                                       : diag::err_dynamic_var_init)
11338               << Init->getSourceRange();
11339           VD->setInvalidDecl();
11340         }
11341       } else {
11342         // This is a host-side global variable.  Check that the initializer is
11343         // callable from the host side.
11344         const FunctionDecl *InitFn = nullptr;
11345         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11346           InitFn = CE->getConstructor();
11347         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11348           InitFn = CE->getDirectCallee();
11349         }
11350         if (InitFn) {
11351           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11352           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11353             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11354                 << InitFnTarget << InitFn;
11355             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11356             VD->setInvalidDecl();
11357           }
11358         }
11359       }
11360     }
11361   }
11362 
11363   // Grab the dllimport or dllexport attribute off of the VarDecl.
11364   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11365 
11366   // Imported static data members cannot be defined out-of-line.
11367   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11368     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11369         VD->isThisDeclarationADefinition()) {
11370       // We allow definitions of dllimport class template static data members
11371       // with a warning.
11372       CXXRecordDecl *Context =
11373         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11374       bool IsClassTemplateMember =
11375           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11376           Context->getDescribedClassTemplate();
11377 
11378       Diag(VD->getLocation(),
11379            IsClassTemplateMember
11380                ? diag::warn_attribute_dllimport_static_field_definition
11381                : diag::err_attribute_dllimport_static_field_definition);
11382       Diag(IA->getLocation(), diag::note_attribute);
11383       if (!IsClassTemplateMember)
11384         VD->setInvalidDecl();
11385     }
11386   }
11387 
11388   // dllimport/dllexport variables cannot be thread local, their TLS index
11389   // isn't exported with the variable.
11390   if (DLLAttr && VD->getTLSKind()) {
11391     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11392     if (F && getDLLAttr(F)) {
11393       assert(VD->isStaticLocal());
11394       // But if this is a static local in a dlimport/dllexport function, the
11395       // function will never be inlined, which means the var would never be
11396       // imported, so having it marked import/export is safe.
11397     } else {
11398       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11399                                                                     << DLLAttr;
11400       VD->setInvalidDecl();
11401     }
11402   }
11403 
11404   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11405     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11406       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11407       VD->dropAttr<UsedAttr>();
11408     }
11409   }
11410 
11411   const DeclContext *DC = VD->getDeclContext();
11412   // If there's a #pragma GCC visibility in scope, and this isn't a class
11413   // member, set the visibility of this variable.
11414   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11415     AddPushedVisibilityAttribute(VD);
11416 
11417   // FIXME: Warn on unused var template partial specializations.
11418   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11419     MarkUnusedFileScopedDecl(VD);
11420 
11421   // Now we have parsed the initializer and can update the table of magic
11422   // tag values.
11423   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11424       !VD->getType()->isIntegralOrEnumerationType())
11425     return;
11426 
11427   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11428     const Expr *MagicValueExpr = VD->getInit();
11429     if (!MagicValueExpr) {
11430       continue;
11431     }
11432     llvm::APSInt MagicValueInt;
11433     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11434       Diag(I->getRange().getBegin(),
11435            diag::err_type_tag_for_datatype_not_ice)
11436         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11437       continue;
11438     }
11439     if (MagicValueInt.getActiveBits() > 64) {
11440       Diag(I->getRange().getBegin(),
11441            diag::err_type_tag_for_datatype_too_large)
11442         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11443       continue;
11444     }
11445     uint64_t MagicValue = MagicValueInt.getZExtValue();
11446     RegisterTypeTagForDatatype(I->getArgumentKind(),
11447                                MagicValue,
11448                                I->getMatchingCType(),
11449                                I->getLayoutCompatible(),
11450                                I->getMustBeNull());
11451   }
11452 }
11453 
11454 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11455   auto *VD = dyn_cast<VarDecl>(DD);
11456   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11457 }
11458 
11459 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11460                                                    ArrayRef<Decl *> Group) {
11461   SmallVector<Decl*, 8> Decls;
11462 
11463   if (DS.isTypeSpecOwned())
11464     Decls.push_back(DS.getRepAsDecl());
11465 
11466   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11467   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11468   bool DiagnosedMultipleDecomps = false;
11469   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11470   bool DiagnosedNonDeducedAuto = false;
11471 
11472   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11473     if (Decl *D = Group[i]) {
11474       // For declarators, there are some additional syntactic-ish checks we need
11475       // to perform.
11476       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11477         if (!FirstDeclaratorInGroup)
11478           FirstDeclaratorInGroup = DD;
11479         if (!FirstDecompDeclaratorInGroup)
11480           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11481         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11482             !hasDeducedAuto(DD))
11483           FirstNonDeducedAutoInGroup = DD;
11484 
11485         if (FirstDeclaratorInGroup != DD) {
11486           // A decomposition declaration cannot be combined with any other
11487           // declaration in the same group.
11488           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11489             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11490                  diag::err_decomp_decl_not_alone)
11491                 << FirstDeclaratorInGroup->getSourceRange()
11492                 << DD->getSourceRange();
11493             DiagnosedMultipleDecomps = true;
11494           }
11495 
11496           // A declarator that uses 'auto' in any way other than to declare a
11497           // variable with a deduced type cannot be combined with any other
11498           // declarator in the same group.
11499           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11500             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11501                  diag::err_auto_non_deduced_not_alone)
11502                 << FirstNonDeducedAutoInGroup->getType()
11503                        ->hasAutoForTrailingReturnType()
11504                 << FirstDeclaratorInGroup->getSourceRange()
11505                 << DD->getSourceRange();
11506             DiagnosedNonDeducedAuto = true;
11507           }
11508         }
11509       }
11510 
11511       Decls.push_back(D);
11512     }
11513   }
11514 
11515   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11516     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11517       handleTagNumbering(Tag, S);
11518       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11519           getLangOpts().CPlusPlus)
11520         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11521     }
11522   }
11523 
11524   return BuildDeclaratorGroup(Decls);
11525 }
11526 
11527 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11528 /// group, performing any necessary semantic checking.
11529 Sema::DeclGroupPtrTy
11530 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11531   // C++14 [dcl.spec.auto]p7: (DR1347)
11532   //   If the type that replaces the placeholder type is not the same in each
11533   //   deduction, the program is ill-formed.
11534   if (Group.size() > 1) {
11535     QualType Deduced;
11536     VarDecl *DeducedDecl = nullptr;
11537     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11538       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11539       if (!D || D->isInvalidDecl())
11540         break;
11541       DeducedType *DT = D->getType()->getContainedDeducedType();
11542       if (!DT || DT->getDeducedType().isNull())
11543         continue;
11544       if (Deduced.isNull()) {
11545         Deduced = DT->getDeducedType();
11546         DeducedDecl = D;
11547       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11548         auto *AT = dyn_cast<AutoType>(DT);
11549         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11550              diag::err_auto_different_deductions)
11551           << (AT ? (unsigned)AT->getKeyword() : 3)
11552           << Deduced << DeducedDecl->getDeclName()
11553           << DT->getDeducedType() << D->getDeclName()
11554           << DeducedDecl->getInit()->getSourceRange()
11555           << D->getInit()->getSourceRange();
11556         D->setInvalidDecl();
11557         break;
11558       }
11559     }
11560   }
11561 
11562   ActOnDocumentableDecls(Group);
11563 
11564   return DeclGroupPtrTy::make(
11565       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11566 }
11567 
11568 void Sema::ActOnDocumentableDecl(Decl *D) {
11569   ActOnDocumentableDecls(D);
11570 }
11571 
11572 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11573   // Don't parse the comment if Doxygen diagnostics are ignored.
11574   if (Group.empty() || !Group[0])
11575     return;
11576 
11577   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11578                       Group[0]->getLocation()) &&
11579       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11580                       Group[0]->getLocation()))
11581     return;
11582 
11583   if (Group.size() >= 2) {
11584     // This is a decl group.  Normally it will contain only declarations
11585     // produced from declarator list.  But in case we have any definitions or
11586     // additional declaration references:
11587     //   'typedef struct S {} S;'
11588     //   'typedef struct S *S;'
11589     //   'struct S *pS;'
11590     // FinalizeDeclaratorGroup adds these as separate declarations.
11591     Decl *MaybeTagDecl = Group[0];
11592     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11593       Group = Group.slice(1);
11594     }
11595   }
11596 
11597   // See if there are any new comments that are not attached to a decl.
11598   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11599   if (!Comments.empty() &&
11600       !Comments.back()->isAttached()) {
11601     // There is at least one comment that not attached to a decl.
11602     // Maybe it should be attached to one of these decls?
11603     //
11604     // Note that this way we pick up not only comments that precede the
11605     // declaration, but also comments that *follow* the declaration -- thanks to
11606     // the lookahead in the lexer: we've consumed the semicolon and looked
11607     // ahead through comments.
11608     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11609       Context.getCommentForDecl(Group[i], &PP);
11610   }
11611 }
11612 
11613 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11614 /// to introduce parameters into function prototype scope.
11615 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11616   const DeclSpec &DS = D.getDeclSpec();
11617 
11618   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11619 
11620   // C++03 [dcl.stc]p2 also permits 'auto'.
11621   StorageClass SC = SC_None;
11622   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11623     SC = SC_Register;
11624   } else if (getLangOpts().CPlusPlus &&
11625              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11626     SC = SC_Auto;
11627   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11628     Diag(DS.getStorageClassSpecLoc(),
11629          diag::err_invalid_storage_class_in_func_decl);
11630     D.getMutableDeclSpec().ClearStorageClassSpecs();
11631   }
11632 
11633   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11634     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11635       << DeclSpec::getSpecifierName(TSCS);
11636   if (DS.isInlineSpecified())
11637     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11638         << getLangOpts().CPlusPlus1z;
11639   if (DS.isConstexprSpecified())
11640     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11641       << 0;
11642   if (DS.isConceptSpecified())
11643     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11644 
11645   DiagnoseFunctionSpecifiers(DS);
11646 
11647   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11648   QualType parmDeclType = TInfo->getType();
11649 
11650   if (getLangOpts().CPlusPlus) {
11651     // Check that there are no default arguments inside the type of this
11652     // parameter.
11653     CheckExtraCXXDefaultArguments(D);
11654 
11655     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11656     if (D.getCXXScopeSpec().isSet()) {
11657       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11658         << D.getCXXScopeSpec().getRange();
11659       D.getCXXScopeSpec().clear();
11660     }
11661   }
11662 
11663   // Ensure we have a valid name
11664   IdentifierInfo *II = nullptr;
11665   if (D.hasName()) {
11666     II = D.getIdentifier();
11667     if (!II) {
11668       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11669         << GetNameForDeclarator(D).getName();
11670       D.setInvalidType(true);
11671     }
11672   }
11673 
11674   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11675   if (II) {
11676     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11677                    ForRedeclaration);
11678     LookupName(R, S);
11679     if (R.isSingleResult()) {
11680       NamedDecl *PrevDecl = R.getFoundDecl();
11681       if (PrevDecl->isTemplateParameter()) {
11682         // Maybe we will complain about the shadowed template parameter.
11683         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11684         // Just pretend that we didn't see the previous declaration.
11685         PrevDecl = nullptr;
11686       } else if (S->isDeclScope(PrevDecl)) {
11687         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11688         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11689 
11690         // Recover by removing the name
11691         II = nullptr;
11692         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11693         D.setInvalidType(true);
11694       }
11695     }
11696   }
11697 
11698   // Temporarily put parameter variables in the translation unit, not
11699   // the enclosing context.  This prevents them from accidentally
11700   // looking like class members in C++.
11701   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11702                                     D.getLocStart(),
11703                                     D.getIdentifierLoc(), II,
11704                                     parmDeclType, TInfo,
11705                                     SC);
11706 
11707   if (D.isInvalidType())
11708     New->setInvalidDecl();
11709 
11710   assert(S->isFunctionPrototypeScope());
11711   assert(S->getFunctionPrototypeDepth() >= 1);
11712   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11713                     S->getNextFunctionPrototypeIndex());
11714 
11715   // Add the parameter declaration into this scope.
11716   S->AddDecl(New);
11717   if (II)
11718     IdResolver.AddDecl(New);
11719 
11720   ProcessDeclAttributes(S, New, D);
11721 
11722   if (D.getDeclSpec().isModulePrivateSpecified())
11723     Diag(New->getLocation(), diag::err_module_private_local)
11724       << 1 << New->getDeclName()
11725       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11726       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11727 
11728   if (New->hasAttr<BlocksAttr>()) {
11729     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11730   }
11731   return New;
11732 }
11733 
11734 /// \brief Synthesizes a variable for a parameter arising from a
11735 /// typedef.
11736 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11737                                               SourceLocation Loc,
11738                                               QualType T) {
11739   /* FIXME: setting StartLoc == Loc.
11740      Would it be worth to modify callers so as to provide proper source
11741      location for the unnamed parameters, embedding the parameter's type? */
11742   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11743                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11744                                            SC_None, nullptr);
11745   Param->setImplicit();
11746   return Param;
11747 }
11748 
11749 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11750   // Don't diagnose unused-parameter errors in template instantiations; we
11751   // will already have done so in the template itself.
11752   if (inTemplateInstantiation())
11753     return;
11754 
11755   for (const ParmVarDecl *Parameter : Parameters) {
11756     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11757         !Parameter->hasAttr<UnusedAttr>()) {
11758       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11759         << Parameter->getDeclName();
11760     }
11761   }
11762 }
11763 
11764 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11765     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11766   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11767     return;
11768 
11769   // Warn if the return value is pass-by-value and larger than the specified
11770   // threshold.
11771   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11772     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11773     if (Size > LangOpts.NumLargeByValueCopy)
11774       Diag(D->getLocation(), diag::warn_return_value_size)
11775           << D->getDeclName() << Size;
11776   }
11777 
11778   // Warn if any parameter is pass-by-value and larger than the specified
11779   // threshold.
11780   for (const ParmVarDecl *Parameter : Parameters) {
11781     QualType T = Parameter->getType();
11782     if (T->isDependentType() || !T.isPODType(Context))
11783       continue;
11784     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11785     if (Size > LangOpts.NumLargeByValueCopy)
11786       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11787           << Parameter->getDeclName() << Size;
11788   }
11789 }
11790 
11791 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11792                                   SourceLocation NameLoc, IdentifierInfo *Name,
11793                                   QualType T, TypeSourceInfo *TSInfo,
11794                                   StorageClass SC) {
11795   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11796   if (getLangOpts().ObjCAutoRefCount &&
11797       T.getObjCLifetime() == Qualifiers::OCL_None &&
11798       T->isObjCLifetimeType()) {
11799 
11800     Qualifiers::ObjCLifetime lifetime;
11801 
11802     // Special cases for arrays:
11803     //   - if it's const, use __unsafe_unretained
11804     //   - otherwise, it's an error
11805     if (T->isArrayType()) {
11806       if (!T.isConstQualified()) {
11807         DelayedDiagnostics.add(
11808             sema::DelayedDiagnostic::makeForbiddenType(
11809             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11810       }
11811       lifetime = Qualifiers::OCL_ExplicitNone;
11812     } else {
11813       lifetime = T->getObjCARCImplicitLifetime();
11814     }
11815     T = Context.getLifetimeQualifiedType(T, lifetime);
11816   }
11817 
11818   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11819                                          Context.getAdjustedParameterType(T),
11820                                          TSInfo, SC, nullptr);
11821 
11822   // Parameters can not be abstract class types.
11823   // For record types, this is done by the AbstractClassUsageDiagnoser once
11824   // the class has been completely parsed.
11825   if (!CurContext->isRecord() &&
11826       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11827                              AbstractParamType))
11828     New->setInvalidDecl();
11829 
11830   // Parameter declarators cannot be interface types. All ObjC objects are
11831   // passed by reference.
11832   if (T->isObjCObjectType()) {
11833     SourceLocation TypeEndLoc =
11834         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11835     Diag(NameLoc,
11836          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11837       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11838     T = Context.getObjCObjectPointerType(T);
11839     New->setType(T);
11840   }
11841 
11842   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11843   // duration shall not be qualified by an address-space qualifier."
11844   // Since all parameters have automatic store duration, they can not have
11845   // an address space.
11846   if (T.getAddressSpace() != 0) {
11847     // OpenCL allows function arguments declared to be an array of a type
11848     // to be qualified with an address space.
11849     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11850       Diag(NameLoc, diag::err_arg_with_address_space);
11851       New->setInvalidDecl();
11852     }
11853   }
11854 
11855   return New;
11856 }
11857 
11858 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11859                                            SourceLocation LocAfterDecls) {
11860   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11861 
11862   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11863   // for a K&R function.
11864   if (!FTI.hasPrototype) {
11865     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11866       --i;
11867       if (FTI.Params[i].Param == nullptr) {
11868         SmallString<256> Code;
11869         llvm::raw_svector_ostream(Code)
11870             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11871         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11872             << FTI.Params[i].Ident
11873             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11874 
11875         // Implicitly declare the argument as type 'int' for lack of a better
11876         // type.
11877         AttributeFactory attrs;
11878         DeclSpec DS(attrs);
11879         const char* PrevSpec; // unused
11880         unsigned DiagID; // unused
11881         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11882                            DiagID, Context.getPrintingPolicy());
11883         // Use the identifier location for the type source range.
11884         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11885         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11886         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11887         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11888         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11889       }
11890     }
11891   }
11892 }
11893 
11894 Decl *
11895 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11896                               MultiTemplateParamsArg TemplateParameterLists,
11897                               SkipBodyInfo *SkipBody) {
11898   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11899   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11900   Scope *ParentScope = FnBodyScope->getParent();
11901 
11902   D.setFunctionDefinitionKind(FDK_Definition);
11903   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11904   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11905 }
11906 
11907 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11908   Consumer.HandleInlineFunctionDefinition(D);
11909 }
11910 
11911 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11912                              const FunctionDecl*& PossibleZeroParamPrototype) {
11913   // Don't warn about invalid declarations.
11914   if (FD->isInvalidDecl())
11915     return false;
11916 
11917   // Or declarations that aren't global.
11918   if (!FD->isGlobal())
11919     return false;
11920 
11921   // Don't warn about C++ member functions.
11922   if (isa<CXXMethodDecl>(FD))
11923     return false;
11924 
11925   // Don't warn about 'main'.
11926   if (FD->isMain())
11927     return false;
11928 
11929   // Don't warn about inline functions.
11930   if (FD->isInlined())
11931     return false;
11932 
11933   // Don't warn about function templates.
11934   if (FD->getDescribedFunctionTemplate())
11935     return false;
11936 
11937   // Don't warn about function template specializations.
11938   if (FD->isFunctionTemplateSpecialization())
11939     return false;
11940 
11941   // Don't warn for OpenCL kernels.
11942   if (FD->hasAttr<OpenCLKernelAttr>())
11943     return false;
11944 
11945   // Don't warn on explicitly deleted functions.
11946   if (FD->isDeleted())
11947     return false;
11948 
11949   bool MissingPrototype = true;
11950   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11951        Prev; Prev = Prev->getPreviousDecl()) {
11952     // Ignore any declarations that occur in function or method
11953     // scope, because they aren't visible from the header.
11954     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11955       continue;
11956 
11957     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11958     if (FD->getNumParams() == 0)
11959       PossibleZeroParamPrototype = Prev;
11960     break;
11961   }
11962 
11963   return MissingPrototype;
11964 }
11965 
11966 void
11967 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11968                                    const FunctionDecl *EffectiveDefinition,
11969                                    SkipBodyInfo *SkipBody) {
11970   const FunctionDecl *Definition = EffectiveDefinition;
11971   if (!Definition)
11972     if (!FD->isDefined(Definition))
11973       return;
11974 
11975   if (canRedefineFunction(Definition, getLangOpts()))
11976     return;
11977 
11978   // Don't emit an error when this is redifinition of a typo-corrected
11979   // definition.
11980   if (TypoCorrectedFunctionDefinitions.count(Definition))
11981     return;
11982 
11983   // If we don't have a visible definition of the function, and it's inline or
11984   // a template, skip the new definition.
11985   if (SkipBody && !hasVisibleDefinition(Definition) &&
11986       (Definition->getFormalLinkage() == InternalLinkage ||
11987        Definition->isInlined() ||
11988        Definition->getDescribedFunctionTemplate() ||
11989        Definition->getNumTemplateParameterLists())) {
11990     SkipBody->ShouldSkip = true;
11991     if (auto *TD = Definition->getDescribedFunctionTemplate())
11992       makeMergedDefinitionVisible(TD);
11993     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
11994     return;
11995   }
11996 
11997   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11998       Definition->getStorageClass() == SC_Extern)
11999     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12000         << FD->getDeclName() << getLangOpts().CPlusPlus;
12001   else
12002     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12003 
12004   Diag(Definition->getLocation(), diag::note_previous_definition);
12005   FD->setInvalidDecl();
12006 }
12007 
12008 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12009                                    Sema &S) {
12010   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12011 
12012   LambdaScopeInfo *LSI = S.PushLambdaScope();
12013   LSI->CallOperator = CallOperator;
12014   LSI->Lambda = LambdaClass;
12015   LSI->ReturnType = CallOperator->getReturnType();
12016   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12017 
12018   if (LCD == LCD_None)
12019     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12020   else if (LCD == LCD_ByCopy)
12021     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12022   else if (LCD == LCD_ByRef)
12023     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12024   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12025 
12026   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12027   LSI->Mutable = !CallOperator->isConst();
12028 
12029   // Add the captures to the LSI so they can be noted as already
12030   // captured within tryCaptureVar.
12031   auto I = LambdaClass->field_begin();
12032   for (const auto &C : LambdaClass->captures()) {
12033     if (C.capturesVariable()) {
12034       VarDecl *VD = C.getCapturedVar();
12035       if (VD->isInitCapture())
12036         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12037       QualType CaptureType = VD->getType();
12038       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12039       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12040           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12041           /*EllipsisLoc*/C.isPackExpansion()
12042                          ? C.getEllipsisLoc() : SourceLocation(),
12043           CaptureType, /*Expr*/ nullptr);
12044 
12045     } else if (C.capturesThis()) {
12046       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12047                               /*Expr*/ nullptr,
12048                               C.getCaptureKind() == LCK_StarThis);
12049     } else {
12050       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12051     }
12052     ++I;
12053   }
12054 }
12055 
12056 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12057                                     SkipBodyInfo *SkipBody) {
12058   if (!D)
12059     return D;
12060   FunctionDecl *FD = nullptr;
12061 
12062   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12063     FD = FunTmpl->getTemplatedDecl();
12064   else
12065     FD = cast<FunctionDecl>(D);
12066 
12067   // Check for defining attributes before the check for redefinition.
12068   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12069     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12070     FD->dropAttr<AliasAttr>();
12071     FD->setInvalidDecl();
12072   }
12073   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12074     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12075     FD->dropAttr<IFuncAttr>();
12076     FD->setInvalidDecl();
12077   }
12078 
12079   // See if this is a redefinition.
12080   if (!FD->isLateTemplateParsed()) {
12081     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12082 
12083     // If we're skipping the body, we're done. Don't enter the scope.
12084     if (SkipBody && SkipBody->ShouldSkip)
12085       return D;
12086   }
12087 
12088   // Mark this function as "will have a body eventually".  This lets users to
12089   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12090   // this function.
12091   FD->setWillHaveBody();
12092 
12093   // If we are instantiating a generic lambda call operator, push
12094   // a LambdaScopeInfo onto the function stack.  But use the information
12095   // that's already been calculated (ActOnLambdaExpr) to prime the current
12096   // LambdaScopeInfo.
12097   // When the template operator is being specialized, the LambdaScopeInfo,
12098   // has to be properly restored so that tryCaptureVariable doesn't try
12099   // and capture any new variables. In addition when calculating potential
12100   // captures during transformation of nested lambdas, it is necessary to
12101   // have the LSI properly restored.
12102   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12103     assert(inTemplateInstantiation() &&
12104            "There should be an active template instantiation on the stack "
12105            "when instantiating a generic lambda!");
12106     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12107   } else {
12108     // Enter a new function scope
12109     PushFunctionScope();
12110   }
12111 
12112   // Builtin functions cannot be defined.
12113   if (unsigned BuiltinID = FD->getBuiltinID()) {
12114     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12115         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12116       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12117       FD->setInvalidDecl();
12118     }
12119   }
12120 
12121   // The return type of a function definition must be complete
12122   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12123   QualType ResultType = FD->getReturnType();
12124   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12125       !FD->isInvalidDecl() &&
12126       RequireCompleteType(FD->getLocation(), ResultType,
12127                           diag::err_func_def_incomplete_result))
12128     FD->setInvalidDecl();
12129 
12130   if (FnBodyScope)
12131     PushDeclContext(FnBodyScope, FD);
12132 
12133   // Check the validity of our function parameters
12134   CheckParmsForFunctionDef(FD->parameters(),
12135                            /*CheckParameterNames=*/true);
12136 
12137   // Add non-parameter declarations already in the function to the current
12138   // scope.
12139   if (FnBodyScope) {
12140     for (Decl *NPD : FD->decls()) {
12141       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12142       if (!NonParmDecl)
12143         continue;
12144       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12145              "parameters should not be in newly created FD yet");
12146 
12147       // If the decl has a name, make it accessible in the current scope.
12148       if (NonParmDecl->getDeclName())
12149         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12150 
12151       // Similarly, dive into enums and fish their constants out, making them
12152       // accessible in this scope.
12153       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12154         for (auto *EI : ED->enumerators())
12155           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12156       }
12157     }
12158   }
12159 
12160   // Introduce our parameters into the function scope
12161   for (auto Param : FD->parameters()) {
12162     Param->setOwningFunction(FD);
12163 
12164     // If this has an identifier, add it to the scope stack.
12165     if (Param->getIdentifier() && FnBodyScope) {
12166       CheckShadow(FnBodyScope, Param);
12167 
12168       PushOnScopeChains(Param, FnBodyScope);
12169     }
12170   }
12171 
12172   // Ensure that the function's exception specification is instantiated.
12173   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12174     ResolveExceptionSpec(D->getLocation(), FPT);
12175 
12176   // dllimport cannot be applied to non-inline function definitions.
12177   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12178       !FD->isTemplateInstantiation()) {
12179     assert(!FD->hasAttr<DLLExportAttr>());
12180     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12181     FD->setInvalidDecl();
12182     return D;
12183   }
12184   // We want to attach documentation to original Decl (which might be
12185   // a function template).
12186   ActOnDocumentableDecl(D);
12187   if (getCurLexicalContext()->isObjCContainer() &&
12188       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12189       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12190     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12191 
12192   return D;
12193 }
12194 
12195 /// \brief Given the set of return statements within a function body,
12196 /// compute the variables that are subject to the named return value
12197 /// optimization.
12198 ///
12199 /// Each of the variables that is subject to the named return value
12200 /// optimization will be marked as NRVO variables in the AST, and any
12201 /// return statement that has a marked NRVO variable as its NRVO candidate can
12202 /// use the named return value optimization.
12203 ///
12204 /// This function applies a very simplistic algorithm for NRVO: if every return
12205 /// statement in the scope of a variable has the same NRVO candidate, that
12206 /// candidate is an NRVO variable.
12207 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12208   ReturnStmt **Returns = Scope->Returns.data();
12209 
12210   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12211     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12212       if (!NRVOCandidate->isNRVOVariable())
12213         Returns[I]->setNRVOCandidate(nullptr);
12214     }
12215   }
12216 }
12217 
12218 bool Sema::canDelayFunctionBody(const Declarator &D) {
12219   // We can't delay parsing the body of a constexpr function template (yet).
12220   if (D.getDeclSpec().isConstexprSpecified())
12221     return false;
12222 
12223   // We can't delay parsing the body of a function template with a deduced
12224   // return type (yet).
12225   if (D.getDeclSpec().hasAutoTypeSpec()) {
12226     // If the placeholder introduces a non-deduced trailing return type,
12227     // we can still delay parsing it.
12228     if (D.getNumTypeObjects()) {
12229       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12230       if (Outer.Kind == DeclaratorChunk::Function &&
12231           Outer.Fun.hasTrailingReturnType()) {
12232         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12233         return Ty.isNull() || !Ty->isUndeducedType();
12234       }
12235     }
12236     return false;
12237   }
12238 
12239   return true;
12240 }
12241 
12242 bool Sema::canSkipFunctionBody(Decl *D) {
12243   // We cannot skip the body of a function (or function template) which is
12244   // constexpr, since we may need to evaluate its body in order to parse the
12245   // rest of the file.
12246   // We cannot skip the body of a function with an undeduced return type,
12247   // because any callers of that function need to know the type.
12248   if (const FunctionDecl *FD = D->getAsFunction())
12249     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12250       return false;
12251   return Consumer.shouldSkipFunctionBody(D);
12252 }
12253 
12254 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12255   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12256     FD->setHasSkippedBody();
12257   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12258     MD->setHasSkippedBody();
12259   return Decl;
12260 }
12261 
12262 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12263   return ActOnFinishFunctionBody(D, BodyArg, false);
12264 }
12265 
12266 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12267                                     bool IsInstantiation) {
12268   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12269 
12270   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12271   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12272 
12273   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12274     CheckCompletedCoroutineBody(FD, Body);
12275 
12276   if (FD) {
12277     FD->setBody(Body);
12278     FD->setWillHaveBody(false);
12279 
12280     if (getLangOpts().CPlusPlus14) {
12281       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12282           FD->getReturnType()->isUndeducedType()) {
12283         // If the function has a deduced result type but contains no 'return'
12284         // statements, the result type as written must be exactly 'auto', and
12285         // the deduced result type is 'void'.
12286         if (!FD->getReturnType()->getAs<AutoType>()) {
12287           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12288               << FD->getReturnType();
12289           FD->setInvalidDecl();
12290         } else {
12291           // Substitute 'void' for the 'auto' in the type.
12292           TypeLoc ResultType = getReturnTypeLoc(FD);
12293           Context.adjustDeducedFunctionResultType(
12294               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12295         }
12296       }
12297     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12298       // In C++11, we don't use 'auto' deduction rules for lambda call
12299       // operators because we don't support return type deduction.
12300       auto *LSI = getCurLambda();
12301       if (LSI->HasImplicitReturnType) {
12302         deduceClosureReturnType(*LSI);
12303 
12304         // C++11 [expr.prim.lambda]p4:
12305         //   [...] if there are no return statements in the compound-statement
12306         //   [the deduced type is] the type void
12307         QualType RetType =
12308             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12309 
12310         // Update the return type to the deduced type.
12311         const FunctionProtoType *Proto =
12312             FD->getType()->getAs<FunctionProtoType>();
12313         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12314                                             Proto->getExtProtoInfo()));
12315       }
12316     }
12317 
12318     // The only way to be included in UndefinedButUsed is if there is an
12319     // ODR use before the definition. Avoid the expensive map lookup if this
12320     // is the first declaration.
12321     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12322       if (!FD->isExternallyVisible())
12323         UndefinedButUsed.erase(FD);
12324       else if (FD->isInlined() &&
12325                !LangOpts.GNUInline &&
12326                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12327         UndefinedButUsed.erase(FD);
12328     }
12329 
12330     // If the function implicitly returns zero (like 'main') or is naked,
12331     // don't complain about missing return statements.
12332     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12333       WP.disableCheckFallThrough();
12334 
12335     // MSVC permits the use of pure specifier (=0) on function definition,
12336     // defined at class scope, warn about this non-standard construct.
12337     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12338       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12339 
12340     if (!FD->isInvalidDecl()) {
12341       // Don't diagnose unused parameters of defaulted or deleted functions.
12342       if (!FD->isDeleted() && !FD->isDefaulted())
12343         DiagnoseUnusedParameters(FD->parameters());
12344       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12345                                              FD->getReturnType(), FD);
12346 
12347       // If this is a structor, we need a vtable.
12348       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12349         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12350       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12351         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12352 
12353       // Try to apply the named return value optimization. We have to check
12354       // if we can do this here because lambdas keep return statements around
12355       // to deduce an implicit return type.
12356       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12357           !FD->isDependentContext())
12358         computeNRVO(Body, getCurFunction());
12359     }
12360 
12361     // GNU warning -Wmissing-prototypes:
12362     //   Warn if a global function is defined without a previous
12363     //   prototype declaration. This warning is issued even if the
12364     //   definition itself provides a prototype. The aim is to detect
12365     //   global functions that fail to be declared in header files.
12366     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12367     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12368       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12369 
12370       if (PossibleZeroParamPrototype) {
12371         // We found a declaration that is not a prototype,
12372         // but that could be a zero-parameter prototype
12373         if (TypeSourceInfo *TI =
12374                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12375           TypeLoc TL = TI->getTypeLoc();
12376           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12377             Diag(PossibleZeroParamPrototype->getLocation(),
12378                  diag::note_declaration_not_a_prototype)
12379                 << PossibleZeroParamPrototype
12380                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12381         }
12382       }
12383 
12384       // GNU warning -Wstrict-prototypes
12385       //   Warn if K&R function is defined without a previous declaration.
12386       //   This warning is issued only if the definition itself does not provide
12387       //   a prototype. Only K&R definitions do not provide a prototype.
12388       //   An empty list in a function declarator that is part of a definition
12389       //   of that function specifies that the function has no parameters
12390       //   (C99 6.7.5.3p14)
12391       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12392           !LangOpts.CPlusPlus) {
12393         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12394         TypeLoc TL = TI->getTypeLoc();
12395         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12396         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12397       }
12398     }
12399 
12400     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12401       const CXXMethodDecl *KeyFunction;
12402       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12403           MD->isVirtual() &&
12404           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12405           MD == KeyFunction->getCanonicalDecl()) {
12406         // Update the key-function state if necessary for this ABI.
12407         if (FD->isInlined() &&
12408             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12409           Context.setNonKeyFunction(MD);
12410 
12411           // If the newly-chosen key function is already defined, then we
12412           // need to mark the vtable as used retroactively.
12413           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12414           const FunctionDecl *Definition;
12415           if (KeyFunction && KeyFunction->isDefined(Definition))
12416             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12417         } else {
12418           // We just defined they key function; mark the vtable as used.
12419           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12420         }
12421       }
12422     }
12423 
12424     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12425            "Function parsing confused");
12426   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12427     assert(MD == getCurMethodDecl() && "Method parsing confused");
12428     MD->setBody(Body);
12429     if (!MD->isInvalidDecl()) {
12430       DiagnoseUnusedParameters(MD->parameters());
12431       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12432                                              MD->getReturnType(), MD);
12433 
12434       if (Body)
12435         computeNRVO(Body, getCurFunction());
12436     }
12437     if (getCurFunction()->ObjCShouldCallSuper) {
12438       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12439         << MD->getSelector().getAsString();
12440       getCurFunction()->ObjCShouldCallSuper = false;
12441     }
12442     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12443       const ObjCMethodDecl *InitMethod = nullptr;
12444       bool isDesignated =
12445           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12446       assert(isDesignated && InitMethod);
12447       (void)isDesignated;
12448 
12449       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12450         auto IFace = MD->getClassInterface();
12451         if (!IFace)
12452           return false;
12453         auto SuperD = IFace->getSuperClass();
12454         if (!SuperD)
12455           return false;
12456         return SuperD->getIdentifier() ==
12457             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12458       };
12459       // Don't issue this warning for unavailable inits or direct subclasses
12460       // of NSObject.
12461       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12462         Diag(MD->getLocation(),
12463              diag::warn_objc_designated_init_missing_super_call);
12464         Diag(InitMethod->getLocation(),
12465              diag::note_objc_designated_init_marked_here);
12466       }
12467       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12468     }
12469     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12470       // Don't issue this warning for unavaialable inits.
12471       if (!MD->isUnavailable())
12472         Diag(MD->getLocation(),
12473              diag::warn_objc_secondary_init_missing_init_call);
12474       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12475     }
12476   } else {
12477     return nullptr;
12478   }
12479 
12480   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12481     DiagnoseUnguardedAvailabilityViolations(dcl);
12482 
12483   assert(!getCurFunction()->ObjCShouldCallSuper &&
12484          "This should only be set for ObjC methods, which should have been "
12485          "handled in the block above.");
12486 
12487   // Verify and clean out per-function state.
12488   if (Body && (!FD || !FD->isDefaulted())) {
12489     // C++ constructors that have function-try-blocks can't have return
12490     // statements in the handlers of that block. (C++ [except.handle]p14)
12491     // Verify this.
12492     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12493       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12494 
12495     // Verify that gotos and switch cases don't jump into scopes illegally.
12496     if (getCurFunction()->NeedsScopeChecking() &&
12497         !PP.isCodeCompletionEnabled())
12498       DiagnoseInvalidJumps(Body);
12499 
12500     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12501       if (!Destructor->getParent()->isDependentType())
12502         CheckDestructor(Destructor);
12503 
12504       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12505                                              Destructor->getParent());
12506     }
12507 
12508     // If any errors have occurred, clear out any temporaries that may have
12509     // been leftover. This ensures that these temporaries won't be picked up for
12510     // deletion in some later function.
12511     if (getDiagnostics().hasErrorOccurred() ||
12512         getDiagnostics().getSuppressAllDiagnostics()) {
12513       DiscardCleanupsInEvaluationContext();
12514     }
12515     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12516         !isa<FunctionTemplateDecl>(dcl)) {
12517       // Since the body is valid, issue any analysis-based warnings that are
12518       // enabled.
12519       ActivePolicy = &WP;
12520     }
12521 
12522     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12523         (!CheckConstexprFunctionDecl(FD) ||
12524          !CheckConstexprFunctionBody(FD, Body)))
12525       FD->setInvalidDecl();
12526 
12527     if (FD && FD->hasAttr<NakedAttr>()) {
12528       for (const Stmt *S : Body->children()) {
12529         // Allow local register variables without initializer as they don't
12530         // require prologue.
12531         bool RegisterVariables = false;
12532         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12533           for (const auto *Decl : DS->decls()) {
12534             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12535               RegisterVariables =
12536                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12537               if (!RegisterVariables)
12538                 break;
12539             }
12540           }
12541         }
12542         if (RegisterVariables)
12543           continue;
12544         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12545           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12546           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12547           FD->setInvalidDecl();
12548           break;
12549         }
12550       }
12551     }
12552 
12553     assert(ExprCleanupObjects.size() ==
12554                ExprEvalContexts.back().NumCleanupObjects &&
12555            "Leftover temporaries in function");
12556     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12557     assert(MaybeODRUseExprs.empty() &&
12558            "Leftover expressions for odr-use checking");
12559   }
12560 
12561   if (!IsInstantiation)
12562     PopDeclContext();
12563 
12564   PopFunctionScopeInfo(ActivePolicy, dcl);
12565   // If any errors have occurred, clear out any temporaries that may have
12566   // been leftover. This ensures that these temporaries won't be picked up for
12567   // deletion in some later function.
12568   if (getDiagnostics().hasErrorOccurred()) {
12569     DiscardCleanupsInEvaluationContext();
12570   }
12571 
12572   return dcl;
12573 }
12574 
12575 /// When we finish delayed parsing of an attribute, we must attach it to the
12576 /// relevant Decl.
12577 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12578                                        ParsedAttributes &Attrs) {
12579   // Always attach attributes to the underlying decl.
12580   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12581     D = TD->getTemplatedDecl();
12582   ProcessDeclAttributeList(S, D, Attrs.getList());
12583 
12584   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12585     if (Method->isStatic())
12586       checkThisInStaticMemberFunctionAttributes(Method);
12587 }
12588 
12589 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12590 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12591 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12592                                           IdentifierInfo &II, Scope *S) {
12593   // Before we produce a declaration for an implicitly defined
12594   // function, see whether there was a locally-scoped declaration of
12595   // this name as a function or variable. If so, use that
12596   // (non-visible) declaration, and complain about it.
12597   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12598     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12599     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12600     return ExternCPrev;
12601   }
12602 
12603   // Extension in C99.  Legal in C90, but warn about it.
12604   unsigned diag_id;
12605   if (II.getName().startswith("__builtin_"))
12606     diag_id = diag::warn_builtin_unknown;
12607   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12608   else if (getLangOpts().OpenCL)
12609     diag_id = diag::err_opencl_implicit_function_decl;
12610   else if (getLangOpts().C99)
12611     diag_id = diag::ext_implicit_function_decl;
12612   else
12613     diag_id = diag::warn_implicit_function_decl;
12614   Diag(Loc, diag_id) << &II;
12615 
12616   // Because typo correction is expensive, only do it if the implicit
12617   // function declaration is going to be treated as an error.
12618   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12619     TypoCorrection Corrected;
12620     if (S &&
12621         (Corrected = CorrectTypo(
12622              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12623              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12624       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12625                    /*ErrorRecovery*/false);
12626   }
12627 
12628   // Set a Declarator for the implicit definition: int foo();
12629   const char *Dummy;
12630   AttributeFactory attrFactory;
12631   DeclSpec DS(attrFactory);
12632   unsigned DiagID;
12633   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12634                                   Context.getPrintingPolicy());
12635   (void)Error; // Silence warning.
12636   assert(!Error && "Error setting up implicit decl!");
12637   SourceLocation NoLoc;
12638   Declarator D(DS, Declarator::BlockContext);
12639   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12640                                              /*IsAmbiguous=*/false,
12641                                              /*LParenLoc=*/NoLoc,
12642                                              /*Params=*/nullptr,
12643                                              /*NumParams=*/0,
12644                                              /*EllipsisLoc=*/NoLoc,
12645                                              /*RParenLoc=*/NoLoc,
12646                                              /*TypeQuals=*/0,
12647                                              /*RefQualifierIsLvalueRef=*/true,
12648                                              /*RefQualifierLoc=*/NoLoc,
12649                                              /*ConstQualifierLoc=*/NoLoc,
12650                                              /*VolatileQualifierLoc=*/NoLoc,
12651                                              /*RestrictQualifierLoc=*/NoLoc,
12652                                              /*MutableLoc=*/NoLoc,
12653                                              EST_None,
12654                                              /*ESpecRange=*/SourceRange(),
12655                                              /*Exceptions=*/nullptr,
12656                                              /*ExceptionRanges=*/nullptr,
12657                                              /*NumExceptions=*/0,
12658                                              /*NoexceptExpr=*/nullptr,
12659                                              /*ExceptionSpecTokens=*/nullptr,
12660                                              /*DeclsInPrototype=*/None,
12661                                              Loc, Loc, D),
12662                 DS.getAttributes(),
12663                 SourceLocation());
12664   D.SetIdentifier(&II, Loc);
12665 
12666   // Insert this function into translation-unit scope.
12667 
12668   DeclContext *PrevDC = CurContext;
12669   CurContext = Context.getTranslationUnitDecl();
12670 
12671   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12672   FD->setImplicit();
12673 
12674   CurContext = PrevDC;
12675 
12676   AddKnownFunctionAttributes(FD);
12677 
12678   return FD;
12679 }
12680 
12681 /// \brief Adds any function attributes that we know a priori based on
12682 /// the declaration of this function.
12683 ///
12684 /// These attributes can apply both to implicitly-declared builtins
12685 /// (like __builtin___printf_chk) or to library-declared functions
12686 /// like NSLog or printf.
12687 ///
12688 /// We need to check for duplicate attributes both here and where user-written
12689 /// attributes are applied to declarations.
12690 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12691   if (FD->isInvalidDecl())
12692     return;
12693 
12694   // If this is a built-in function, map its builtin attributes to
12695   // actual attributes.
12696   if (unsigned BuiltinID = FD->getBuiltinID()) {
12697     // Handle printf-formatting attributes.
12698     unsigned FormatIdx;
12699     bool HasVAListArg;
12700     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12701       if (!FD->hasAttr<FormatAttr>()) {
12702         const char *fmt = "printf";
12703         unsigned int NumParams = FD->getNumParams();
12704         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12705             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12706           fmt = "NSString";
12707         FD->addAttr(FormatAttr::CreateImplicit(Context,
12708                                                &Context.Idents.get(fmt),
12709                                                FormatIdx+1,
12710                                                HasVAListArg ? 0 : FormatIdx+2,
12711                                                FD->getLocation()));
12712       }
12713     }
12714     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12715                                              HasVAListArg)) {
12716      if (!FD->hasAttr<FormatAttr>())
12717        FD->addAttr(FormatAttr::CreateImplicit(Context,
12718                                               &Context.Idents.get("scanf"),
12719                                               FormatIdx+1,
12720                                               HasVAListArg ? 0 : FormatIdx+2,
12721                                               FD->getLocation()));
12722     }
12723 
12724     // Mark const if we don't care about errno and that is the only
12725     // thing preventing the function from being const. This allows
12726     // IRgen to use LLVM intrinsics for such functions.
12727     if (!getLangOpts().MathErrno &&
12728         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12729       if (!FD->hasAttr<ConstAttr>())
12730         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12731     }
12732 
12733     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12734         !FD->hasAttr<ReturnsTwiceAttr>())
12735       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12736                                          FD->getLocation()));
12737     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12738       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12739     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12740       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12741     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12742       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12743     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12744         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12745       // Add the appropriate attribute, depending on the CUDA compilation mode
12746       // and which target the builtin belongs to. For example, during host
12747       // compilation, aux builtins are __device__, while the rest are __host__.
12748       if (getLangOpts().CUDAIsDevice !=
12749           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12750         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12751       else
12752         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12753     }
12754   }
12755 
12756   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12757   // throw, add an implicit nothrow attribute to any extern "C" function we come
12758   // across.
12759   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12760       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12761     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12762     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12763       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12764   }
12765 
12766   IdentifierInfo *Name = FD->getIdentifier();
12767   if (!Name)
12768     return;
12769   if ((!getLangOpts().CPlusPlus &&
12770        FD->getDeclContext()->isTranslationUnit()) ||
12771       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12772        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12773        LinkageSpecDecl::lang_c)) {
12774     // Okay: this could be a libc/libm/Objective-C function we know
12775     // about.
12776   } else
12777     return;
12778 
12779   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12780     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12781     // target-specific builtins, perhaps?
12782     if (!FD->hasAttr<FormatAttr>())
12783       FD->addAttr(FormatAttr::CreateImplicit(Context,
12784                                              &Context.Idents.get("printf"), 2,
12785                                              Name->isStr("vasprintf") ? 0 : 3,
12786                                              FD->getLocation()));
12787   }
12788 
12789   if (Name->isStr("__CFStringMakeConstantString")) {
12790     // We already have a __builtin___CFStringMakeConstantString,
12791     // but builds that use -fno-constant-cfstrings don't go through that.
12792     if (!FD->hasAttr<FormatArgAttr>())
12793       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12794                                                 FD->getLocation()));
12795   }
12796 }
12797 
12798 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12799                                     TypeSourceInfo *TInfo) {
12800   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12801   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12802 
12803   if (!TInfo) {
12804     assert(D.isInvalidType() && "no declarator info for valid type");
12805     TInfo = Context.getTrivialTypeSourceInfo(T);
12806   }
12807 
12808   // Scope manipulation handled by caller.
12809   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12810                                            D.getLocStart(),
12811                                            D.getIdentifierLoc(),
12812                                            D.getIdentifier(),
12813                                            TInfo);
12814 
12815   // Bail out immediately if we have an invalid declaration.
12816   if (D.isInvalidType()) {
12817     NewTD->setInvalidDecl();
12818     return NewTD;
12819   }
12820 
12821   if (D.getDeclSpec().isModulePrivateSpecified()) {
12822     if (CurContext->isFunctionOrMethod())
12823       Diag(NewTD->getLocation(), diag::err_module_private_local)
12824         << 2 << NewTD->getDeclName()
12825         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12826         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12827     else
12828       NewTD->setModulePrivate();
12829   }
12830 
12831   // C++ [dcl.typedef]p8:
12832   //   If the typedef declaration defines an unnamed class (or
12833   //   enum), the first typedef-name declared by the declaration
12834   //   to be that class type (or enum type) is used to denote the
12835   //   class type (or enum type) for linkage purposes only.
12836   // We need to check whether the type was declared in the declaration.
12837   switch (D.getDeclSpec().getTypeSpecType()) {
12838   case TST_enum:
12839   case TST_struct:
12840   case TST_interface:
12841   case TST_union:
12842   case TST_class: {
12843     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12844     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12845     break;
12846   }
12847 
12848   default:
12849     break;
12850   }
12851 
12852   return NewTD;
12853 }
12854 
12855 /// \brief Check that this is a valid underlying type for an enum declaration.
12856 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12857   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12858   QualType T = TI->getType();
12859 
12860   if (T->isDependentType())
12861     return false;
12862 
12863   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12864     if (BT->isInteger())
12865       return false;
12866 
12867   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12868   return true;
12869 }
12870 
12871 /// Check whether this is a valid redeclaration of a previous enumeration.
12872 /// \return true if the redeclaration was invalid.
12873 bool Sema::CheckEnumRedeclaration(
12874     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12875     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12876   bool IsFixed = !EnumUnderlyingTy.isNull();
12877 
12878   if (IsScoped != Prev->isScoped()) {
12879     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12880       << Prev->isScoped();
12881     Diag(Prev->getLocation(), diag::note_previous_declaration);
12882     return true;
12883   }
12884 
12885   if (IsFixed && Prev->isFixed()) {
12886     if (!EnumUnderlyingTy->isDependentType() &&
12887         !Prev->getIntegerType()->isDependentType() &&
12888         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12889                                         Prev->getIntegerType())) {
12890       // TODO: Highlight the underlying type of the redeclaration.
12891       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12892         << EnumUnderlyingTy << Prev->getIntegerType();
12893       Diag(Prev->getLocation(), diag::note_previous_declaration)
12894           << Prev->getIntegerTypeRange();
12895       return true;
12896     }
12897   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12898     ;
12899   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12900     ;
12901   } else if (IsFixed != Prev->isFixed()) {
12902     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12903       << Prev->isFixed();
12904     Diag(Prev->getLocation(), diag::note_previous_declaration);
12905     return true;
12906   }
12907 
12908   return false;
12909 }
12910 
12911 /// \brief Get diagnostic %select index for tag kind for
12912 /// redeclaration diagnostic message.
12913 /// WARNING: Indexes apply to particular diagnostics only!
12914 ///
12915 /// \returns diagnostic %select index.
12916 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12917   switch (Tag) {
12918   case TTK_Struct: return 0;
12919   case TTK_Interface: return 1;
12920   case TTK_Class:  return 2;
12921   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12922   }
12923 }
12924 
12925 /// \brief Determine if tag kind is a class-key compatible with
12926 /// class for redeclaration (class, struct, or __interface).
12927 ///
12928 /// \returns true iff the tag kind is compatible.
12929 static bool isClassCompatTagKind(TagTypeKind Tag)
12930 {
12931   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12932 }
12933 
12934 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12935                                              TagTypeKind TTK) {
12936   if (isa<TypedefDecl>(PrevDecl))
12937     return NTK_Typedef;
12938   else if (isa<TypeAliasDecl>(PrevDecl))
12939     return NTK_TypeAlias;
12940   else if (isa<ClassTemplateDecl>(PrevDecl))
12941     return NTK_Template;
12942   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12943     return NTK_TypeAliasTemplate;
12944   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12945     return NTK_TemplateTemplateArgument;
12946   switch (TTK) {
12947   case TTK_Struct:
12948   case TTK_Interface:
12949   case TTK_Class:
12950     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12951   case TTK_Union:
12952     return NTK_NonUnion;
12953   case TTK_Enum:
12954     return NTK_NonEnum;
12955   }
12956   llvm_unreachable("invalid TTK");
12957 }
12958 
12959 /// \brief Determine whether a tag with a given kind is acceptable
12960 /// as a redeclaration of the given tag declaration.
12961 ///
12962 /// \returns true if the new tag kind is acceptable, false otherwise.
12963 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12964                                         TagTypeKind NewTag, bool isDefinition,
12965                                         SourceLocation NewTagLoc,
12966                                         const IdentifierInfo *Name) {
12967   // C++ [dcl.type.elab]p3:
12968   //   The class-key or enum keyword present in the
12969   //   elaborated-type-specifier shall agree in kind with the
12970   //   declaration to which the name in the elaborated-type-specifier
12971   //   refers. This rule also applies to the form of
12972   //   elaborated-type-specifier that declares a class-name or
12973   //   friend class since it can be construed as referring to the
12974   //   definition of the class. Thus, in any
12975   //   elaborated-type-specifier, the enum keyword shall be used to
12976   //   refer to an enumeration (7.2), the union class-key shall be
12977   //   used to refer to a union (clause 9), and either the class or
12978   //   struct class-key shall be used to refer to a class (clause 9)
12979   //   declared using the class or struct class-key.
12980   TagTypeKind OldTag = Previous->getTagKind();
12981   if (!isDefinition || !isClassCompatTagKind(NewTag))
12982     if (OldTag == NewTag)
12983       return true;
12984 
12985   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12986     // Warn about the struct/class tag mismatch.
12987     bool isTemplate = false;
12988     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12989       isTemplate = Record->getDescribedClassTemplate();
12990 
12991     if (inTemplateInstantiation()) {
12992       // In a template instantiation, do not offer fix-its for tag mismatches
12993       // since they usually mess up the template instead of fixing the problem.
12994       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12995         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12996         << getRedeclDiagFromTagKind(OldTag);
12997       return true;
12998     }
12999 
13000     if (isDefinition) {
13001       // On definitions, check previous tags and issue a fix-it for each
13002       // one that doesn't match the current tag.
13003       if (Previous->getDefinition()) {
13004         // Don't suggest fix-its for redefinitions.
13005         return true;
13006       }
13007 
13008       bool previousMismatch = false;
13009       for (auto I : Previous->redecls()) {
13010         if (I->getTagKind() != NewTag) {
13011           if (!previousMismatch) {
13012             previousMismatch = true;
13013             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13014               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13015               << getRedeclDiagFromTagKind(I->getTagKind());
13016           }
13017           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13018             << getRedeclDiagFromTagKind(NewTag)
13019             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13020                  TypeWithKeyword::getTagTypeKindName(NewTag));
13021         }
13022       }
13023       return true;
13024     }
13025 
13026     // Check for a previous definition.  If current tag and definition
13027     // are same type, do nothing.  If no definition, but disagree with
13028     // with previous tag type, give a warning, but no fix-it.
13029     const TagDecl *Redecl = Previous->getDefinition() ?
13030                             Previous->getDefinition() : Previous;
13031     if (Redecl->getTagKind() == NewTag) {
13032       return true;
13033     }
13034 
13035     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13036       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13037       << getRedeclDiagFromTagKind(OldTag);
13038     Diag(Redecl->getLocation(), diag::note_previous_use);
13039 
13040     // If there is a previous definition, suggest a fix-it.
13041     if (Previous->getDefinition()) {
13042         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13043           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13044           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13045                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13046     }
13047 
13048     return true;
13049   }
13050   return false;
13051 }
13052 
13053 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13054 /// from an outer enclosing namespace or file scope inside a friend declaration.
13055 /// This should provide the commented out code in the following snippet:
13056 ///   namespace N {
13057 ///     struct X;
13058 ///     namespace M {
13059 ///       struct Y { friend struct /*N::*/ X; };
13060 ///     }
13061 ///   }
13062 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13063                                          SourceLocation NameLoc) {
13064   // While the decl is in a namespace, do repeated lookup of that name and see
13065   // if we get the same namespace back.  If we do not, continue until
13066   // translation unit scope, at which point we have a fully qualified NNS.
13067   SmallVector<IdentifierInfo *, 4> Namespaces;
13068   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13069   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13070     // This tag should be declared in a namespace, which can only be enclosed by
13071     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13072     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13073     if (!Namespace || Namespace->isAnonymousNamespace())
13074       return FixItHint();
13075     IdentifierInfo *II = Namespace->getIdentifier();
13076     Namespaces.push_back(II);
13077     NamedDecl *Lookup = SemaRef.LookupSingleName(
13078         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13079     if (Lookup == Namespace)
13080       break;
13081   }
13082 
13083   // Once we have all the namespaces, reverse them to go outermost first, and
13084   // build an NNS.
13085   SmallString<64> Insertion;
13086   llvm::raw_svector_ostream OS(Insertion);
13087   if (DC->isTranslationUnit())
13088     OS << "::";
13089   std::reverse(Namespaces.begin(), Namespaces.end());
13090   for (auto *II : Namespaces)
13091     OS << II->getName() << "::";
13092   return FixItHint::CreateInsertion(NameLoc, Insertion);
13093 }
13094 
13095 /// \brief Determine whether a tag originally declared in context \p OldDC can
13096 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13097 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13098 /// using-declaration).
13099 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13100                                          DeclContext *NewDC) {
13101   OldDC = OldDC->getRedeclContext();
13102   NewDC = NewDC->getRedeclContext();
13103 
13104   if (OldDC->Equals(NewDC))
13105     return true;
13106 
13107   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13108   // encloses the other).
13109   if (S.getLangOpts().MSVCCompat &&
13110       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13111     return true;
13112 
13113   return false;
13114 }
13115 
13116 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13117 /// former case, Name will be non-null.  In the later case, Name will be null.
13118 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13119 /// reference/declaration/definition of a tag.
13120 ///
13121 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13122 /// trailing-type-specifier) other than one in an alias-declaration.
13123 ///
13124 /// \param SkipBody If non-null, will be set to indicate if the caller should
13125 /// skip the definition of this tag and treat it as if it were a declaration.
13126 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13127                      SourceLocation KWLoc, CXXScopeSpec &SS,
13128                      IdentifierInfo *Name, SourceLocation NameLoc,
13129                      AttributeList *Attr, AccessSpecifier AS,
13130                      SourceLocation ModulePrivateLoc,
13131                      MultiTemplateParamsArg TemplateParameterLists,
13132                      bool &OwnedDecl, bool &IsDependent,
13133                      SourceLocation ScopedEnumKWLoc,
13134                      bool ScopedEnumUsesClassTag,
13135                      TypeResult UnderlyingType,
13136                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13137                      SkipBodyInfo *SkipBody) {
13138   // If this is not a definition, it must have a name.
13139   IdentifierInfo *OrigName = Name;
13140   assert((Name != nullptr || TUK == TUK_Definition) &&
13141          "Nameless record must be a definition!");
13142   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13143 
13144   OwnedDecl = false;
13145   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13146   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13147 
13148   // FIXME: Check member specializations more carefully.
13149   bool isMemberSpecialization = false;
13150   bool Invalid = false;
13151 
13152   // We only need to do this matching if we have template parameters
13153   // or a scope specifier, which also conveniently avoids this work
13154   // for non-C++ cases.
13155   if (TemplateParameterLists.size() > 0 ||
13156       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13157     if (TemplateParameterList *TemplateParams =
13158             MatchTemplateParametersToScopeSpecifier(
13159                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13160                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13161       if (Kind == TTK_Enum) {
13162         Diag(KWLoc, diag::err_enum_template);
13163         return nullptr;
13164       }
13165 
13166       if (TemplateParams->size() > 0) {
13167         // This is a declaration or definition of a class template (which may
13168         // be a member of another template).
13169 
13170         if (Invalid)
13171           return nullptr;
13172 
13173         OwnedDecl = false;
13174         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13175                                                SS, Name, NameLoc, Attr,
13176                                                TemplateParams, AS,
13177                                                ModulePrivateLoc,
13178                                                /*FriendLoc*/SourceLocation(),
13179                                                TemplateParameterLists.size()-1,
13180                                                TemplateParameterLists.data(),
13181                                                SkipBody);
13182         return Result.get();
13183       } else {
13184         // The "template<>" header is extraneous.
13185         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13186           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13187         isMemberSpecialization = true;
13188       }
13189     }
13190   }
13191 
13192   // Figure out the underlying type if this a enum declaration. We need to do
13193   // this early, because it's needed to detect if this is an incompatible
13194   // redeclaration.
13195   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13196   bool EnumUnderlyingIsImplicit = false;
13197 
13198   if (Kind == TTK_Enum) {
13199     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13200       // No underlying type explicitly specified, or we failed to parse the
13201       // type, default to int.
13202       EnumUnderlying = Context.IntTy.getTypePtr();
13203     else if (UnderlyingType.get()) {
13204       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13205       // integral type; any cv-qualification is ignored.
13206       TypeSourceInfo *TI = nullptr;
13207       GetTypeFromParser(UnderlyingType.get(), &TI);
13208       EnumUnderlying = TI;
13209 
13210       if (CheckEnumUnderlyingType(TI))
13211         // Recover by falling back to int.
13212         EnumUnderlying = Context.IntTy.getTypePtr();
13213 
13214       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13215                                           UPPC_FixedUnderlyingType))
13216         EnumUnderlying = Context.IntTy.getTypePtr();
13217 
13218     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13219       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13220         // Microsoft enums are always of int type.
13221         EnumUnderlying = Context.IntTy.getTypePtr();
13222         EnumUnderlyingIsImplicit = true;
13223       }
13224     }
13225   }
13226 
13227   DeclContext *SearchDC = CurContext;
13228   DeclContext *DC = CurContext;
13229   bool isStdBadAlloc = false;
13230   bool isStdAlignValT = false;
13231 
13232   RedeclarationKind Redecl = ForRedeclaration;
13233   if (TUK == TUK_Friend || TUK == TUK_Reference)
13234     Redecl = NotForRedeclaration;
13235 
13236   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13237   /// implemented asks for structural equivalence checking, the returned decl
13238   /// here is passed back to the parser, allowing the tag body to be parsed.
13239   auto createTagFromNewDecl = [&]() -> TagDecl * {
13240     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13241     // If there is an identifier, use the location of the identifier as the
13242     // location of the decl, otherwise use the location of the struct/union
13243     // keyword.
13244     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13245     TagDecl *New = nullptr;
13246 
13247     if (Kind == TTK_Enum) {
13248       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13249                              ScopedEnum, ScopedEnumUsesClassTag,
13250                              !EnumUnderlying.isNull());
13251       // If this is an undefined enum, bail.
13252       if (TUK != TUK_Definition && !Invalid)
13253         return nullptr;
13254       if (EnumUnderlying) {
13255         EnumDecl *ED = cast<EnumDecl>(New);
13256         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13257           ED->setIntegerTypeSourceInfo(TI);
13258         else
13259           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13260         ED->setPromotionType(ED->getIntegerType());
13261       }
13262     } else { // struct/union
13263       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13264                                nullptr);
13265     }
13266 
13267     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13268       // Add alignment attributes if necessary; these attributes are checked
13269       // when the ASTContext lays out the structure.
13270       //
13271       // It is important for implementing the correct semantics that this
13272       // happen here (in ActOnTag). The #pragma pack stack is
13273       // maintained as a result of parser callbacks which can occur at
13274       // many points during the parsing of a struct declaration (because
13275       // the #pragma tokens are effectively skipped over during the
13276       // parsing of the struct).
13277       if (TUK == TUK_Definition) {
13278         AddAlignmentAttributesForRecord(RD);
13279         AddMsStructLayoutForRecord(RD);
13280       }
13281     }
13282     return New;
13283   };
13284 
13285   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13286   if (Name && SS.isNotEmpty()) {
13287     // We have a nested-name tag ('struct foo::bar').
13288 
13289     // Check for invalid 'foo::'.
13290     if (SS.isInvalid()) {
13291       Name = nullptr;
13292       goto CreateNewDecl;
13293     }
13294 
13295     // If this is a friend or a reference to a class in a dependent
13296     // context, don't try to make a decl for it.
13297     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13298       DC = computeDeclContext(SS, false);
13299       if (!DC) {
13300         IsDependent = true;
13301         return nullptr;
13302       }
13303     } else {
13304       DC = computeDeclContext(SS, true);
13305       if (!DC) {
13306         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13307           << SS.getRange();
13308         return nullptr;
13309       }
13310     }
13311 
13312     if (RequireCompleteDeclContext(SS, DC))
13313       return nullptr;
13314 
13315     SearchDC = DC;
13316     // Look-up name inside 'foo::'.
13317     LookupQualifiedName(Previous, DC);
13318 
13319     if (Previous.isAmbiguous())
13320       return nullptr;
13321 
13322     if (Previous.empty()) {
13323       // Name lookup did not find anything. However, if the
13324       // nested-name-specifier refers to the current instantiation,
13325       // and that current instantiation has any dependent base
13326       // classes, we might find something at instantiation time: treat
13327       // this as a dependent elaborated-type-specifier.
13328       // But this only makes any sense for reference-like lookups.
13329       if (Previous.wasNotFoundInCurrentInstantiation() &&
13330           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13331         IsDependent = true;
13332         return nullptr;
13333       }
13334 
13335       // A tag 'foo::bar' must already exist.
13336       Diag(NameLoc, diag::err_not_tag_in_scope)
13337         << Kind << Name << DC << SS.getRange();
13338       Name = nullptr;
13339       Invalid = true;
13340       goto CreateNewDecl;
13341     }
13342   } else if (Name) {
13343     // C++14 [class.mem]p14:
13344     //   If T is the name of a class, then each of the following shall have a
13345     //   name different from T:
13346     //    -- every member of class T that is itself a type
13347     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13348         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13349       return nullptr;
13350 
13351     // If this is a named struct, check to see if there was a previous forward
13352     // declaration or definition.
13353     // FIXME: We're looking into outer scopes here, even when we
13354     // shouldn't be. Doing so can result in ambiguities that we
13355     // shouldn't be diagnosing.
13356     LookupName(Previous, S);
13357 
13358     // When declaring or defining a tag, ignore ambiguities introduced
13359     // by types using'ed into this scope.
13360     if (Previous.isAmbiguous() &&
13361         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13362       LookupResult::Filter F = Previous.makeFilter();
13363       while (F.hasNext()) {
13364         NamedDecl *ND = F.next();
13365         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13366                 SearchDC->getRedeclContext()))
13367           F.erase();
13368       }
13369       F.done();
13370     }
13371 
13372     // C++11 [namespace.memdef]p3:
13373     //   If the name in a friend declaration is neither qualified nor
13374     //   a template-id and the declaration is a function or an
13375     //   elaborated-type-specifier, the lookup to determine whether
13376     //   the entity has been previously declared shall not consider
13377     //   any scopes outside the innermost enclosing namespace.
13378     //
13379     // MSVC doesn't implement the above rule for types, so a friend tag
13380     // declaration may be a redeclaration of a type declared in an enclosing
13381     // scope.  They do implement this rule for friend functions.
13382     //
13383     // Does it matter that this should be by scope instead of by
13384     // semantic context?
13385     if (!Previous.empty() && TUK == TUK_Friend) {
13386       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13387       LookupResult::Filter F = Previous.makeFilter();
13388       bool FriendSawTagOutsideEnclosingNamespace = false;
13389       while (F.hasNext()) {
13390         NamedDecl *ND = F.next();
13391         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13392         if (DC->isFileContext() &&
13393             !EnclosingNS->Encloses(ND->getDeclContext())) {
13394           if (getLangOpts().MSVCCompat)
13395             FriendSawTagOutsideEnclosingNamespace = true;
13396           else
13397             F.erase();
13398         }
13399       }
13400       F.done();
13401 
13402       // Diagnose this MSVC extension in the easy case where lookup would have
13403       // unambiguously found something outside the enclosing namespace.
13404       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13405         NamedDecl *ND = Previous.getFoundDecl();
13406         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13407             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13408       }
13409     }
13410 
13411     // Note:  there used to be some attempt at recovery here.
13412     if (Previous.isAmbiguous())
13413       return nullptr;
13414 
13415     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13416       // FIXME: This makes sure that we ignore the contexts associated
13417       // with C structs, unions, and enums when looking for a matching
13418       // tag declaration or definition. See the similar lookup tweak
13419       // in Sema::LookupName; is there a better way to deal with this?
13420       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13421         SearchDC = SearchDC->getParent();
13422     }
13423   }
13424 
13425   if (Previous.isSingleResult() &&
13426       Previous.getFoundDecl()->isTemplateParameter()) {
13427     // Maybe we will complain about the shadowed template parameter.
13428     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13429     // Just pretend that we didn't see the previous declaration.
13430     Previous.clear();
13431   }
13432 
13433   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13434       DC->Equals(getStdNamespace())) {
13435     if (Name->isStr("bad_alloc")) {
13436       // This is a declaration of or a reference to "std::bad_alloc".
13437       isStdBadAlloc = true;
13438 
13439       // If std::bad_alloc has been implicitly declared (but made invisible to
13440       // name lookup), fill in this implicit declaration as the previous
13441       // declaration, so that the declarations get chained appropriately.
13442       if (Previous.empty() && StdBadAlloc)
13443         Previous.addDecl(getStdBadAlloc());
13444     } else if (Name->isStr("align_val_t")) {
13445       isStdAlignValT = true;
13446       if (Previous.empty() && StdAlignValT)
13447         Previous.addDecl(getStdAlignValT());
13448     }
13449   }
13450 
13451   // If we didn't find a previous declaration, and this is a reference
13452   // (or friend reference), move to the correct scope.  In C++, we
13453   // also need to do a redeclaration lookup there, just in case
13454   // there's a shadow friend decl.
13455   if (Name && Previous.empty() &&
13456       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13457     if (Invalid) goto CreateNewDecl;
13458     assert(SS.isEmpty());
13459 
13460     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13461       // C++ [basic.scope.pdecl]p5:
13462       //   -- for an elaborated-type-specifier of the form
13463       //
13464       //          class-key identifier
13465       //
13466       //      if the elaborated-type-specifier is used in the
13467       //      decl-specifier-seq or parameter-declaration-clause of a
13468       //      function defined in namespace scope, the identifier is
13469       //      declared as a class-name in the namespace that contains
13470       //      the declaration; otherwise, except as a friend
13471       //      declaration, the identifier is declared in the smallest
13472       //      non-class, non-function-prototype scope that contains the
13473       //      declaration.
13474       //
13475       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13476       // C structs and unions.
13477       //
13478       // It is an error in C++ to declare (rather than define) an enum
13479       // type, including via an elaborated type specifier.  We'll
13480       // diagnose that later; for now, declare the enum in the same
13481       // scope as we would have picked for any other tag type.
13482       //
13483       // GNU C also supports this behavior as part of its incomplete
13484       // enum types extension, while GNU C++ does not.
13485       //
13486       // Find the context where we'll be declaring the tag.
13487       // FIXME: We would like to maintain the current DeclContext as the
13488       // lexical context,
13489       SearchDC = getTagInjectionContext(SearchDC);
13490 
13491       // Find the scope where we'll be declaring the tag.
13492       S = getTagInjectionScope(S, getLangOpts());
13493     } else {
13494       assert(TUK == TUK_Friend);
13495       // C++ [namespace.memdef]p3:
13496       //   If a friend declaration in a non-local class first declares a
13497       //   class or function, the friend class or function is a member of
13498       //   the innermost enclosing namespace.
13499       SearchDC = SearchDC->getEnclosingNamespaceContext();
13500     }
13501 
13502     // In C++, we need to do a redeclaration lookup to properly
13503     // diagnose some problems.
13504     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13505     // hidden declaration so that we don't get ambiguity errors when using a
13506     // type declared by an elaborated-type-specifier.  In C that is not correct
13507     // and we should instead merge compatible types found by lookup.
13508     if (getLangOpts().CPlusPlus) {
13509       Previous.setRedeclarationKind(ForRedeclaration);
13510       LookupQualifiedName(Previous, SearchDC);
13511     } else {
13512       Previous.setRedeclarationKind(ForRedeclaration);
13513       LookupName(Previous, S);
13514     }
13515   }
13516 
13517   // If we have a known previous declaration to use, then use it.
13518   if (Previous.empty() && SkipBody && SkipBody->Previous)
13519     Previous.addDecl(SkipBody->Previous);
13520 
13521   if (!Previous.empty()) {
13522     NamedDecl *PrevDecl = Previous.getFoundDecl();
13523     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13524 
13525     // It's okay to have a tag decl in the same scope as a typedef
13526     // which hides a tag decl in the same scope.  Finding this
13527     // insanity with a redeclaration lookup can only actually happen
13528     // in C++.
13529     //
13530     // This is also okay for elaborated-type-specifiers, which is
13531     // technically forbidden by the current standard but which is
13532     // okay according to the likely resolution of an open issue;
13533     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13534     if (getLangOpts().CPlusPlus) {
13535       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13536         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13537           TagDecl *Tag = TT->getDecl();
13538           if (Tag->getDeclName() == Name &&
13539               Tag->getDeclContext()->getRedeclContext()
13540                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13541             PrevDecl = Tag;
13542             Previous.clear();
13543             Previous.addDecl(Tag);
13544             Previous.resolveKind();
13545           }
13546         }
13547       }
13548     }
13549 
13550     // If this is a redeclaration of a using shadow declaration, it must
13551     // declare a tag in the same context. In MSVC mode, we allow a
13552     // redefinition if either context is within the other.
13553     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13554       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13555       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13556           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13557           !(OldTag && isAcceptableTagRedeclContext(
13558                           *this, OldTag->getDeclContext(), SearchDC))) {
13559         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13560         Diag(Shadow->getTargetDecl()->getLocation(),
13561              diag::note_using_decl_target);
13562         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13563             << 0;
13564         // Recover by ignoring the old declaration.
13565         Previous.clear();
13566         goto CreateNewDecl;
13567       }
13568     }
13569 
13570     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13571       // If this is a use of a previous tag, or if the tag is already declared
13572       // in the same scope (so that the definition/declaration completes or
13573       // rementions the tag), reuse the decl.
13574       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13575           isDeclInScope(DirectPrevDecl, SearchDC, S,
13576                         SS.isNotEmpty() || isMemberSpecialization)) {
13577         // Make sure that this wasn't declared as an enum and now used as a
13578         // struct or something similar.
13579         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13580                                           TUK == TUK_Definition, KWLoc,
13581                                           Name)) {
13582           bool SafeToContinue
13583             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13584                Kind != TTK_Enum);
13585           if (SafeToContinue)
13586             Diag(KWLoc, diag::err_use_with_wrong_tag)
13587               << Name
13588               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13589                                               PrevTagDecl->getKindName());
13590           else
13591             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13592           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13593 
13594           if (SafeToContinue)
13595             Kind = PrevTagDecl->getTagKind();
13596           else {
13597             // Recover by making this an anonymous redefinition.
13598             Name = nullptr;
13599             Previous.clear();
13600             Invalid = true;
13601           }
13602         }
13603 
13604         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13605           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13606 
13607           // If this is an elaborated-type-specifier for a scoped enumeration,
13608           // the 'class' keyword is not necessary and not permitted.
13609           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13610             if (ScopedEnum)
13611               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13612                 << PrevEnum->isScoped()
13613                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13614             return PrevTagDecl;
13615           }
13616 
13617           QualType EnumUnderlyingTy;
13618           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13619             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13620           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13621             EnumUnderlyingTy = QualType(T, 0);
13622 
13623           // All conflicts with previous declarations are recovered by
13624           // returning the previous declaration, unless this is a definition,
13625           // in which case we want the caller to bail out.
13626           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13627                                      ScopedEnum, EnumUnderlyingTy,
13628                                      EnumUnderlyingIsImplicit, PrevEnum))
13629             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13630         }
13631 
13632         // C++11 [class.mem]p1:
13633         //   A member shall not be declared twice in the member-specification,
13634         //   except that a nested class or member class template can be declared
13635         //   and then later defined.
13636         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13637             S->isDeclScope(PrevDecl)) {
13638           Diag(NameLoc, diag::ext_member_redeclared);
13639           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13640         }
13641 
13642         if (!Invalid) {
13643           // If this is a use, just return the declaration we found, unless
13644           // we have attributes.
13645           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13646             if (Attr) {
13647               // FIXME: Diagnose these attributes. For now, we create a new
13648               // declaration to hold them.
13649             } else if (TUK == TUK_Reference &&
13650                        (PrevTagDecl->getFriendObjectKind() ==
13651                             Decl::FOK_Undeclared ||
13652                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13653                        SS.isEmpty()) {
13654               // This declaration is a reference to an existing entity, but
13655               // has different visibility from that entity: it either makes
13656               // a friend visible or it makes a type visible in a new module.
13657               // In either case, create a new declaration. We only do this if
13658               // the declaration would have meant the same thing if no prior
13659               // declaration were found, that is, if it was found in the same
13660               // scope where we would have injected a declaration.
13661               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13662                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13663                 return PrevTagDecl;
13664               // This is in the injected scope, create a new declaration in
13665               // that scope.
13666               S = getTagInjectionScope(S, getLangOpts());
13667             } else {
13668               return PrevTagDecl;
13669             }
13670           }
13671 
13672           // Diagnose attempts to redefine a tag.
13673           if (TUK == TUK_Definition) {
13674             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13675               // If we're defining a specialization and the previous definition
13676               // is from an implicit instantiation, don't emit an error
13677               // here; we'll catch this in the general case below.
13678               bool IsExplicitSpecializationAfterInstantiation = false;
13679               if (isMemberSpecialization) {
13680                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13681                   IsExplicitSpecializationAfterInstantiation =
13682                     RD->getTemplateSpecializationKind() !=
13683                     TSK_ExplicitSpecialization;
13684                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13685                   IsExplicitSpecializationAfterInstantiation =
13686                     ED->getTemplateSpecializationKind() !=
13687                     TSK_ExplicitSpecialization;
13688               }
13689 
13690               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13691               // not keep more that one definition around (merge them). However,
13692               // ensure the decl passes the structural compatibility check in
13693               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13694               NamedDecl *Hidden = nullptr;
13695               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13696                 // There is a definition of this tag, but it is not visible. We
13697                 // explicitly make use of C++'s one definition rule here, and
13698                 // assume that this definition is identical to the hidden one
13699                 // we already have. Make the existing definition visible and
13700                 // use it in place of this one.
13701                 if (!getLangOpts().CPlusPlus) {
13702                   // Postpone making the old definition visible until after we
13703                   // complete parsing the new one and do the structural
13704                   // comparison.
13705                   SkipBody->CheckSameAsPrevious = true;
13706                   SkipBody->New = createTagFromNewDecl();
13707                   SkipBody->Previous = Hidden;
13708                 } else {
13709                   SkipBody->ShouldSkip = true;
13710                   makeMergedDefinitionVisible(Hidden);
13711                 }
13712                 return Def;
13713               } else if (!IsExplicitSpecializationAfterInstantiation) {
13714                 // A redeclaration in function prototype scope in C isn't
13715                 // visible elsewhere, so merely issue a warning.
13716                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13717                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13718                 else
13719                   Diag(NameLoc, diag::err_redefinition) << Name;
13720                 notePreviousDefinition(Def,
13721                                        NameLoc.isValid() ? NameLoc : KWLoc);
13722                 // If this is a redefinition, recover by making this
13723                 // struct be anonymous, which will make any later
13724                 // references get the previous definition.
13725                 Name = nullptr;
13726                 Previous.clear();
13727                 Invalid = true;
13728               }
13729             } else {
13730               // If the type is currently being defined, complain
13731               // about a nested redefinition.
13732               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13733               if (TD->isBeingDefined()) {
13734                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13735                 Diag(PrevTagDecl->getLocation(),
13736                      diag::note_previous_definition);
13737                 Name = nullptr;
13738                 Previous.clear();
13739                 Invalid = true;
13740               }
13741             }
13742 
13743             // Okay, this is definition of a previously declared or referenced
13744             // tag. We're going to create a new Decl for it.
13745           }
13746 
13747           // Okay, we're going to make a redeclaration.  If this is some kind
13748           // of reference, make sure we build the redeclaration in the same DC
13749           // as the original, and ignore the current access specifier.
13750           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13751             SearchDC = PrevTagDecl->getDeclContext();
13752             AS = AS_none;
13753           }
13754         }
13755         // If we get here we have (another) forward declaration or we
13756         // have a definition.  Just create a new decl.
13757 
13758       } else {
13759         // If we get here, this is a definition of a new tag type in a nested
13760         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13761         // new decl/type.  We set PrevDecl to NULL so that the entities
13762         // have distinct types.
13763         Previous.clear();
13764       }
13765       // If we get here, we're going to create a new Decl. If PrevDecl
13766       // is non-NULL, it's a definition of the tag declared by
13767       // PrevDecl. If it's NULL, we have a new definition.
13768 
13769     // Otherwise, PrevDecl is not a tag, but was found with tag
13770     // lookup.  This is only actually possible in C++, where a few
13771     // things like templates still live in the tag namespace.
13772     } else {
13773       // Use a better diagnostic if an elaborated-type-specifier
13774       // found the wrong kind of type on the first
13775       // (non-redeclaration) lookup.
13776       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13777           !Previous.isForRedeclaration()) {
13778         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13779         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13780                                                        << Kind;
13781         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13782         Invalid = true;
13783 
13784       // Otherwise, only diagnose if the declaration is in scope.
13785       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13786                                 SS.isNotEmpty() || isMemberSpecialization)) {
13787         // do nothing
13788 
13789       // Diagnose implicit declarations introduced by elaborated types.
13790       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13791         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13792         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13793         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13794         Invalid = true;
13795 
13796       // Otherwise it's a declaration.  Call out a particularly common
13797       // case here.
13798       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13799         unsigned Kind = 0;
13800         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13801         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13802           << Name << Kind << TND->getUnderlyingType();
13803         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13804         Invalid = true;
13805 
13806       // Otherwise, diagnose.
13807       } else {
13808         // The tag name clashes with something else in the target scope,
13809         // issue an error and recover by making this tag be anonymous.
13810         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13811         notePreviousDefinition(PrevDecl, NameLoc);
13812         Name = nullptr;
13813         Invalid = true;
13814       }
13815 
13816       // The existing declaration isn't relevant to us; we're in a
13817       // new scope, so clear out the previous declaration.
13818       Previous.clear();
13819     }
13820   }
13821 
13822 CreateNewDecl:
13823 
13824   TagDecl *PrevDecl = nullptr;
13825   if (Previous.isSingleResult())
13826     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13827 
13828   // If there is an identifier, use the location of the identifier as the
13829   // location of the decl, otherwise use the location of the struct/union
13830   // keyword.
13831   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13832 
13833   // Otherwise, create a new declaration. If there is a previous
13834   // declaration of the same entity, the two will be linked via
13835   // PrevDecl.
13836   TagDecl *New;
13837 
13838   bool IsForwardReference = false;
13839   if (Kind == TTK_Enum) {
13840     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13841     // enum X { A, B, C } D;    D should chain to X.
13842     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13843                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13844                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13845 
13846     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13847       StdAlignValT = cast<EnumDecl>(New);
13848 
13849     // If this is an undefined enum, warn.
13850     if (TUK != TUK_Definition && !Invalid) {
13851       TagDecl *Def;
13852       if (!EnumUnderlyingIsImplicit &&
13853           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13854           cast<EnumDecl>(New)->isFixed()) {
13855         // C++0x: 7.2p2: opaque-enum-declaration.
13856         // Conflicts are diagnosed above. Do nothing.
13857       }
13858       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13859         Diag(Loc, diag::ext_forward_ref_enum_def)
13860           << New;
13861         Diag(Def->getLocation(), diag::note_previous_definition);
13862       } else {
13863         unsigned DiagID = diag::ext_forward_ref_enum;
13864         if (getLangOpts().MSVCCompat)
13865           DiagID = diag::ext_ms_forward_ref_enum;
13866         else if (getLangOpts().CPlusPlus)
13867           DiagID = diag::err_forward_ref_enum;
13868         Diag(Loc, DiagID);
13869 
13870         // If this is a forward-declared reference to an enumeration, make a
13871         // note of it; we won't actually be introducing the declaration into
13872         // the declaration context.
13873         if (TUK == TUK_Reference)
13874           IsForwardReference = true;
13875       }
13876     }
13877 
13878     if (EnumUnderlying) {
13879       EnumDecl *ED = cast<EnumDecl>(New);
13880       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13881         ED->setIntegerTypeSourceInfo(TI);
13882       else
13883         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13884       ED->setPromotionType(ED->getIntegerType());
13885     }
13886   } else {
13887     // struct/union/class
13888 
13889     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13890     // struct X { int A; } D;    D should chain to X.
13891     if (getLangOpts().CPlusPlus) {
13892       // FIXME: Look for a way to use RecordDecl for simple structs.
13893       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13894                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13895 
13896       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13897         StdBadAlloc = cast<CXXRecordDecl>(New);
13898     } else
13899       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13900                                cast_or_null<RecordDecl>(PrevDecl));
13901   }
13902 
13903   // C++11 [dcl.type]p3:
13904   //   A type-specifier-seq shall not define a class or enumeration [...].
13905   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13906       TUK == TUK_Definition) {
13907     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13908       << Context.getTagDeclType(New);
13909     Invalid = true;
13910   }
13911 
13912   // Maybe add qualifier info.
13913   if (SS.isNotEmpty()) {
13914     if (SS.isSet()) {
13915       // If this is either a declaration or a definition, check the
13916       // nested-name-specifier against the current context. We don't do this
13917       // for explicit specializations, because they have similar checking
13918       // (with more specific diagnostics) in the call to
13919       // CheckMemberSpecialization, below.
13920       if (!isMemberSpecialization &&
13921           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13922           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13923         Invalid = true;
13924 
13925       New->setQualifierInfo(SS.getWithLocInContext(Context));
13926       if (TemplateParameterLists.size() > 0) {
13927         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13928       }
13929     }
13930     else
13931       Invalid = true;
13932   }
13933 
13934   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13935     // Add alignment attributes if necessary; these attributes are checked when
13936     // the ASTContext lays out the structure.
13937     //
13938     // It is important for implementing the correct semantics that this
13939     // happen here (in ActOnTag). The #pragma pack stack is
13940     // maintained as a result of parser callbacks which can occur at
13941     // many points during the parsing of a struct declaration (because
13942     // the #pragma tokens are effectively skipped over during the
13943     // parsing of the struct).
13944     if (TUK == TUK_Definition) {
13945       AddAlignmentAttributesForRecord(RD);
13946       AddMsStructLayoutForRecord(RD);
13947     }
13948   }
13949 
13950   if (ModulePrivateLoc.isValid()) {
13951     if (isMemberSpecialization)
13952       Diag(New->getLocation(), diag::err_module_private_specialization)
13953         << 2
13954         << FixItHint::CreateRemoval(ModulePrivateLoc);
13955     // __module_private__ does not apply to local classes. However, we only
13956     // diagnose this as an error when the declaration specifiers are
13957     // freestanding. Here, we just ignore the __module_private__.
13958     else if (!SearchDC->isFunctionOrMethod())
13959       New->setModulePrivate();
13960   }
13961 
13962   // If this is a specialization of a member class (of a class template),
13963   // check the specialization.
13964   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13965     Invalid = true;
13966 
13967   // If we're declaring or defining a tag in function prototype scope in C,
13968   // note that this type can only be used within the function and add it to
13969   // the list of decls to inject into the function definition scope.
13970   if ((Name || Kind == TTK_Enum) &&
13971       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13972     if (getLangOpts().CPlusPlus) {
13973       // C++ [dcl.fct]p6:
13974       //   Types shall not be defined in return or parameter types.
13975       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13976         Diag(Loc, diag::err_type_defined_in_param_type)
13977             << Name;
13978         Invalid = true;
13979       }
13980     } else if (!PrevDecl) {
13981       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13982     }
13983   }
13984 
13985   if (Invalid)
13986     New->setInvalidDecl();
13987 
13988   // Set the lexical context. If the tag has a C++ scope specifier, the
13989   // lexical context will be different from the semantic context.
13990   New->setLexicalDeclContext(CurContext);
13991 
13992   // Mark this as a friend decl if applicable.
13993   // In Microsoft mode, a friend declaration also acts as a forward
13994   // declaration so we always pass true to setObjectOfFriendDecl to make
13995   // the tag name visible.
13996   if (TUK == TUK_Friend)
13997     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13998 
13999   // Set the access specifier.
14000   if (!Invalid && SearchDC->isRecord())
14001     SetMemberAccessSpecifier(New, PrevDecl, AS);
14002 
14003   if (TUK == TUK_Definition)
14004     New->startDefinition();
14005 
14006   if (Attr)
14007     ProcessDeclAttributeList(S, New, Attr);
14008   AddPragmaAttributes(S, New);
14009 
14010   // If this has an identifier, add it to the scope stack.
14011   if (TUK == TUK_Friend) {
14012     // We might be replacing an existing declaration in the lookup tables;
14013     // if so, borrow its access specifier.
14014     if (PrevDecl)
14015       New->setAccess(PrevDecl->getAccess());
14016 
14017     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14018     DC->makeDeclVisibleInContext(New);
14019     if (Name) // can be null along some error paths
14020       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14021         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14022   } else if (Name) {
14023     S = getNonFieldDeclScope(S);
14024     PushOnScopeChains(New, S, !IsForwardReference);
14025     if (IsForwardReference)
14026       SearchDC->makeDeclVisibleInContext(New);
14027   } else {
14028     CurContext->addDecl(New);
14029   }
14030 
14031   // If this is the C FILE type, notify the AST context.
14032   if (IdentifierInfo *II = New->getIdentifier())
14033     if (!New->isInvalidDecl() &&
14034         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14035         II->isStr("FILE"))
14036       Context.setFILEDecl(New);
14037 
14038   if (PrevDecl)
14039     mergeDeclAttributes(New, PrevDecl);
14040 
14041   // If there's a #pragma GCC visibility in scope, set the visibility of this
14042   // record.
14043   AddPushedVisibilityAttribute(New);
14044 
14045   if (isMemberSpecialization && !New->isInvalidDecl())
14046     CompleteMemberSpecialization(New, Previous);
14047 
14048   OwnedDecl = true;
14049   // In C++, don't return an invalid declaration. We can't recover well from
14050   // the cases where we make the type anonymous.
14051   if (Invalid && getLangOpts().CPlusPlus) {
14052     if (New->isBeingDefined())
14053       if (auto RD = dyn_cast<RecordDecl>(New))
14054         RD->completeDefinition();
14055     return nullptr;
14056   } else {
14057     return New;
14058   }
14059 }
14060 
14061 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14062   AdjustDeclIfTemplate(TagD);
14063   TagDecl *Tag = cast<TagDecl>(TagD);
14064 
14065   // Enter the tag context.
14066   PushDeclContext(S, Tag);
14067 
14068   ActOnDocumentableDecl(TagD);
14069 
14070   // If there's a #pragma GCC visibility in scope, set the visibility of this
14071   // record.
14072   AddPushedVisibilityAttribute(Tag);
14073 }
14074 
14075 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14076                                     SkipBodyInfo &SkipBody) {
14077   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14078     return false;
14079 
14080   // Make the previous decl visible.
14081   makeMergedDefinitionVisible(SkipBody.Previous);
14082   return true;
14083 }
14084 
14085 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14086   assert(isa<ObjCContainerDecl>(IDecl) &&
14087          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14088   DeclContext *OCD = cast<DeclContext>(IDecl);
14089   assert(getContainingDC(OCD) == CurContext &&
14090       "The next DeclContext should be lexically contained in the current one.");
14091   CurContext = OCD;
14092   return IDecl;
14093 }
14094 
14095 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14096                                            SourceLocation FinalLoc,
14097                                            bool IsFinalSpelledSealed,
14098                                            SourceLocation LBraceLoc) {
14099   AdjustDeclIfTemplate(TagD);
14100   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14101 
14102   FieldCollector->StartClass();
14103 
14104   if (!Record->getIdentifier())
14105     return;
14106 
14107   if (FinalLoc.isValid())
14108     Record->addAttr(new (Context)
14109                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14110 
14111   // C++ [class]p2:
14112   //   [...] The class-name is also inserted into the scope of the
14113   //   class itself; this is known as the injected-class-name. For
14114   //   purposes of access checking, the injected-class-name is treated
14115   //   as if it were a public member name.
14116   CXXRecordDecl *InjectedClassName
14117     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14118                             Record->getLocStart(), Record->getLocation(),
14119                             Record->getIdentifier(),
14120                             /*PrevDecl=*/nullptr,
14121                             /*DelayTypeCreation=*/true);
14122   Context.getTypeDeclType(InjectedClassName, Record);
14123   InjectedClassName->setImplicit();
14124   InjectedClassName->setAccess(AS_public);
14125   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14126       InjectedClassName->setDescribedClassTemplate(Template);
14127   PushOnScopeChains(InjectedClassName, S);
14128   assert(InjectedClassName->isInjectedClassName() &&
14129          "Broken injected-class-name");
14130 }
14131 
14132 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14133                                     SourceRange BraceRange) {
14134   AdjustDeclIfTemplate(TagD);
14135   TagDecl *Tag = cast<TagDecl>(TagD);
14136   Tag->setBraceRange(BraceRange);
14137 
14138   // Make sure we "complete" the definition even it is invalid.
14139   if (Tag->isBeingDefined()) {
14140     assert(Tag->isInvalidDecl() && "We should already have completed it");
14141     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14142       RD->completeDefinition();
14143   }
14144 
14145   if (isa<CXXRecordDecl>(Tag)) {
14146     FieldCollector->FinishClass();
14147   }
14148 
14149   // Exit this scope of this tag's definition.
14150   PopDeclContext();
14151 
14152   if (getCurLexicalContext()->isObjCContainer() &&
14153       Tag->getDeclContext()->isFileContext())
14154     Tag->setTopLevelDeclInObjCContainer();
14155 
14156   // Notify the consumer that we've defined a tag.
14157   if (!Tag->isInvalidDecl())
14158     Consumer.HandleTagDeclDefinition(Tag);
14159 }
14160 
14161 void Sema::ActOnObjCContainerFinishDefinition() {
14162   // Exit this scope of this interface definition.
14163   PopDeclContext();
14164 }
14165 
14166 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14167   assert(DC == CurContext && "Mismatch of container contexts");
14168   OriginalLexicalContext = DC;
14169   ActOnObjCContainerFinishDefinition();
14170 }
14171 
14172 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14173   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14174   OriginalLexicalContext = nullptr;
14175 }
14176 
14177 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14178   AdjustDeclIfTemplate(TagD);
14179   TagDecl *Tag = cast<TagDecl>(TagD);
14180   Tag->setInvalidDecl();
14181 
14182   // Make sure we "complete" the definition even it is invalid.
14183   if (Tag->isBeingDefined()) {
14184     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14185       RD->completeDefinition();
14186   }
14187 
14188   // We're undoing ActOnTagStartDefinition here, not
14189   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14190   // the FieldCollector.
14191 
14192   PopDeclContext();
14193 }
14194 
14195 // Note that FieldName may be null for anonymous bitfields.
14196 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14197                                 IdentifierInfo *FieldName,
14198                                 QualType FieldTy, bool IsMsStruct,
14199                                 Expr *BitWidth, bool *ZeroWidth) {
14200   // Default to true; that shouldn't confuse checks for emptiness
14201   if (ZeroWidth)
14202     *ZeroWidth = true;
14203 
14204   // C99 6.7.2.1p4 - verify the field type.
14205   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14206   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14207     // Handle incomplete types with specific error.
14208     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14209       return ExprError();
14210     if (FieldName)
14211       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14212         << FieldName << FieldTy << BitWidth->getSourceRange();
14213     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14214       << FieldTy << BitWidth->getSourceRange();
14215   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14216                                              UPPC_BitFieldWidth))
14217     return ExprError();
14218 
14219   // If the bit-width is type- or value-dependent, don't try to check
14220   // it now.
14221   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14222     return BitWidth;
14223 
14224   llvm::APSInt Value;
14225   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14226   if (ICE.isInvalid())
14227     return ICE;
14228   BitWidth = ICE.get();
14229 
14230   if (Value != 0 && ZeroWidth)
14231     *ZeroWidth = false;
14232 
14233   // Zero-width bitfield is ok for anonymous field.
14234   if (Value == 0 && FieldName)
14235     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14236 
14237   if (Value.isSigned() && Value.isNegative()) {
14238     if (FieldName)
14239       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14240                << FieldName << Value.toString(10);
14241     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14242       << Value.toString(10);
14243   }
14244 
14245   if (!FieldTy->isDependentType()) {
14246     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14247     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14248     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14249 
14250     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14251     // ABI.
14252     bool CStdConstraintViolation =
14253         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14254     bool MSBitfieldViolation =
14255         Value.ugt(TypeStorageSize) &&
14256         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14257     if (CStdConstraintViolation || MSBitfieldViolation) {
14258       unsigned DiagWidth =
14259           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14260       if (FieldName)
14261         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14262                << FieldName << (unsigned)Value.getZExtValue()
14263                << !CStdConstraintViolation << DiagWidth;
14264 
14265       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14266              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14267              << DiagWidth;
14268     }
14269 
14270     // Warn on types where the user might conceivably expect to get all
14271     // specified bits as value bits: that's all integral types other than
14272     // 'bool'.
14273     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14274       if (FieldName)
14275         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14276             << FieldName << (unsigned)Value.getZExtValue()
14277             << (unsigned)TypeWidth;
14278       else
14279         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14280             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14281     }
14282   }
14283 
14284   return BitWidth;
14285 }
14286 
14287 /// ActOnField - Each field of a C struct/union is passed into this in order
14288 /// to create a FieldDecl object for it.
14289 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14290                        Declarator &D, Expr *BitfieldWidth) {
14291   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14292                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14293                                /*InitStyle=*/ICIS_NoInit, AS_public);
14294   return Res;
14295 }
14296 
14297 /// HandleField - Analyze a field of a C struct or a C++ data member.
14298 ///
14299 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14300                              SourceLocation DeclStart,
14301                              Declarator &D, Expr *BitWidth,
14302                              InClassInitStyle InitStyle,
14303                              AccessSpecifier AS) {
14304   if (D.isDecompositionDeclarator()) {
14305     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14306     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14307       << Decomp.getSourceRange();
14308     return nullptr;
14309   }
14310 
14311   IdentifierInfo *II = D.getIdentifier();
14312   SourceLocation Loc = DeclStart;
14313   if (II) Loc = D.getIdentifierLoc();
14314 
14315   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14316   QualType T = TInfo->getType();
14317   if (getLangOpts().CPlusPlus) {
14318     CheckExtraCXXDefaultArguments(D);
14319 
14320     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14321                                         UPPC_DataMemberType)) {
14322       D.setInvalidType();
14323       T = Context.IntTy;
14324       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14325     }
14326   }
14327 
14328   // TR 18037 does not allow fields to be declared with address spaces.
14329   if (T.getQualifiers().hasAddressSpace()) {
14330     Diag(Loc, diag::err_field_with_address_space);
14331     D.setInvalidType();
14332   }
14333 
14334   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14335   // used as structure or union field: image, sampler, event or block types.
14336   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14337                           T->isSamplerT() || T->isBlockPointerType())) {
14338     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14339     D.setInvalidType();
14340   }
14341 
14342   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14343 
14344   if (D.getDeclSpec().isInlineSpecified())
14345     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14346         << getLangOpts().CPlusPlus1z;
14347   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14348     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14349          diag::err_invalid_thread)
14350       << DeclSpec::getSpecifierName(TSCS);
14351 
14352   // Check to see if this name was declared as a member previously
14353   NamedDecl *PrevDecl = nullptr;
14354   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14355   LookupName(Previous, S);
14356   switch (Previous.getResultKind()) {
14357     case LookupResult::Found:
14358     case LookupResult::FoundUnresolvedValue:
14359       PrevDecl = Previous.getAsSingle<NamedDecl>();
14360       break;
14361 
14362     case LookupResult::FoundOverloaded:
14363       PrevDecl = Previous.getRepresentativeDecl();
14364       break;
14365 
14366     case LookupResult::NotFound:
14367     case LookupResult::NotFoundInCurrentInstantiation:
14368     case LookupResult::Ambiguous:
14369       break;
14370   }
14371   Previous.suppressDiagnostics();
14372 
14373   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14374     // Maybe we will complain about the shadowed template parameter.
14375     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14376     // Just pretend that we didn't see the previous declaration.
14377     PrevDecl = nullptr;
14378   }
14379 
14380   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14381     PrevDecl = nullptr;
14382 
14383   bool Mutable
14384     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14385   SourceLocation TSSL = D.getLocStart();
14386   FieldDecl *NewFD
14387     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14388                      TSSL, AS, PrevDecl, &D);
14389 
14390   if (NewFD->isInvalidDecl())
14391     Record->setInvalidDecl();
14392 
14393   if (D.getDeclSpec().isModulePrivateSpecified())
14394     NewFD->setModulePrivate();
14395 
14396   if (NewFD->isInvalidDecl() && PrevDecl) {
14397     // Don't introduce NewFD into scope; there's already something
14398     // with the same name in the same scope.
14399   } else if (II) {
14400     PushOnScopeChains(NewFD, S);
14401   } else
14402     Record->addDecl(NewFD);
14403 
14404   return NewFD;
14405 }
14406 
14407 /// \brief Build a new FieldDecl and check its well-formedness.
14408 ///
14409 /// This routine builds a new FieldDecl given the fields name, type,
14410 /// record, etc. \p PrevDecl should refer to any previous declaration
14411 /// with the same name and in the same scope as the field to be
14412 /// created.
14413 ///
14414 /// \returns a new FieldDecl.
14415 ///
14416 /// \todo The Declarator argument is a hack. It will be removed once
14417 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14418                                 TypeSourceInfo *TInfo,
14419                                 RecordDecl *Record, SourceLocation Loc,
14420                                 bool Mutable, Expr *BitWidth,
14421                                 InClassInitStyle InitStyle,
14422                                 SourceLocation TSSL,
14423                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14424                                 Declarator *D) {
14425   IdentifierInfo *II = Name.getAsIdentifierInfo();
14426   bool InvalidDecl = false;
14427   if (D) InvalidDecl = D->isInvalidType();
14428 
14429   // If we receive a broken type, recover by assuming 'int' and
14430   // marking this declaration as invalid.
14431   if (T.isNull()) {
14432     InvalidDecl = true;
14433     T = Context.IntTy;
14434   }
14435 
14436   QualType EltTy = Context.getBaseElementType(T);
14437   if (!EltTy->isDependentType()) {
14438     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14439       // Fields of incomplete type force their record to be invalid.
14440       Record->setInvalidDecl();
14441       InvalidDecl = true;
14442     } else {
14443       NamedDecl *Def;
14444       EltTy->isIncompleteType(&Def);
14445       if (Def && Def->isInvalidDecl()) {
14446         Record->setInvalidDecl();
14447         InvalidDecl = true;
14448       }
14449     }
14450   }
14451 
14452   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14453   if (BitWidth && getLangOpts().OpenCL) {
14454     Diag(Loc, diag::err_opencl_bitfields);
14455     InvalidDecl = true;
14456   }
14457 
14458   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14459   // than a variably modified type.
14460   if (!InvalidDecl && T->isVariablyModifiedType()) {
14461     bool SizeIsNegative;
14462     llvm::APSInt Oversized;
14463 
14464     TypeSourceInfo *FixedTInfo =
14465       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14466                                                     SizeIsNegative,
14467                                                     Oversized);
14468     if (FixedTInfo) {
14469       Diag(Loc, diag::warn_illegal_constant_array_size);
14470       TInfo = FixedTInfo;
14471       T = FixedTInfo->getType();
14472     } else {
14473       if (SizeIsNegative)
14474         Diag(Loc, diag::err_typecheck_negative_array_size);
14475       else if (Oversized.getBoolValue())
14476         Diag(Loc, diag::err_array_too_large)
14477           << Oversized.toString(10);
14478       else
14479         Diag(Loc, diag::err_typecheck_field_variable_size);
14480       InvalidDecl = true;
14481     }
14482   }
14483 
14484   // Fields can not have abstract class types
14485   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14486                                              diag::err_abstract_type_in_decl,
14487                                              AbstractFieldType))
14488     InvalidDecl = true;
14489 
14490   bool ZeroWidth = false;
14491   if (InvalidDecl)
14492     BitWidth = nullptr;
14493   // If this is declared as a bit-field, check the bit-field.
14494   if (BitWidth) {
14495     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14496                               &ZeroWidth).get();
14497     if (!BitWidth) {
14498       InvalidDecl = true;
14499       BitWidth = nullptr;
14500       ZeroWidth = false;
14501     }
14502   }
14503 
14504   // Check that 'mutable' is consistent with the type of the declaration.
14505   if (!InvalidDecl && Mutable) {
14506     unsigned DiagID = 0;
14507     if (T->isReferenceType())
14508       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14509                                         : diag::err_mutable_reference;
14510     else if (T.isConstQualified())
14511       DiagID = diag::err_mutable_const;
14512 
14513     if (DiagID) {
14514       SourceLocation ErrLoc = Loc;
14515       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14516         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14517       Diag(ErrLoc, DiagID);
14518       if (DiagID != diag::ext_mutable_reference) {
14519         Mutable = false;
14520         InvalidDecl = true;
14521       }
14522     }
14523   }
14524 
14525   // C++11 [class.union]p8 (DR1460):
14526   //   At most one variant member of a union may have a
14527   //   brace-or-equal-initializer.
14528   if (InitStyle != ICIS_NoInit)
14529     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14530 
14531   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14532                                        BitWidth, Mutable, InitStyle);
14533   if (InvalidDecl)
14534     NewFD->setInvalidDecl();
14535 
14536   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14537     Diag(Loc, diag::err_duplicate_member) << II;
14538     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14539     NewFD->setInvalidDecl();
14540   }
14541 
14542   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14543     if (Record->isUnion()) {
14544       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14545         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14546         if (RDecl->getDefinition()) {
14547           // C++ [class.union]p1: An object of a class with a non-trivial
14548           // constructor, a non-trivial copy constructor, a non-trivial
14549           // destructor, or a non-trivial copy assignment operator
14550           // cannot be a member of a union, nor can an array of such
14551           // objects.
14552           if (CheckNontrivialField(NewFD))
14553             NewFD->setInvalidDecl();
14554         }
14555       }
14556 
14557       // C++ [class.union]p1: If a union contains a member of reference type,
14558       // the program is ill-formed, except when compiling with MSVC extensions
14559       // enabled.
14560       if (EltTy->isReferenceType()) {
14561         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14562                                     diag::ext_union_member_of_reference_type :
14563                                     diag::err_union_member_of_reference_type)
14564           << NewFD->getDeclName() << EltTy;
14565         if (!getLangOpts().MicrosoftExt)
14566           NewFD->setInvalidDecl();
14567       }
14568     }
14569   }
14570 
14571   // FIXME: We need to pass in the attributes given an AST
14572   // representation, not a parser representation.
14573   if (D) {
14574     // FIXME: The current scope is almost... but not entirely... correct here.
14575     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14576 
14577     if (NewFD->hasAttrs())
14578       CheckAlignasUnderalignment(NewFD);
14579   }
14580 
14581   // In auto-retain/release, infer strong retension for fields of
14582   // retainable type.
14583   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14584     NewFD->setInvalidDecl();
14585 
14586   if (T.isObjCGCWeak())
14587     Diag(Loc, diag::warn_attribute_weak_on_field);
14588 
14589   NewFD->setAccess(AS);
14590   return NewFD;
14591 }
14592 
14593 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14594   assert(FD);
14595   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14596 
14597   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14598     return false;
14599 
14600   QualType EltTy = Context.getBaseElementType(FD->getType());
14601   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14602     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14603     if (RDecl->getDefinition()) {
14604       // We check for copy constructors before constructors
14605       // because otherwise we'll never get complaints about
14606       // copy constructors.
14607 
14608       CXXSpecialMember member = CXXInvalid;
14609       // We're required to check for any non-trivial constructors. Since the
14610       // implicit default constructor is suppressed if there are any
14611       // user-declared constructors, we just need to check that there is a
14612       // trivial default constructor and a trivial copy constructor. (We don't
14613       // worry about move constructors here, since this is a C++98 check.)
14614       if (RDecl->hasNonTrivialCopyConstructor())
14615         member = CXXCopyConstructor;
14616       else if (!RDecl->hasTrivialDefaultConstructor())
14617         member = CXXDefaultConstructor;
14618       else if (RDecl->hasNonTrivialCopyAssignment())
14619         member = CXXCopyAssignment;
14620       else if (RDecl->hasNonTrivialDestructor())
14621         member = CXXDestructor;
14622 
14623       if (member != CXXInvalid) {
14624         if (!getLangOpts().CPlusPlus11 &&
14625             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14626           // Objective-C++ ARC: it is an error to have a non-trivial field of
14627           // a union. However, system headers in Objective-C programs
14628           // occasionally have Objective-C lifetime objects within unions,
14629           // and rather than cause the program to fail, we make those
14630           // members unavailable.
14631           SourceLocation Loc = FD->getLocation();
14632           if (getSourceManager().isInSystemHeader(Loc)) {
14633             if (!FD->hasAttr<UnavailableAttr>())
14634               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14635                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14636             return false;
14637           }
14638         }
14639 
14640         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14641                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14642                diag::err_illegal_union_or_anon_struct_member)
14643           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14644         DiagnoseNontrivial(RDecl, member);
14645         return !getLangOpts().CPlusPlus11;
14646       }
14647     }
14648   }
14649 
14650   return false;
14651 }
14652 
14653 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14654 ///  AST enum value.
14655 static ObjCIvarDecl::AccessControl
14656 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14657   switch (ivarVisibility) {
14658   default: llvm_unreachable("Unknown visitibility kind");
14659   case tok::objc_private: return ObjCIvarDecl::Private;
14660   case tok::objc_public: return ObjCIvarDecl::Public;
14661   case tok::objc_protected: return ObjCIvarDecl::Protected;
14662   case tok::objc_package: return ObjCIvarDecl::Package;
14663   }
14664 }
14665 
14666 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14667 /// in order to create an IvarDecl object for it.
14668 Decl *Sema::ActOnIvar(Scope *S,
14669                                 SourceLocation DeclStart,
14670                                 Declarator &D, Expr *BitfieldWidth,
14671                                 tok::ObjCKeywordKind Visibility) {
14672 
14673   IdentifierInfo *II = D.getIdentifier();
14674   Expr *BitWidth = (Expr*)BitfieldWidth;
14675   SourceLocation Loc = DeclStart;
14676   if (II) Loc = D.getIdentifierLoc();
14677 
14678   // FIXME: Unnamed fields can be handled in various different ways, for
14679   // example, unnamed unions inject all members into the struct namespace!
14680 
14681   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14682   QualType T = TInfo->getType();
14683 
14684   if (BitWidth) {
14685     // 6.7.2.1p3, 6.7.2.1p4
14686     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14687     if (!BitWidth)
14688       D.setInvalidType();
14689   } else {
14690     // Not a bitfield.
14691 
14692     // validate II.
14693 
14694   }
14695   if (T->isReferenceType()) {
14696     Diag(Loc, diag::err_ivar_reference_type);
14697     D.setInvalidType();
14698   }
14699   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14700   // than a variably modified type.
14701   else if (T->isVariablyModifiedType()) {
14702     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14703     D.setInvalidType();
14704   }
14705 
14706   // Get the visibility (access control) for this ivar.
14707   ObjCIvarDecl::AccessControl ac =
14708     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14709                                         : ObjCIvarDecl::None;
14710   // Must set ivar's DeclContext to its enclosing interface.
14711   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14712   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14713     return nullptr;
14714   ObjCContainerDecl *EnclosingContext;
14715   if (ObjCImplementationDecl *IMPDecl =
14716       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14717     if (LangOpts.ObjCRuntime.isFragile()) {
14718     // Case of ivar declared in an implementation. Context is that of its class.
14719       EnclosingContext = IMPDecl->getClassInterface();
14720       assert(EnclosingContext && "Implementation has no class interface!");
14721     }
14722     else
14723       EnclosingContext = EnclosingDecl;
14724   } else {
14725     if (ObjCCategoryDecl *CDecl =
14726         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14727       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14728         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14729         return nullptr;
14730       }
14731     }
14732     EnclosingContext = EnclosingDecl;
14733   }
14734 
14735   // Construct the decl.
14736   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14737                                              DeclStart, Loc, II, T,
14738                                              TInfo, ac, (Expr *)BitfieldWidth);
14739 
14740   if (II) {
14741     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14742                                            ForRedeclaration);
14743     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14744         && !isa<TagDecl>(PrevDecl)) {
14745       Diag(Loc, diag::err_duplicate_member) << II;
14746       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14747       NewID->setInvalidDecl();
14748     }
14749   }
14750 
14751   // Process attributes attached to the ivar.
14752   ProcessDeclAttributes(S, NewID, D);
14753 
14754   if (D.isInvalidType())
14755     NewID->setInvalidDecl();
14756 
14757   // In ARC, infer 'retaining' for ivars of retainable type.
14758   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14759     NewID->setInvalidDecl();
14760 
14761   if (D.getDeclSpec().isModulePrivateSpecified())
14762     NewID->setModulePrivate();
14763 
14764   if (II) {
14765     // FIXME: When interfaces are DeclContexts, we'll need to add
14766     // these to the interface.
14767     S->AddDecl(NewID);
14768     IdResolver.AddDecl(NewID);
14769   }
14770 
14771   if (LangOpts.ObjCRuntime.isNonFragile() &&
14772       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14773     Diag(Loc, diag::warn_ivars_in_interface);
14774 
14775   return NewID;
14776 }
14777 
14778 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14779 /// class and class extensions. For every class \@interface and class
14780 /// extension \@interface, if the last ivar is a bitfield of any type,
14781 /// then add an implicit `char :0` ivar to the end of that interface.
14782 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14783                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14784   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14785     return;
14786 
14787   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14788   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14789 
14790   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14791     return;
14792   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14793   if (!ID) {
14794     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14795       if (!CD->IsClassExtension())
14796         return;
14797     }
14798     // No need to add this to end of @implementation.
14799     else
14800       return;
14801   }
14802   // All conditions are met. Add a new bitfield to the tail end of ivars.
14803   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14804   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14805 
14806   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14807                               DeclLoc, DeclLoc, nullptr,
14808                               Context.CharTy,
14809                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14810                                                                DeclLoc),
14811                               ObjCIvarDecl::Private, BW,
14812                               true);
14813   AllIvarDecls.push_back(Ivar);
14814 }
14815 
14816 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14817                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14818                        SourceLocation RBrac, AttributeList *Attr) {
14819   assert(EnclosingDecl && "missing record or interface decl");
14820 
14821   // If this is an Objective-C @implementation or category and we have
14822   // new fields here we should reset the layout of the interface since
14823   // it will now change.
14824   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14825     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14826     switch (DC->getKind()) {
14827     default: break;
14828     case Decl::ObjCCategory:
14829       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14830       break;
14831     case Decl::ObjCImplementation:
14832       Context.
14833         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14834       break;
14835     }
14836   }
14837 
14838   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14839 
14840   // Start counting up the number of named members; make sure to include
14841   // members of anonymous structs and unions in the total.
14842   unsigned NumNamedMembers = 0;
14843   if (Record) {
14844     for (const auto *I : Record->decls()) {
14845       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14846         if (IFD->getDeclName())
14847           ++NumNamedMembers;
14848     }
14849   }
14850 
14851   // Verify that all the fields are okay.
14852   SmallVector<FieldDecl*, 32> RecFields;
14853 
14854   bool ObjCFieldLifetimeErrReported = false;
14855   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14856        i != end; ++i) {
14857     FieldDecl *FD = cast<FieldDecl>(*i);
14858 
14859     // Get the type for the field.
14860     const Type *FDTy = FD->getType().getTypePtr();
14861 
14862     if (!FD->isAnonymousStructOrUnion()) {
14863       // Remember all fields written by the user.
14864       RecFields.push_back(FD);
14865     }
14866 
14867     // If the field is already invalid for some reason, don't emit more
14868     // diagnostics about it.
14869     if (FD->isInvalidDecl()) {
14870       EnclosingDecl->setInvalidDecl();
14871       continue;
14872     }
14873 
14874     // C99 6.7.2.1p2:
14875     //   A structure or union shall not contain a member with
14876     //   incomplete or function type (hence, a structure shall not
14877     //   contain an instance of itself, but may contain a pointer to
14878     //   an instance of itself), except that the last member of a
14879     //   structure with more than one named member may have incomplete
14880     //   array type; such a structure (and any union containing,
14881     //   possibly recursively, a member that is such a structure)
14882     //   shall not be a member of a structure or an element of an
14883     //   array.
14884     if (FDTy->isFunctionType()) {
14885       // Field declared as a function.
14886       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14887         << FD->getDeclName();
14888       FD->setInvalidDecl();
14889       EnclosingDecl->setInvalidDecl();
14890       continue;
14891     } else if (FDTy->isIncompleteArrayType() && Record &&
14892                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14893                 ((getLangOpts().MicrosoftExt ||
14894                   getLangOpts().CPlusPlus) &&
14895                  (i + 1 == Fields.end() || Record->isUnion())))) {
14896       // Flexible array member.
14897       // Microsoft and g++ is more permissive regarding flexible array.
14898       // It will accept flexible array in union and also
14899       // as the sole element of a struct/class.
14900       unsigned DiagID = 0;
14901       if (Record->isUnion())
14902         DiagID = getLangOpts().MicrosoftExt
14903                      ? diag::ext_flexible_array_union_ms
14904                      : getLangOpts().CPlusPlus
14905                            ? diag::ext_flexible_array_union_gnu
14906                            : diag::err_flexible_array_union;
14907       else if (NumNamedMembers < 1)
14908         DiagID = getLangOpts().MicrosoftExt
14909                      ? diag::ext_flexible_array_empty_aggregate_ms
14910                      : getLangOpts().CPlusPlus
14911                            ? diag::ext_flexible_array_empty_aggregate_gnu
14912                            : diag::err_flexible_array_empty_aggregate;
14913 
14914       if (DiagID)
14915         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14916                                         << Record->getTagKind();
14917       // While the layout of types that contain virtual bases is not specified
14918       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14919       // virtual bases after the derived members.  This would make a flexible
14920       // array member declared at the end of an object not adjacent to the end
14921       // of the type.
14922       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14923         if (RD->getNumVBases() != 0)
14924           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14925             << FD->getDeclName() << Record->getTagKind();
14926       if (!getLangOpts().C99)
14927         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14928           << FD->getDeclName() << Record->getTagKind();
14929 
14930       // If the element type has a non-trivial destructor, we would not
14931       // implicitly destroy the elements, so disallow it for now.
14932       //
14933       // FIXME: GCC allows this. We should probably either implicitly delete
14934       // the destructor of the containing class, or just allow this.
14935       QualType BaseElem = Context.getBaseElementType(FD->getType());
14936       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14937         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14938           << FD->getDeclName() << FD->getType();
14939         FD->setInvalidDecl();
14940         EnclosingDecl->setInvalidDecl();
14941         continue;
14942       }
14943       // Okay, we have a legal flexible array member at the end of the struct.
14944       Record->setHasFlexibleArrayMember(true);
14945     } else if (!FDTy->isDependentType() &&
14946                RequireCompleteType(FD->getLocation(), FD->getType(),
14947                                    diag::err_field_incomplete)) {
14948       // Incomplete type
14949       FD->setInvalidDecl();
14950       EnclosingDecl->setInvalidDecl();
14951       continue;
14952     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14953       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14954         // A type which contains a flexible array member is considered to be a
14955         // flexible array member.
14956         Record->setHasFlexibleArrayMember(true);
14957         if (!Record->isUnion()) {
14958           // If this is a struct/class and this is not the last element, reject
14959           // it.  Note that GCC supports variable sized arrays in the middle of
14960           // structures.
14961           if (i + 1 != Fields.end())
14962             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14963               << FD->getDeclName() << FD->getType();
14964           else {
14965             // We support flexible arrays at the end of structs in
14966             // other structs as an extension.
14967             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14968               << FD->getDeclName();
14969           }
14970         }
14971       }
14972       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14973           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14974                                  diag::err_abstract_type_in_decl,
14975                                  AbstractIvarType)) {
14976         // Ivars can not have abstract class types
14977         FD->setInvalidDecl();
14978       }
14979       if (Record && FDTTy->getDecl()->hasObjectMember())
14980         Record->setHasObjectMember(true);
14981       if (Record && FDTTy->getDecl()->hasVolatileMember())
14982         Record->setHasVolatileMember(true);
14983     } else if (FDTy->isObjCObjectType()) {
14984       /// A field cannot be an Objective-c object
14985       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14986         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14987       QualType T = Context.getObjCObjectPointerType(FD->getType());
14988       FD->setType(T);
14989     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14990                Record && !ObjCFieldLifetimeErrReported &&
14991                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14992       // It's an error in ARC or Weak if a field has lifetime.
14993       // We don't want to report this in a system header, though,
14994       // so we just make the field unavailable.
14995       // FIXME: that's really not sufficient; we need to make the type
14996       // itself invalid to, say, initialize or copy.
14997       QualType T = FD->getType();
14998       if (T.hasNonTrivialObjCLifetime()) {
14999         SourceLocation loc = FD->getLocation();
15000         if (getSourceManager().isInSystemHeader(loc)) {
15001           if (!FD->hasAttr<UnavailableAttr>()) {
15002             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15003                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15004           }
15005         } else {
15006           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15007             << T->isBlockPointerType() << Record->getTagKind();
15008         }
15009         ObjCFieldLifetimeErrReported = true;
15010       }
15011     } else if (getLangOpts().ObjC1 &&
15012                getLangOpts().getGC() != LangOptions::NonGC &&
15013                Record && !Record->hasObjectMember()) {
15014       if (FD->getType()->isObjCObjectPointerType() ||
15015           FD->getType().isObjCGCStrong())
15016         Record->setHasObjectMember(true);
15017       else if (Context.getAsArrayType(FD->getType())) {
15018         QualType BaseType = Context.getBaseElementType(FD->getType());
15019         if (BaseType->isRecordType() &&
15020             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15021           Record->setHasObjectMember(true);
15022         else if (BaseType->isObjCObjectPointerType() ||
15023                  BaseType.isObjCGCStrong())
15024                Record->setHasObjectMember(true);
15025       }
15026     }
15027     if (Record && FD->getType().isVolatileQualified())
15028       Record->setHasVolatileMember(true);
15029     // Keep track of the number of named members.
15030     if (FD->getIdentifier())
15031       ++NumNamedMembers;
15032   }
15033 
15034   // Okay, we successfully defined 'Record'.
15035   if (Record) {
15036     bool Completed = false;
15037     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15038       if (!CXXRecord->isInvalidDecl()) {
15039         // Set access bits correctly on the directly-declared conversions.
15040         for (CXXRecordDecl::conversion_iterator
15041                I = CXXRecord->conversion_begin(),
15042                E = CXXRecord->conversion_end(); I != E; ++I)
15043           I.setAccess((*I)->getAccess());
15044       }
15045 
15046       if (!CXXRecord->isDependentType()) {
15047         if (CXXRecord->hasUserDeclaredDestructor()) {
15048           // Adjust user-defined destructor exception spec.
15049           if (getLangOpts().CPlusPlus11)
15050             AdjustDestructorExceptionSpec(CXXRecord,
15051                                           CXXRecord->getDestructor());
15052         }
15053 
15054         if (!CXXRecord->isInvalidDecl()) {
15055           // Add any implicitly-declared members to this class.
15056           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15057 
15058           // If we have virtual base classes, we may end up finding multiple
15059           // final overriders for a given virtual function. Check for this
15060           // problem now.
15061           if (CXXRecord->getNumVBases()) {
15062             CXXFinalOverriderMap FinalOverriders;
15063             CXXRecord->getFinalOverriders(FinalOverriders);
15064 
15065             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15066                                              MEnd = FinalOverriders.end();
15067                  M != MEnd; ++M) {
15068               for (OverridingMethods::iterator SO = M->second.begin(),
15069                                             SOEnd = M->second.end();
15070                    SO != SOEnd; ++SO) {
15071                 assert(SO->second.size() > 0 &&
15072                        "Virtual function without overridding functions?");
15073                 if (SO->second.size() == 1)
15074                   continue;
15075 
15076                 // C++ [class.virtual]p2:
15077                 //   In a derived class, if a virtual member function of a base
15078                 //   class subobject has more than one final overrider the
15079                 //   program is ill-formed.
15080                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15081                   << (const NamedDecl *)M->first << Record;
15082                 Diag(M->first->getLocation(),
15083                      diag::note_overridden_virtual_function);
15084                 for (OverridingMethods::overriding_iterator
15085                           OM = SO->second.begin(),
15086                        OMEnd = SO->second.end();
15087                      OM != OMEnd; ++OM)
15088                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15089                     << (const NamedDecl *)M->first << OM->Method->getParent();
15090 
15091                 Record->setInvalidDecl();
15092               }
15093             }
15094             CXXRecord->completeDefinition(&FinalOverriders);
15095             Completed = true;
15096           }
15097         }
15098       }
15099     }
15100 
15101     if (!Completed)
15102       Record->completeDefinition();
15103 
15104     // We may have deferred checking for a deleted destructor. Check now.
15105     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15106       auto *Dtor = CXXRecord->getDestructor();
15107       if (Dtor && Dtor->isImplicit() &&
15108           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
15109         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15110     }
15111 
15112     if (Record->hasAttrs()) {
15113       CheckAlignasUnderalignment(Record);
15114 
15115       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15116         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15117                                            IA->getRange(), IA->getBestCase(),
15118                                            IA->getSemanticSpelling());
15119     }
15120 
15121     // Check if the structure/union declaration is a type that can have zero
15122     // size in C. For C this is a language extension, for C++ it may cause
15123     // compatibility problems.
15124     bool CheckForZeroSize;
15125     if (!getLangOpts().CPlusPlus) {
15126       CheckForZeroSize = true;
15127     } else {
15128       // For C++ filter out types that cannot be referenced in C code.
15129       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15130       CheckForZeroSize =
15131           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15132           !CXXRecord->isDependentType() &&
15133           CXXRecord->isCLike();
15134     }
15135     if (CheckForZeroSize) {
15136       bool ZeroSize = true;
15137       bool IsEmpty = true;
15138       unsigned NonBitFields = 0;
15139       for (RecordDecl::field_iterator I = Record->field_begin(),
15140                                       E = Record->field_end();
15141            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15142         IsEmpty = false;
15143         if (I->isUnnamedBitfield()) {
15144           if (I->getBitWidthValue(Context) > 0)
15145             ZeroSize = false;
15146         } else {
15147           ++NonBitFields;
15148           QualType FieldType = I->getType();
15149           if (FieldType->isIncompleteType() ||
15150               !Context.getTypeSizeInChars(FieldType).isZero())
15151             ZeroSize = false;
15152         }
15153       }
15154 
15155       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15156       // allowed in C++, but warn if its declaration is inside
15157       // extern "C" block.
15158       if (ZeroSize) {
15159         Diag(RecLoc, getLangOpts().CPlusPlus ?
15160                          diag::warn_zero_size_struct_union_in_extern_c :
15161                          diag::warn_zero_size_struct_union_compat)
15162           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15163       }
15164 
15165       // Structs without named members are extension in C (C99 6.7.2.1p7),
15166       // but are accepted by GCC.
15167       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15168         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15169                                diag::ext_no_named_members_in_struct_union)
15170           << Record->isUnion();
15171       }
15172     }
15173   } else {
15174     ObjCIvarDecl **ClsFields =
15175       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15176     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15177       ID->setEndOfDefinitionLoc(RBrac);
15178       // Add ivar's to class's DeclContext.
15179       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15180         ClsFields[i]->setLexicalDeclContext(ID);
15181         ID->addDecl(ClsFields[i]);
15182       }
15183       // Must enforce the rule that ivars in the base classes may not be
15184       // duplicates.
15185       if (ID->getSuperClass())
15186         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15187     } else if (ObjCImplementationDecl *IMPDecl =
15188                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15189       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15190       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15191         // Ivar declared in @implementation never belongs to the implementation.
15192         // Only it is in implementation's lexical context.
15193         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15194       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15195       IMPDecl->setIvarLBraceLoc(LBrac);
15196       IMPDecl->setIvarRBraceLoc(RBrac);
15197     } else if (ObjCCategoryDecl *CDecl =
15198                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15199       // case of ivars in class extension; all other cases have been
15200       // reported as errors elsewhere.
15201       // FIXME. Class extension does not have a LocEnd field.
15202       // CDecl->setLocEnd(RBrac);
15203       // Add ivar's to class extension's DeclContext.
15204       // Diagnose redeclaration of private ivars.
15205       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15206       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15207         if (IDecl) {
15208           if (const ObjCIvarDecl *ClsIvar =
15209               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15210             Diag(ClsFields[i]->getLocation(),
15211                  diag::err_duplicate_ivar_declaration);
15212             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15213             continue;
15214           }
15215           for (const auto *Ext : IDecl->known_extensions()) {
15216             if (const ObjCIvarDecl *ClsExtIvar
15217                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15218               Diag(ClsFields[i]->getLocation(),
15219                    diag::err_duplicate_ivar_declaration);
15220               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15221               continue;
15222             }
15223           }
15224         }
15225         ClsFields[i]->setLexicalDeclContext(CDecl);
15226         CDecl->addDecl(ClsFields[i]);
15227       }
15228       CDecl->setIvarLBraceLoc(LBrac);
15229       CDecl->setIvarRBraceLoc(RBrac);
15230     }
15231   }
15232 
15233   if (Attr)
15234     ProcessDeclAttributeList(S, Record, Attr);
15235 }
15236 
15237 /// \brief Determine whether the given integral value is representable within
15238 /// the given type T.
15239 static bool isRepresentableIntegerValue(ASTContext &Context,
15240                                         llvm::APSInt &Value,
15241                                         QualType T) {
15242   assert(T->isIntegralType(Context) && "Integral type required!");
15243   unsigned BitWidth = Context.getIntWidth(T);
15244 
15245   if (Value.isUnsigned() || Value.isNonNegative()) {
15246     if (T->isSignedIntegerOrEnumerationType())
15247       --BitWidth;
15248     return Value.getActiveBits() <= BitWidth;
15249   }
15250   return Value.getMinSignedBits() <= BitWidth;
15251 }
15252 
15253 // \brief Given an integral type, return the next larger integral type
15254 // (or a NULL type of no such type exists).
15255 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15256   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15257   // enum checking below.
15258   assert(T->isIntegralType(Context) && "Integral type required!");
15259   const unsigned NumTypes = 4;
15260   QualType SignedIntegralTypes[NumTypes] = {
15261     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15262   };
15263   QualType UnsignedIntegralTypes[NumTypes] = {
15264     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15265     Context.UnsignedLongLongTy
15266   };
15267 
15268   unsigned BitWidth = Context.getTypeSize(T);
15269   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15270                                                         : UnsignedIntegralTypes;
15271   for (unsigned I = 0; I != NumTypes; ++I)
15272     if (Context.getTypeSize(Types[I]) > BitWidth)
15273       return Types[I];
15274 
15275   return QualType();
15276 }
15277 
15278 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15279                                           EnumConstantDecl *LastEnumConst,
15280                                           SourceLocation IdLoc,
15281                                           IdentifierInfo *Id,
15282                                           Expr *Val) {
15283   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15284   llvm::APSInt EnumVal(IntWidth);
15285   QualType EltTy;
15286 
15287   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15288     Val = nullptr;
15289 
15290   if (Val)
15291     Val = DefaultLvalueConversion(Val).get();
15292 
15293   if (Val) {
15294     if (Enum->isDependentType() || Val->isTypeDependent())
15295       EltTy = Context.DependentTy;
15296     else {
15297       SourceLocation ExpLoc;
15298       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15299           !getLangOpts().MSVCCompat) {
15300         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15301         // constant-expression in the enumerator-definition shall be a converted
15302         // constant expression of the underlying type.
15303         EltTy = Enum->getIntegerType();
15304         ExprResult Converted =
15305           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15306                                            CCEK_Enumerator);
15307         if (Converted.isInvalid())
15308           Val = nullptr;
15309         else
15310           Val = Converted.get();
15311       } else if (!Val->isValueDependent() &&
15312                  !(Val = VerifyIntegerConstantExpression(Val,
15313                                                          &EnumVal).get())) {
15314         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15315       } else {
15316         if (Enum->isFixed()) {
15317           EltTy = Enum->getIntegerType();
15318 
15319           // In Obj-C and Microsoft mode, require the enumeration value to be
15320           // representable in the underlying type of the enumeration. In C++11,
15321           // we perform a non-narrowing conversion as part of converted constant
15322           // expression checking.
15323           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15324             if (getLangOpts().MSVCCompat) {
15325               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15326               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15327             } else
15328               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15329           } else
15330             Val = ImpCastExprToType(Val, EltTy,
15331                                     EltTy->isBooleanType() ?
15332                                     CK_IntegralToBoolean : CK_IntegralCast)
15333                     .get();
15334         } else if (getLangOpts().CPlusPlus) {
15335           // C++11 [dcl.enum]p5:
15336           //   If the underlying type is not fixed, the type of each enumerator
15337           //   is the type of its initializing value:
15338           //     - If an initializer is specified for an enumerator, the
15339           //       initializing value has the same type as the expression.
15340           EltTy = Val->getType();
15341         } else {
15342           // C99 6.7.2.2p2:
15343           //   The expression that defines the value of an enumeration constant
15344           //   shall be an integer constant expression that has a value
15345           //   representable as an int.
15346 
15347           // Complain if the value is not representable in an int.
15348           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15349             Diag(IdLoc, diag::ext_enum_value_not_int)
15350               << EnumVal.toString(10) << Val->getSourceRange()
15351               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15352           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15353             // Force the type of the expression to 'int'.
15354             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15355           }
15356           EltTy = Val->getType();
15357         }
15358       }
15359     }
15360   }
15361 
15362   if (!Val) {
15363     if (Enum->isDependentType())
15364       EltTy = Context.DependentTy;
15365     else if (!LastEnumConst) {
15366       // C++0x [dcl.enum]p5:
15367       //   If the underlying type is not fixed, the type of each enumerator
15368       //   is the type of its initializing value:
15369       //     - If no initializer is specified for the first enumerator, the
15370       //       initializing value has an unspecified integral type.
15371       //
15372       // GCC uses 'int' for its unspecified integral type, as does
15373       // C99 6.7.2.2p3.
15374       if (Enum->isFixed()) {
15375         EltTy = Enum->getIntegerType();
15376       }
15377       else {
15378         EltTy = Context.IntTy;
15379       }
15380     } else {
15381       // Assign the last value + 1.
15382       EnumVal = LastEnumConst->getInitVal();
15383       ++EnumVal;
15384       EltTy = LastEnumConst->getType();
15385 
15386       // Check for overflow on increment.
15387       if (EnumVal < LastEnumConst->getInitVal()) {
15388         // C++0x [dcl.enum]p5:
15389         //   If the underlying type is not fixed, the type of each enumerator
15390         //   is the type of its initializing value:
15391         //
15392         //     - Otherwise the type of the initializing value is the same as
15393         //       the type of the initializing value of the preceding enumerator
15394         //       unless the incremented value is not representable in that type,
15395         //       in which case the type is an unspecified integral type
15396         //       sufficient to contain the incremented value. If no such type
15397         //       exists, the program is ill-formed.
15398         QualType T = getNextLargerIntegralType(Context, EltTy);
15399         if (T.isNull() || Enum->isFixed()) {
15400           // There is no integral type larger enough to represent this
15401           // value. Complain, then allow the value to wrap around.
15402           EnumVal = LastEnumConst->getInitVal();
15403           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15404           ++EnumVal;
15405           if (Enum->isFixed())
15406             // When the underlying type is fixed, this is ill-formed.
15407             Diag(IdLoc, diag::err_enumerator_wrapped)
15408               << EnumVal.toString(10)
15409               << EltTy;
15410           else
15411             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15412               << EnumVal.toString(10);
15413         } else {
15414           EltTy = T;
15415         }
15416 
15417         // Retrieve the last enumerator's value, extent that type to the
15418         // type that is supposed to be large enough to represent the incremented
15419         // value, then increment.
15420         EnumVal = LastEnumConst->getInitVal();
15421         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15422         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15423         ++EnumVal;
15424 
15425         // If we're not in C++, diagnose the overflow of enumerator values,
15426         // which in C99 means that the enumerator value is not representable in
15427         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15428         // permits enumerator values that are representable in some larger
15429         // integral type.
15430         if (!getLangOpts().CPlusPlus && !T.isNull())
15431           Diag(IdLoc, diag::warn_enum_value_overflow);
15432       } else if (!getLangOpts().CPlusPlus &&
15433                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15434         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15435         Diag(IdLoc, diag::ext_enum_value_not_int)
15436           << EnumVal.toString(10) << 1;
15437       }
15438     }
15439   }
15440 
15441   if (!EltTy->isDependentType()) {
15442     // Make the enumerator value match the signedness and size of the
15443     // enumerator's type.
15444     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15445     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15446   }
15447 
15448   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15449                                   Val, EnumVal);
15450 }
15451 
15452 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15453                                                 SourceLocation IILoc) {
15454   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15455       !getLangOpts().CPlusPlus)
15456     return SkipBodyInfo();
15457 
15458   // We have an anonymous enum definition. Look up the first enumerator to
15459   // determine if we should merge the definition with an existing one and
15460   // skip the body.
15461   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15462                                          ForRedeclaration);
15463   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15464   if (!PrevECD)
15465     return SkipBodyInfo();
15466 
15467   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15468   NamedDecl *Hidden;
15469   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15470     SkipBodyInfo Skip;
15471     Skip.Previous = Hidden;
15472     return Skip;
15473   }
15474 
15475   return SkipBodyInfo();
15476 }
15477 
15478 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15479                               SourceLocation IdLoc, IdentifierInfo *Id,
15480                               AttributeList *Attr,
15481                               SourceLocation EqualLoc, Expr *Val) {
15482   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15483   EnumConstantDecl *LastEnumConst =
15484     cast_or_null<EnumConstantDecl>(lastEnumConst);
15485 
15486   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15487   // we find one that is.
15488   S = getNonFieldDeclScope(S);
15489 
15490   // Verify that there isn't already something declared with this name in this
15491   // scope.
15492   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15493                                          ForRedeclaration);
15494   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15495     // Maybe we will complain about the shadowed template parameter.
15496     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15497     // Just pretend that we didn't see the previous declaration.
15498     PrevDecl = nullptr;
15499   }
15500 
15501   // C++ [class.mem]p15:
15502   // If T is the name of a class, then each of the following shall have a name
15503   // different from T:
15504   // - every enumerator of every member of class T that is an unscoped
15505   // enumerated type
15506   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15507     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15508                             DeclarationNameInfo(Id, IdLoc));
15509 
15510   EnumConstantDecl *New =
15511     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15512   if (!New)
15513     return nullptr;
15514 
15515   if (PrevDecl) {
15516     // When in C++, we may get a TagDecl with the same name; in this case the
15517     // enum constant will 'hide' the tag.
15518     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15519            "Received TagDecl when not in C++!");
15520     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15521         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15522       if (isa<EnumConstantDecl>(PrevDecl))
15523         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15524       else
15525         Diag(IdLoc, diag::err_redefinition) << Id;
15526       notePreviousDefinition(PrevDecl, IdLoc);
15527       return nullptr;
15528     }
15529   }
15530 
15531   // Process attributes.
15532   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15533   AddPragmaAttributes(S, New);
15534 
15535   // Register this decl in the current scope stack.
15536   New->setAccess(TheEnumDecl->getAccess());
15537   PushOnScopeChains(New, S);
15538 
15539   ActOnDocumentableDecl(New);
15540 
15541   return New;
15542 }
15543 
15544 // Returns true when the enum initial expression does not trigger the
15545 // duplicate enum warning.  A few common cases are exempted as follows:
15546 // Element2 = Element1
15547 // Element2 = Element1 + 1
15548 // Element2 = Element1 - 1
15549 // Where Element2 and Element1 are from the same enum.
15550 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15551   Expr *InitExpr = ECD->getInitExpr();
15552   if (!InitExpr)
15553     return true;
15554   InitExpr = InitExpr->IgnoreImpCasts();
15555 
15556   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15557     if (!BO->isAdditiveOp())
15558       return true;
15559     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15560     if (!IL)
15561       return true;
15562     if (IL->getValue() != 1)
15563       return true;
15564 
15565     InitExpr = BO->getLHS();
15566   }
15567 
15568   // This checks if the elements are from the same enum.
15569   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15570   if (!DRE)
15571     return true;
15572 
15573   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15574   if (!EnumConstant)
15575     return true;
15576 
15577   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15578       Enum)
15579     return true;
15580 
15581   return false;
15582 }
15583 
15584 namespace {
15585 struct DupKey {
15586   int64_t val;
15587   bool isTombstoneOrEmptyKey;
15588   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15589     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15590 };
15591 
15592 static DupKey GetDupKey(const llvm::APSInt& Val) {
15593   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15594                 false);
15595 }
15596 
15597 struct DenseMapInfoDupKey {
15598   static DupKey getEmptyKey() { return DupKey(0, true); }
15599   static DupKey getTombstoneKey() { return DupKey(1, true); }
15600   static unsigned getHashValue(const DupKey Key) {
15601     return (unsigned)(Key.val * 37);
15602   }
15603   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15604     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15605            LHS.val == RHS.val;
15606   }
15607 };
15608 } // end anonymous namespace
15609 
15610 // Emits a warning when an element is implicitly set a value that
15611 // a previous element has already been set to.
15612 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15613                                         EnumDecl *Enum,
15614                                         QualType EnumType) {
15615   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15616     return;
15617   // Avoid anonymous enums
15618   if (!Enum->getIdentifier())
15619     return;
15620 
15621   // Only check for small enums.
15622   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15623     return;
15624 
15625   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15626   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15627 
15628   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15629   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15630           ValueToVectorMap;
15631 
15632   DuplicatesVector DupVector;
15633   ValueToVectorMap EnumMap;
15634 
15635   // Populate the EnumMap with all values represented by enum constants without
15636   // an initialier.
15637   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15638     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15639 
15640     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15641     // this constant.  Skip this enum since it may be ill-formed.
15642     if (!ECD) {
15643       return;
15644     }
15645 
15646     if (ECD->getInitExpr())
15647       continue;
15648 
15649     DupKey Key = GetDupKey(ECD->getInitVal());
15650     DeclOrVector &Entry = EnumMap[Key];
15651 
15652     // First time encountering this value.
15653     if (Entry.isNull())
15654       Entry = ECD;
15655   }
15656 
15657   // Create vectors for any values that has duplicates.
15658   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15659     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15660     if (!ValidDuplicateEnum(ECD, Enum))
15661       continue;
15662 
15663     DupKey Key = GetDupKey(ECD->getInitVal());
15664 
15665     DeclOrVector& Entry = EnumMap[Key];
15666     if (Entry.isNull())
15667       continue;
15668 
15669     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15670       // Ensure constants are different.
15671       if (D == ECD)
15672         continue;
15673 
15674       // Create new vector and push values onto it.
15675       ECDVector *Vec = new ECDVector();
15676       Vec->push_back(D);
15677       Vec->push_back(ECD);
15678 
15679       // Update entry to point to the duplicates vector.
15680       Entry = Vec;
15681 
15682       // Store the vector somewhere we can consult later for quick emission of
15683       // diagnostics.
15684       DupVector.push_back(Vec);
15685       continue;
15686     }
15687 
15688     ECDVector *Vec = Entry.get<ECDVector*>();
15689     // Make sure constants are not added more than once.
15690     if (*Vec->begin() == ECD)
15691       continue;
15692 
15693     Vec->push_back(ECD);
15694   }
15695 
15696   // Emit diagnostics.
15697   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15698                                   DupVectorEnd = DupVector.end();
15699        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15700     ECDVector *Vec = *DupVectorIter;
15701     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15702 
15703     // Emit warning for one enum constant.
15704     ECDVector::iterator I = Vec->begin();
15705     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15706       << (*I)->getName() << (*I)->getInitVal().toString(10)
15707       << (*I)->getSourceRange();
15708     ++I;
15709 
15710     // Emit one note for each of the remaining enum constants with
15711     // the same value.
15712     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15713       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15714         << (*I)->getName() << (*I)->getInitVal().toString(10)
15715         << (*I)->getSourceRange();
15716     delete Vec;
15717   }
15718 }
15719 
15720 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15721                              bool AllowMask) const {
15722   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15723   assert(ED->isCompleteDefinition() && "expected enum definition");
15724 
15725   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15726   llvm::APInt &FlagBits = R.first->second;
15727 
15728   if (R.second) {
15729     for (auto *E : ED->enumerators()) {
15730       const auto &EVal = E->getInitVal();
15731       // Only single-bit enumerators introduce new flag values.
15732       if (EVal.isPowerOf2())
15733         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15734     }
15735   }
15736 
15737   // A value is in a flag enum if either its bits are a subset of the enum's
15738   // flag bits (the first condition) or we are allowing masks and the same is
15739   // true of its complement (the second condition). When masks are allowed, we
15740   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15741   //
15742   // While it's true that any value could be used as a mask, the assumption is
15743   // that a mask will have all of the insignificant bits set. Anything else is
15744   // likely a logic error.
15745   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15746   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15747 }
15748 
15749 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15750                          Decl *EnumDeclX,
15751                          ArrayRef<Decl *> Elements,
15752                          Scope *S, AttributeList *Attr) {
15753   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15754   QualType EnumType = Context.getTypeDeclType(Enum);
15755 
15756   if (Attr)
15757     ProcessDeclAttributeList(S, Enum, Attr);
15758 
15759   if (Enum->isDependentType()) {
15760     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15761       EnumConstantDecl *ECD =
15762         cast_or_null<EnumConstantDecl>(Elements[i]);
15763       if (!ECD) continue;
15764 
15765       ECD->setType(EnumType);
15766     }
15767 
15768     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15769     return;
15770   }
15771 
15772   // TODO: If the result value doesn't fit in an int, it must be a long or long
15773   // long value.  ISO C does not support this, but GCC does as an extension,
15774   // emit a warning.
15775   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15776   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15777   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15778 
15779   // Verify that all the values are okay, compute the size of the values, and
15780   // reverse the list.
15781   unsigned NumNegativeBits = 0;
15782   unsigned NumPositiveBits = 0;
15783 
15784   // Keep track of whether all elements have type int.
15785   bool AllElementsInt = true;
15786 
15787   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15788     EnumConstantDecl *ECD =
15789       cast_or_null<EnumConstantDecl>(Elements[i]);
15790     if (!ECD) continue;  // Already issued a diagnostic.
15791 
15792     const llvm::APSInt &InitVal = ECD->getInitVal();
15793 
15794     // Keep track of the size of positive and negative values.
15795     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15796       NumPositiveBits = std::max(NumPositiveBits,
15797                                  (unsigned)InitVal.getActiveBits());
15798     else
15799       NumNegativeBits = std::max(NumNegativeBits,
15800                                  (unsigned)InitVal.getMinSignedBits());
15801 
15802     // Keep track of whether every enum element has type int (very commmon).
15803     if (AllElementsInt)
15804       AllElementsInt = ECD->getType() == Context.IntTy;
15805   }
15806 
15807   // Figure out the type that should be used for this enum.
15808   QualType BestType;
15809   unsigned BestWidth;
15810 
15811   // C++0x N3000 [conv.prom]p3:
15812   //   An rvalue of an unscoped enumeration type whose underlying
15813   //   type is not fixed can be converted to an rvalue of the first
15814   //   of the following types that can represent all the values of
15815   //   the enumeration: int, unsigned int, long int, unsigned long
15816   //   int, long long int, or unsigned long long int.
15817   // C99 6.4.4.3p2:
15818   //   An identifier declared as an enumeration constant has type int.
15819   // The C99 rule is modified by a gcc extension
15820   QualType BestPromotionType;
15821 
15822   bool Packed = Enum->hasAttr<PackedAttr>();
15823   // -fshort-enums is the equivalent to specifying the packed attribute on all
15824   // enum definitions.
15825   if (LangOpts.ShortEnums)
15826     Packed = true;
15827 
15828   if (Enum->isFixed()) {
15829     BestType = Enum->getIntegerType();
15830     if (BestType->isPromotableIntegerType())
15831       BestPromotionType = Context.getPromotedIntegerType(BestType);
15832     else
15833       BestPromotionType = BestType;
15834 
15835     BestWidth = Context.getIntWidth(BestType);
15836   }
15837   else if (NumNegativeBits) {
15838     // If there is a negative value, figure out the smallest integer type (of
15839     // int/long/longlong) that fits.
15840     // If it's packed, check also if it fits a char or a short.
15841     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15842       BestType = Context.SignedCharTy;
15843       BestWidth = CharWidth;
15844     } else if (Packed && NumNegativeBits <= ShortWidth &&
15845                NumPositiveBits < ShortWidth) {
15846       BestType = Context.ShortTy;
15847       BestWidth = ShortWidth;
15848     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15849       BestType = Context.IntTy;
15850       BestWidth = IntWidth;
15851     } else {
15852       BestWidth = Context.getTargetInfo().getLongWidth();
15853 
15854       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15855         BestType = Context.LongTy;
15856       } else {
15857         BestWidth = Context.getTargetInfo().getLongLongWidth();
15858 
15859         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15860           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15861         BestType = Context.LongLongTy;
15862       }
15863     }
15864     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15865   } else {
15866     // If there is no negative value, figure out the smallest type that fits
15867     // all of the enumerator values.
15868     // If it's packed, check also if it fits a char or a short.
15869     if (Packed && NumPositiveBits <= CharWidth) {
15870       BestType = Context.UnsignedCharTy;
15871       BestPromotionType = Context.IntTy;
15872       BestWidth = CharWidth;
15873     } else if (Packed && NumPositiveBits <= ShortWidth) {
15874       BestType = Context.UnsignedShortTy;
15875       BestPromotionType = Context.IntTy;
15876       BestWidth = ShortWidth;
15877     } else if (NumPositiveBits <= IntWidth) {
15878       BestType = Context.UnsignedIntTy;
15879       BestWidth = IntWidth;
15880       BestPromotionType
15881         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15882                            ? Context.UnsignedIntTy : Context.IntTy;
15883     } else if (NumPositiveBits <=
15884                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15885       BestType = Context.UnsignedLongTy;
15886       BestPromotionType
15887         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15888                            ? Context.UnsignedLongTy : Context.LongTy;
15889     } else {
15890       BestWidth = Context.getTargetInfo().getLongLongWidth();
15891       assert(NumPositiveBits <= BestWidth &&
15892              "How could an initializer get larger than ULL?");
15893       BestType = Context.UnsignedLongLongTy;
15894       BestPromotionType
15895         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15896                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15897     }
15898   }
15899 
15900   // Loop over all of the enumerator constants, changing their types to match
15901   // the type of the enum if needed.
15902   for (auto *D : Elements) {
15903     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15904     if (!ECD) continue;  // Already issued a diagnostic.
15905 
15906     // Standard C says the enumerators have int type, but we allow, as an
15907     // extension, the enumerators to be larger than int size.  If each
15908     // enumerator value fits in an int, type it as an int, otherwise type it the
15909     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15910     // that X has type 'int', not 'unsigned'.
15911 
15912     // Determine whether the value fits into an int.
15913     llvm::APSInt InitVal = ECD->getInitVal();
15914 
15915     // If it fits into an integer type, force it.  Otherwise force it to match
15916     // the enum decl type.
15917     QualType NewTy;
15918     unsigned NewWidth;
15919     bool NewSign;
15920     if (!getLangOpts().CPlusPlus &&
15921         !Enum->isFixed() &&
15922         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15923       NewTy = Context.IntTy;
15924       NewWidth = IntWidth;
15925       NewSign = true;
15926     } else if (ECD->getType() == BestType) {
15927       // Already the right type!
15928       if (getLangOpts().CPlusPlus)
15929         // C++ [dcl.enum]p4: Following the closing brace of an
15930         // enum-specifier, each enumerator has the type of its
15931         // enumeration.
15932         ECD->setType(EnumType);
15933       continue;
15934     } else {
15935       NewTy = BestType;
15936       NewWidth = BestWidth;
15937       NewSign = BestType->isSignedIntegerOrEnumerationType();
15938     }
15939 
15940     // Adjust the APSInt value.
15941     InitVal = InitVal.extOrTrunc(NewWidth);
15942     InitVal.setIsSigned(NewSign);
15943     ECD->setInitVal(InitVal);
15944 
15945     // Adjust the Expr initializer and type.
15946     if (ECD->getInitExpr() &&
15947         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15948       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15949                                                 CK_IntegralCast,
15950                                                 ECD->getInitExpr(),
15951                                                 /*base paths*/ nullptr,
15952                                                 VK_RValue));
15953     if (getLangOpts().CPlusPlus)
15954       // C++ [dcl.enum]p4: Following the closing brace of an
15955       // enum-specifier, each enumerator has the type of its
15956       // enumeration.
15957       ECD->setType(EnumType);
15958     else
15959       ECD->setType(NewTy);
15960   }
15961 
15962   Enum->completeDefinition(BestType, BestPromotionType,
15963                            NumPositiveBits, NumNegativeBits);
15964 
15965   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15966 
15967   if (Enum->isClosedFlag()) {
15968     for (Decl *D : Elements) {
15969       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15970       if (!ECD) continue;  // Already issued a diagnostic.
15971 
15972       llvm::APSInt InitVal = ECD->getInitVal();
15973       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15974           !IsValueInFlagEnum(Enum, InitVal, true))
15975         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15976           << ECD << Enum;
15977     }
15978   }
15979 
15980   // Now that the enum type is defined, ensure it's not been underaligned.
15981   if (Enum->hasAttrs())
15982     CheckAlignasUnderalignment(Enum);
15983 }
15984 
15985 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15986                                   SourceLocation StartLoc,
15987                                   SourceLocation EndLoc) {
15988   StringLiteral *AsmString = cast<StringLiteral>(expr);
15989 
15990   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15991                                                    AsmString, StartLoc,
15992                                                    EndLoc);
15993   CurContext->addDecl(New);
15994   return New;
15995 }
15996 
15997 static void checkModuleImportContext(Sema &S, Module *M,
15998                                      SourceLocation ImportLoc, DeclContext *DC,
15999                                      bool FromInclude = false) {
16000   SourceLocation ExternCLoc;
16001 
16002   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16003     switch (LSD->getLanguage()) {
16004     case LinkageSpecDecl::lang_c:
16005       if (ExternCLoc.isInvalid())
16006         ExternCLoc = LSD->getLocStart();
16007       break;
16008     case LinkageSpecDecl::lang_cxx:
16009       break;
16010     }
16011     DC = LSD->getParent();
16012   }
16013 
16014   while (isa<LinkageSpecDecl>(DC))
16015     DC = DC->getParent();
16016 
16017   if (!isa<TranslationUnitDecl>(DC)) {
16018     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16019                           ? diag::ext_module_import_not_at_top_level_noop
16020                           : diag::err_module_import_not_at_top_level_fatal)
16021         << M->getFullModuleName() << DC;
16022     S.Diag(cast<Decl>(DC)->getLocStart(),
16023            diag::note_module_import_not_at_top_level) << DC;
16024   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16025     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16026       << M->getFullModuleName();
16027     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16028   }
16029 }
16030 
16031 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16032                                            SourceLocation ModuleLoc,
16033                                            ModuleDeclKind MDK,
16034                                            ModuleIdPath Path) {
16035   // A module implementation unit requires that we are not compiling a module
16036   // of any kind. A module interface unit requires that we are not compiling a
16037   // module map.
16038   switch (getLangOpts().getCompilingModule()) {
16039   case LangOptions::CMK_None:
16040     // It's OK to compile a module interface as a normal translation unit.
16041     break;
16042 
16043   case LangOptions::CMK_ModuleInterface:
16044     if (MDK != ModuleDeclKind::Implementation)
16045       break;
16046 
16047     // We were asked to compile a module interface unit but this is a module
16048     // implementation unit. That indicates the 'export' is missing.
16049     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16050       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16051     break;
16052 
16053   case LangOptions::CMK_ModuleMap:
16054     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16055     return nullptr;
16056   }
16057 
16058   // FIXME: Create a ModuleDecl and return it.
16059 
16060   // FIXME: Most of this work should be done by the preprocessor rather than
16061   // here, in order to support macro import.
16062 
16063   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16064   // modules, the dots here are just another character that can appear in a
16065   // module name.
16066   std::string ModuleName;
16067   for (auto &Piece : Path) {
16068     if (!ModuleName.empty())
16069       ModuleName += ".";
16070     ModuleName += Piece.first->getName();
16071   }
16072 
16073   // If a module name was explicitly specified on the command line, it must be
16074   // correct.
16075   if (!getLangOpts().CurrentModule.empty() &&
16076       getLangOpts().CurrentModule != ModuleName) {
16077     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16078         << SourceRange(Path.front().second, Path.back().second)
16079         << getLangOpts().CurrentModule;
16080     return nullptr;
16081   }
16082   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16083 
16084   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16085 
16086   switch (MDK) {
16087   case ModuleDeclKind::Module: {
16088     // FIXME: Check we're not in a submodule.
16089 
16090     // We can't have parsed or imported a definition of this module or parsed a
16091     // module map defining it already.
16092     if (auto *M = Map.findModule(ModuleName)) {
16093       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16094       if (M->DefinitionLoc.isValid())
16095         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16096       else if (const auto *FE = M->getASTFile())
16097         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16098             << FE->getName();
16099       return nullptr;
16100     }
16101 
16102     // Create a Module for the module that we're defining.
16103     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
16104     assert(Mod && "module creation should not fail");
16105 
16106     // Enter the semantic scope of the module.
16107     ActOnModuleBegin(ModuleLoc, Mod);
16108     return nullptr;
16109   }
16110 
16111   case ModuleDeclKind::Partition:
16112     // FIXME: Check we are in a submodule of the named module.
16113     return nullptr;
16114 
16115   case ModuleDeclKind::Implementation:
16116     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16117         PP.getIdentifierInfo(ModuleName), Path[0].second);
16118 
16119     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
16120     if (Import.isInvalid())
16121       return nullptr;
16122     return ConvertDeclToDeclGroup(Import.get());
16123   }
16124 
16125   llvm_unreachable("unexpected module decl kind");
16126 }
16127 
16128 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16129                                    SourceLocation ImportLoc,
16130                                    ModuleIdPath Path) {
16131   Module *Mod =
16132       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16133                                    /*IsIncludeDirective=*/false);
16134   if (!Mod)
16135     return true;
16136 
16137   VisibleModules.setVisible(Mod, ImportLoc);
16138 
16139   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16140 
16141   // FIXME: we should support importing a submodule within a different submodule
16142   // of the same top-level module. Until we do, make it an error rather than
16143   // silently ignoring the import.
16144   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16145   // warn on a redundant import of the current module?
16146   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16147       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16148     Diag(ImportLoc, getLangOpts().isCompilingModule()
16149                         ? diag::err_module_self_import
16150                         : diag::err_module_import_in_implementation)
16151         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16152 
16153   SmallVector<SourceLocation, 2> IdentifierLocs;
16154   Module *ModCheck = Mod;
16155   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16156     // If we've run out of module parents, just drop the remaining identifiers.
16157     // We need the length to be consistent.
16158     if (!ModCheck)
16159       break;
16160     ModCheck = ModCheck->Parent;
16161 
16162     IdentifierLocs.push_back(Path[I].second);
16163   }
16164 
16165   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16166   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16167                                           Mod, IdentifierLocs);
16168   if (!ModuleScopes.empty())
16169     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16170   TU->addDecl(Import);
16171   return Import;
16172 }
16173 
16174 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16175   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16176   BuildModuleInclude(DirectiveLoc, Mod);
16177 }
16178 
16179 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16180   // Determine whether we're in the #include buffer for a module. The #includes
16181   // in that buffer do not qualify as module imports; they're just an
16182   // implementation detail of us building the module.
16183   //
16184   // FIXME: Should we even get ActOnModuleInclude calls for those?
16185   bool IsInModuleIncludes =
16186       TUKind == TU_Module &&
16187       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16188 
16189   bool ShouldAddImport = !IsInModuleIncludes;
16190 
16191   // If this module import was due to an inclusion directive, create an
16192   // implicit import declaration to capture it in the AST.
16193   if (ShouldAddImport) {
16194     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16195     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16196                                                      DirectiveLoc, Mod,
16197                                                      DirectiveLoc);
16198     if (!ModuleScopes.empty())
16199       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16200     TU->addDecl(ImportD);
16201     Consumer.HandleImplicitImportDecl(ImportD);
16202   }
16203 
16204   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16205   VisibleModules.setVisible(Mod, DirectiveLoc);
16206 }
16207 
16208 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16209   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16210 
16211   ModuleScopes.push_back({});
16212   ModuleScopes.back().Module = Mod;
16213   if (getLangOpts().ModulesLocalVisibility)
16214     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16215 
16216   VisibleModules.setVisible(Mod, DirectiveLoc);
16217 
16218   // The enclosing context is now part of this module.
16219   // FIXME: Consider creating a child DeclContext to hold the entities
16220   // lexically within the module.
16221   if (getLangOpts().trackLocalOwningModule()) {
16222     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16223       cast<Decl>(DC)->setModuleOwnershipKind(
16224           getLangOpts().ModulesLocalVisibility
16225               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16226               : Decl::ModuleOwnershipKind::Visible);
16227       cast<Decl>(DC)->setLocalOwningModule(Mod);
16228     }
16229   }
16230 }
16231 
16232 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16233   if (getLangOpts().ModulesLocalVisibility) {
16234     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16235     // Leaving a module hides namespace names, so our visible namespace cache
16236     // is now out of date.
16237     VisibleNamespaceCache.clear();
16238   }
16239 
16240   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16241          "left the wrong module scope");
16242   ModuleScopes.pop_back();
16243 
16244   // We got to the end of processing a local module. Create an
16245   // ImportDecl as we would for an imported module.
16246   FileID File = getSourceManager().getFileID(EomLoc);
16247   SourceLocation DirectiveLoc;
16248   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16249     // We reached the end of a #included module header. Use the #include loc.
16250     assert(File != getSourceManager().getMainFileID() &&
16251            "end of submodule in main source file");
16252     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16253   } else {
16254     // We reached an EOM pragma. Use the pragma location.
16255     DirectiveLoc = EomLoc;
16256   }
16257   BuildModuleInclude(DirectiveLoc, Mod);
16258 
16259   // Any further declarations are in whatever module we returned to.
16260   if (getLangOpts().trackLocalOwningModule()) {
16261     // The parser guarantees that this is the same context that we entered
16262     // the module within.
16263     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16264       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16265       if (!getCurrentModule())
16266         cast<Decl>(DC)->setModuleOwnershipKind(
16267             Decl::ModuleOwnershipKind::Unowned);
16268     }
16269   }
16270 }
16271 
16272 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16273                                                       Module *Mod) {
16274   // Bail if we're not allowed to implicitly import a module here.
16275   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16276       VisibleModules.isVisible(Mod))
16277     return;
16278 
16279   // Create the implicit import declaration.
16280   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16281   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16282                                                    Loc, Mod, Loc);
16283   TU->addDecl(ImportD);
16284   Consumer.HandleImplicitImportDecl(ImportD);
16285 
16286   // Make the module visible.
16287   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16288   VisibleModules.setVisible(Mod, Loc);
16289 }
16290 
16291 /// We have parsed the start of an export declaration, including the '{'
16292 /// (if present).
16293 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16294                                  SourceLocation LBraceLoc) {
16295   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16296 
16297   // C++ Modules TS draft:
16298   //   An export-declaration shall appear in the purview of a module other than
16299   //   the global module.
16300   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16301       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16302     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16303 
16304   //   An export-declaration [...] shall not contain more than one
16305   //   export keyword.
16306   //
16307   // The intent here is that an export-declaration cannot appear within another
16308   // export-declaration.
16309   if (D->isExported())
16310     Diag(ExportLoc, diag::err_export_within_export);
16311 
16312   CurContext->addDecl(D);
16313   PushDeclContext(S, D);
16314   return D;
16315 }
16316 
16317 /// Complete the definition of an export declaration.
16318 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16319   auto *ED = cast<ExportDecl>(D);
16320   if (RBraceLoc.isValid())
16321     ED->setRBraceLoc(RBraceLoc);
16322 
16323   // FIXME: Diagnose export of internal-linkage declaration (including
16324   // anonymous namespace).
16325 
16326   PopDeclContext();
16327   return D;
16328 }
16329 
16330 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16331                                       IdentifierInfo* AliasName,
16332                                       SourceLocation PragmaLoc,
16333                                       SourceLocation NameLoc,
16334                                       SourceLocation AliasNameLoc) {
16335   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16336                                          LookupOrdinaryName);
16337   AsmLabelAttr *Attr =
16338       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16339 
16340   // If a declaration that:
16341   // 1) declares a function or a variable
16342   // 2) has external linkage
16343   // already exists, add a label attribute to it.
16344   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16345     if (isDeclExternC(PrevDecl))
16346       PrevDecl->addAttr(Attr);
16347     else
16348       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16349           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16350   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16351   } else
16352     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16353 }
16354 
16355 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16356                              SourceLocation PragmaLoc,
16357                              SourceLocation NameLoc) {
16358   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16359 
16360   if (PrevDecl) {
16361     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16362   } else {
16363     (void)WeakUndeclaredIdentifiers.insert(
16364       std::pair<IdentifierInfo*,WeakInfo>
16365         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16366   }
16367 }
16368 
16369 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16370                                 IdentifierInfo* AliasName,
16371                                 SourceLocation PragmaLoc,
16372                                 SourceLocation NameLoc,
16373                                 SourceLocation AliasNameLoc) {
16374   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16375                                     LookupOrdinaryName);
16376   WeakInfo W = WeakInfo(Name, NameLoc);
16377 
16378   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16379     if (!PrevDecl->hasAttr<AliasAttr>())
16380       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16381         DeclApplyPragmaWeak(TUScope, ND, W);
16382   } else {
16383     (void)WeakUndeclaredIdentifiers.insert(
16384       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16385   }
16386 }
16387 
16388 Decl *Sema::getObjCDeclContext() const {
16389   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16390 }
16391