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       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowTemplates && getAsTypeTemplateDecl(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              bool IsClassTemplateDeductionContext,
256                              IdentifierInfo **CorrectedII) {
257   // FIXME: Consider allowing this outside C++1z mode as an extension.
258   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260                               !isClassName && !HasTrailingDot;
261 
262   // Determine where we will perform name lookup.
263   DeclContext *LookupCtx = nullptr;
264   if (ObjectTypePtr) {
265     QualType ObjectType = ObjectTypePtr.get();
266     if (ObjectType->isRecordType())
267       LookupCtx = computeDeclContext(ObjectType);
268   } else if (SS && SS->isNotEmpty()) {
269     LookupCtx = computeDeclContext(*SS, false);
270 
271     if (!LookupCtx) {
272       if (isDependentScopeSpecifier(*SS)) {
273         // C++ [temp.res]p3:
274         //   A qualified-id that refers to a type and in which the
275         //   nested-name-specifier depends on a template-parameter (14.6.2)
276         //   shall be prefixed by the keyword typename to indicate that the
277         //   qualified-id denotes a type, forming an
278         //   elaborated-type-specifier (7.1.5.3).
279         //
280         // We therefore do not perform any name lookup if the result would
281         // refer to a member of an unknown specialization.
282         if (!isClassName && !IsCtorOrDtorName)
283           return nullptr;
284 
285         // We know from the grammar that this name refers to a type,
286         // so build a dependent node to describe the type.
287         if (WantNontrivialTypeSourceInfo)
288           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
289 
290         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
292                                        II, NameLoc);
293         return ParsedType::make(T);
294       }
295 
296       return nullptr;
297     }
298 
299     if (!LookupCtx->isDependentContext() &&
300         RequireCompleteDeclContext(*SS, LookupCtx))
301       return nullptr;
302   }
303 
304   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305   // lookup for class-names.
306   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
307                                       LookupOrdinaryName;
308   LookupResult Result(*this, &II, NameLoc, Kind);
309   if (LookupCtx) {
310     // Perform "qualified" name lookup into the declaration context we
311     // computed, which is either the type of the base of a member access
312     // expression or the declaration context associated with a prior
313     // nested-name-specifier.
314     LookupQualifiedName(Result, LookupCtx);
315 
316     if (ObjectTypePtr && Result.empty()) {
317       // C++ [basic.lookup.classref]p3:
318       //   If the unqualified-id is ~type-name, the type-name is looked up
319       //   in the context of the entire postfix-expression. If the type T of
320       //   the object expression is of a class type C, the type-name is also
321       //   looked up in the scope of class C. At least one of the lookups shall
322       //   find a name that refers to (possibly cv-qualified) T.
323       LookupName(Result, S);
324     }
325   } else {
326     // Perform unqualified name lookup.
327     LookupName(Result, S);
328 
329     // For unqualified lookup in a class template in MSVC mode, look into
330     // dependent base classes where the primary class template is known.
331     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332       if (ParsedType TypeInBase =
333               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
334         return TypeInBase;
335     }
336   }
337 
338   NamedDecl *IIDecl = nullptr;
339   switch (Result.getResultKind()) {
340   case LookupResult::NotFound:
341   case LookupResult::NotFoundInCurrentInstantiation:
342     if (CorrectedII) {
343       TypoCorrection Correction =
344           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345                       llvm::make_unique<TypeNameValidatorCCC>(
346                           true, isClassName, AllowDeducedTemplate),
347                       CTK_ErrorRecovery);
348       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
349       TemplateTy Template;
350       bool MemberOfUnknownSpecialization;
351       UnqualifiedId TemplateName;
352       TemplateName.setIdentifier(NewII, NameLoc);
353       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354       CXXScopeSpec NewSS, *NewSSPtr = SS;
355       if (SS && NNS) {
356         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
357         NewSSPtr = &NewSS;
358       }
359       if (Correction && (NNS || NewII != &II) &&
360           // Ignore a correction to a template type as the to-be-corrected
361           // identifier is not a template (typo correction for template names
362           // is handled elsewhere).
363           !(getLangOpts().CPlusPlus && NewSSPtr &&
364             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365                            Template, MemberOfUnknownSpecialization))) {
366         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367                                     isClassName, HasTrailingDot, ObjectTypePtr,
368                                     IsCtorOrDtorName,
369                                     WantNontrivialTypeSourceInfo,
370                                     IsClassTemplateDeductionContext);
371         if (Ty) {
372           diagnoseTypo(Correction,
373                        PDiag(diag::err_unknown_type_or_class_name_suggest)
374                          << Result.getLookupName() << isClassName);
375           if (SS && NNS)
376             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377           *CorrectedII = NewII;
378           return Ty;
379         }
380       }
381     }
382     // If typo correction failed or was not performed, fall through
383   case LookupResult::FoundOverloaded:
384   case LookupResult::FoundUnresolvedValue:
385     Result.suppressDiagnostics();
386     return nullptr;
387 
388   case LookupResult::Ambiguous:
389     // Recover from type-hiding ambiguities by hiding the type.  We'll
390     // do the lookup again when looking for an object, and we can
391     // diagnose the error then.  If we don't do this, then the error
392     // about hiding the type will be immediately followed by an error
393     // that only makes sense if the identifier was treated like a type.
394     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395       Result.suppressDiagnostics();
396       return nullptr;
397     }
398 
399     // Look to see if we have a type anywhere in the list of results.
400     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401          Res != ResEnd; ++Res) {
402       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
404         if (!IIDecl ||
405             (*Res)->getLocation().getRawEncoding() <
406               IIDecl->getLocation().getRawEncoding())
407           IIDecl = *Res;
408       }
409     }
410 
411     if (!IIDecl) {
412       // None of the entities we found is a type, so there is no way
413       // to even assume that the result is a type. In this case, don't
414       // complain about the ambiguity. The parser will either try to
415       // perform this lookup again (e.g., as an object name), which
416       // will produce the ambiguity, or will complain that it expected
417       // a type name.
418       Result.suppressDiagnostics();
419       return nullptr;
420     }
421 
422     // We found a type within the ambiguous lookup; diagnose the
423     // ambiguity and then return that type. This might be the right
424     // answer, or it might not be, but it suppresses any attempt to
425     // perform the name lookup again.
426     break;
427 
428   case LookupResult::Found:
429     IIDecl = Result.getFoundDecl();
430     break;
431   }
432 
433   assert(IIDecl && "Didn't find decl");
434 
435   QualType T;
436   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437     // C++ [class.qual]p2: A lookup that would find the injected-class-name
438     // instead names the constructors of the class, except when naming a class.
439     // This is ill-formed when we're not actually forming a ctor or dtor name.
440     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443         FoundRD->isInjectedClassName() &&
444         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
446           << &II << /*Type*/1;
447 
448     DiagnoseUseOfDecl(IIDecl, NameLoc);
449 
450     T = Context.getTypeDeclType(TD);
451     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454     if (!HasTrailingDot)
455       T = Context.getObjCInterfaceType(IDecl);
456   } else if (AllowDeducedTemplate) {
457     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
459                                                        QualType(), false);
460   }
461 
462   if (T.isNull()) {
463     // If it's not plausibly a type, suppress diagnostics.
464     Result.suppressDiagnostics();
465     return nullptr;
466   }
467 
468   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469   // constructor or destructor name (in such a case, the scope specifier
470   // will be attached to the enclosing Expr or Decl node).
471   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472       !isa<ObjCInterfaceDecl>(IIDecl)) {
473     if (WantNontrivialTypeSourceInfo) {
474       // Construct a type with type-source information.
475       TypeLocBuilder Builder;
476       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
477 
478       T = getElaboratedType(ETK_None, *SS, T);
479       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480       ElabTL.setElaboratedKeywordLoc(SourceLocation());
481       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
483     } else {
484       T = getElaboratedType(ETK_None, *SS, T);
485     }
486   }
487 
488   return ParsedType::make(T);
489 }
490 
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494   for (;; DC = DC->getLookupParent()) {
495     DC = DC->getPrimaryContext();
496     auto *ND = dyn_cast<NamespaceDecl>(DC);
497     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498       return NestedNameSpecifier::Create(Context, nullptr, ND);
499     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501                                          RD->getTypeForDecl());
502     else if (isa<TranslationUnitDecl>(DC))
503       return NestedNameSpecifier::GlobalSpecifier(Context);
504   }
505   llvm_unreachable("something isn't in TU scope?");
506 }
507 
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515     DC = DC->getPrimaryContext();
516     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517       if (MD->getParent()->hasAnyDependentBases())
518         return MD->getParent();
519   }
520   return nullptr;
521 }
522 
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524                                           SourceLocation NameLoc,
525                                           bool IsTemplateTypeArg) {
526   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
527 
528   NestedNameSpecifier *NNS = nullptr;
529   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530     // If we weren't able to parse a default template argument, delay lookup
531     // until instantiation time by making a non-dependent DependentTypeName. We
532     // pretend we saw a NestedNameSpecifier referring to the current scope, and
533     // lookup is retried.
534     // FIXME: This hurts our diagnostic quality, since we get errors like "no
535     // type named 'Foo' in 'current_namespace'" when the user didn't write any
536     // name specifiers.
537     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539   } else if (const CXXRecordDecl *RD =
540                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541     // Build a DependentNameType that will perform lookup into RD at
542     // instantiation time.
543     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544                                       RD->getTypeForDecl());
545 
546     // Diagnose that this identifier was undeclared, and retry the lookup during
547     // template instantiation.
548     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
549                                                                       << RD;
550   } else {
551     // This is not a situation that we should recover from.
552     return ParsedType();
553   }
554 
555   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
556 
557   // Build type location information.  We synthesized the qualifier, so we have
558   // to build a fake NestedNameSpecifierLoc.
559   NestedNameSpecifierLocBuilder NNSLocBuilder;
560   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
562 
563   TypeLocBuilder Builder;
564   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565   DepTL.setNameLoc(NameLoc);
566   DepTL.setElaboratedKeywordLoc(SourceLocation());
567   DepTL.setQualifierLoc(QualifierLoc);
568   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
569 }
570 
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo").  If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577   // Do a tag name lookup in this scope.
578   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579   LookupName(R, S, false);
580   R.suppressDiagnostics();
581   if (R.getResultKind() == LookupResult::Found)
582     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583       switch (TD->getTagKind()) {
584       case TTK_Struct: return DeclSpec::TST_struct;
585       case TTK_Interface: return DeclSpec::TST_interface;
586       case TTK_Union:  return DeclSpec::TST_union;
587       case TTK_Class:  return DeclSpec::TST_class;
588       case TTK_Enum:   return DeclSpec::TST_enum;
589       }
590     }
591 
592   return DeclSpec::TST_unspecified;
593 }
594 
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
599 /// @code
600 /// template<class T> class A {
601 /// public:
602 ///   typedef int TYPE;
603 /// };
604 /// template<class T> class B : public A<T> {
605 /// public:
606 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
607 /// };
608 /// @endcode
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610   if (CurContext->isRecord()) {
611     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
612       return true;
613 
614     const Type *Ty = SS->getScopeRep()->getAsType();
615 
616     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617     for (const auto &Base : RD->bases())
618       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
619         return true;
620     return S->isFunctionPrototypeScope();
621   }
622   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
623 }
624 
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626                                    SourceLocation IILoc,
627                                    Scope *S,
628                                    CXXScopeSpec *SS,
629                                    ParsedType &SuggestedType,
630                                    bool AllowClassTemplates) {
631   // We don't have anything to suggest (yet).
632   SuggestedType = nullptr;
633 
634   // There may have been a typo in the name of the type. Look up typo
635   // results, in case we have something that we can suggest.
636   if (TypoCorrection Corrected =
637           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
638                       llvm::make_unique<TypeNameValidatorCCC>(
639                           false, false, AllowClassTemplates),
640                       CTK_ErrorRecovery)) {
641     if (Corrected.isKeyword()) {
642       // We corrected to a keyword.
643       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
644       II = Corrected.getCorrectionAsIdentifierInfo();
645     } else {
646       // We found a similarly-named type or interface; suggest that.
647       if (!SS || !SS->isSet()) {
648         diagnoseTypo(Corrected,
649                      PDiag(diag::err_unknown_typename_suggest) << II);
650       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
651         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
652         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
653                                 II->getName().equals(CorrectedStr);
654         diagnoseTypo(Corrected,
655                      PDiag(diag::err_unknown_nested_typename_suggest)
656                        << II << DC << DroppedSpecifier << SS->getRange());
657       } else {
658         llvm_unreachable("could not have corrected a typo here");
659       }
660 
661       CXXScopeSpec tmpSS;
662       if (Corrected.getCorrectionSpecifier())
663         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
664                           SourceRange(IILoc));
665       // FIXME: Support class template argument deduction here.
666       SuggestedType =
667           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
668                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
669                       /*IsCtorOrDtorName=*/false,
670                       /*NonTrivialTypeSourceInfo=*/true);
671     }
672     return;
673   }
674 
675   if (getLangOpts().CPlusPlus) {
676     // See if II is a class template that the user forgot to pass arguments to.
677     UnqualifiedId Name;
678     Name.setIdentifier(II, IILoc);
679     CXXScopeSpec EmptySS;
680     TemplateTy TemplateResult;
681     bool MemberOfUnknownSpecialization;
682     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
683                        Name, nullptr, true, TemplateResult,
684                        MemberOfUnknownSpecialization) == TNK_Type_template) {
685       TemplateName TplName = TemplateResult.get();
686       Diag(IILoc, diag::err_template_missing_args)
687         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
688       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
689         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
690           << TplDecl->getTemplateParameters()->getSourceRange();
691       }
692       return;
693     }
694   }
695 
696   // FIXME: Should we move the logic that tries to recover from a missing tag
697   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
698 
699   if (!SS || (!SS->isSet() && !SS->isInvalid()))
700     Diag(IILoc, diag::err_unknown_typename) << II;
701   else if (DeclContext *DC = computeDeclContext(*SS, false))
702     Diag(IILoc, diag::err_typename_nested_not_found)
703       << II << DC << SS->getRange();
704   else if (isDependentScopeSpecifier(*SS)) {
705     unsigned DiagID = diag::err_typename_missing;
706     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
707       DiagID = diag::ext_typename_missing;
708 
709     Diag(SS->getRange().getBegin(), DiagID)
710       << SS->getScopeRep() << II->getName()
711       << SourceRange(SS->getRange().getBegin(), IILoc)
712       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
713     SuggestedType = ActOnTypenameType(S, SourceLocation(),
714                                       *SS, *II, IILoc).get();
715   } else {
716     assert(SS && SS->isInvalid() &&
717            "Invalid scope specifier has already been diagnosed");
718   }
719 }
720 
721 /// \brief Determine whether the given result set contains either a type name
722 /// or
723 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
724   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
725                        NextToken.is(tok::less);
726 
727   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
728     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
729       return true;
730 
731     if (CheckTemplate && isa<TemplateDecl>(*I))
732       return true;
733   }
734 
735   return false;
736 }
737 
738 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
739                                     Scope *S, CXXScopeSpec &SS,
740                                     IdentifierInfo *&Name,
741                                     SourceLocation NameLoc) {
742   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
743   SemaRef.LookupParsedName(R, S, &SS);
744   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
745     StringRef FixItTagName;
746     switch (Tag->getTagKind()) {
747       case TTK_Class:
748         FixItTagName = "class ";
749         break;
750 
751       case TTK_Enum:
752         FixItTagName = "enum ";
753         break;
754 
755       case TTK_Struct:
756         FixItTagName = "struct ";
757         break;
758 
759       case TTK_Interface:
760         FixItTagName = "__interface ";
761         break;
762 
763       case TTK_Union:
764         FixItTagName = "union ";
765         break;
766     }
767 
768     StringRef TagName = FixItTagName.drop_back();
769     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
770       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
771       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
772 
773     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
774          I != IEnd; ++I)
775       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
776         << Name << TagName;
777 
778     // Replace lookup results with just the tag decl.
779     Result.clear(Sema::LookupTagName);
780     SemaRef.LookupParsedName(Result, S, &SS);
781     return true;
782   }
783 
784   return false;
785 }
786 
787 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
788 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
789                                   QualType T, SourceLocation NameLoc) {
790   ASTContext &Context = S.Context;
791 
792   TypeLocBuilder Builder;
793   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
794 
795   T = S.getElaboratedType(ETK_None, SS, T);
796   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
797   ElabTL.setElaboratedKeywordLoc(SourceLocation());
798   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
799   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
800 }
801 
802 Sema::NameClassification
803 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
804                    SourceLocation NameLoc, const Token &NextToken,
805                    bool IsAddressOfOperand,
806                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
807   DeclarationNameInfo NameInfo(Name, NameLoc);
808   ObjCMethodDecl *CurMethod = getCurMethodDecl();
809 
810   if (NextToken.is(tok::coloncolon)) {
811     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
812     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
813   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
814              isCurrentClassName(*Name, S, &SS)) {
815     // Per [class.qual]p2, this names the constructors of SS, not the
816     // injected-class-name. We don't have a classification for that.
817     // There's not much point caching this result, since the parser
818     // will reject it later.
819     return NameClassification::Unknown();
820   }
821 
822   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
823   LookupParsedName(Result, S, &SS, !CurMethod);
824 
825   // For unqualified lookup in a class template in MSVC mode, look into
826   // dependent base classes where the primary class template is known.
827   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
828     if (ParsedType TypeInBase =
829             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
830       return TypeInBase;
831   }
832 
833   // Perform lookup for Objective-C instance variables (including automatically
834   // synthesized instance variables), if we're in an Objective-C method.
835   // FIXME: This lookup really, really needs to be folded in to the normal
836   // unqualified lookup mechanism.
837   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
838     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
839     if (E.get() || E.isInvalid())
840       return E;
841   }
842 
843   bool SecondTry = false;
844   bool IsFilteredTemplateName = false;
845 
846 Corrected:
847   switch (Result.getResultKind()) {
848   case LookupResult::NotFound:
849     // If an unqualified-id is followed by a '(', then we have a function
850     // call.
851     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
852       // In C++, this is an ADL-only call.
853       // FIXME: Reference?
854       if (getLangOpts().CPlusPlus)
855         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
856 
857       // C90 6.3.2.2:
858       //   If the expression that precedes the parenthesized argument list in a
859       //   function call consists solely of an identifier, and if no
860       //   declaration is visible for this identifier, the identifier is
861       //   implicitly declared exactly as if, in the innermost block containing
862       //   the function call, the declaration
863       //
864       //     extern int identifier ();
865       //
866       //   appeared.
867       //
868       // We also allow this in C99 as an extension.
869       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
870         Result.addDecl(D);
871         Result.resolveKind();
872         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
873       }
874     }
875 
876     // In C, we first see whether there is a tag type by the same name, in
877     // which case it's likely that the user just forgot to write "enum",
878     // "struct", or "union".
879     if (!getLangOpts().CPlusPlus && !SecondTry &&
880         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
881       break;
882     }
883 
884     // Perform typo correction to determine if there is another name that is
885     // close to this name.
886     if (!SecondTry && CCC) {
887       SecondTry = true;
888       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
889                                                  Result.getLookupKind(), S,
890                                                  &SS, std::move(CCC),
891                                                  CTK_ErrorRecovery)) {
892         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
893         unsigned QualifiedDiag = diag::err_no_member_suggest;
894 
895         NamedDecl *FirstDecl = Corrected.getFoundDecl();
896         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
897         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
898             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
899           UnqualifiedDiag = diag::err_no_template_suggest;
900           QualifiedDiag = diag::err_no_member_template_suggest;
901         } else if (UnderlyingFirstDecl &&
902                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
903                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
904                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
905           UnqualifiedDiag = diag::err_unknown_typename_suggest;
906           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
907         }
908 
909         if (SS.isEmpty()) {
910           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
911         } else {// FIXME: is this even reachable? Test it.
912           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
913           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
914                                   Name->getName().equals(CorrectedStr);
915           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
916                                     << Name << computeDeclContext(SS, false)
917                                     << DroppedSpecifier << SS.getRange());
918         }
919 
920         // Update the name, so that the caller has the new name.
921         Name = Corrected.getCorrectionAsIdentifierInfo();
922 
923         // Typo correction corrected to a keyword.
924         if (Corrected.isKeyword())
925           return Name;
926 
927         // Also update the LookupResult...
928         // FIXME: This should probably go away at some point
929         Result.clear();
930         Result.setLookupName(Corrected.getCorrection());
931         if (FirstDecl)
932           Result.addDecl(FirstDecl);
933 
934         // If we found an Objective-C instance variable, let
935         // LookupInObjCMethod build the appropriate expression to
936         // reference the ivar.
937         // FIXME: This is a gross hack.
938         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
939           Result.clear();
940           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
941           return E;
942         }
943 
944         goto Corrected;
945       }
946     }
947 
948     // We failed to correct; just fall through and let the parser deal with it.
949     Result.suppressDiagnostics();
950     return NameClassification::Unknown();
951 
952   case LookupResult::NotFoundInCurrentInstantiation: {
953     // We performed name lookup into the current instantiation, and there were
954     // dependent bases, so we treat this result the same way as any other
955     // dependent nested-name-specifier.
956 
957     // C++ [temp.res]p2:
958     //   A name used in a template declaration or definition and that is
959     //   dependent on a template-parameter is assumed not to name a type
960     //   unless the applicable name lookup finds a type name or the name is
961     //   qualified by the keyword typename.
962     //
963     // FIXME: If the next token is '<', we might want to ask the parser to
964     // perform some heroics to see if we actually have a
965     // template-argument-list, which would indicate a missing 'template'
966     // keyword here.
967     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
968                                       NameInfo, IsAddressOfOperand,
969                                       /*TemplateArgs=*/nullptr);
970   }
971 
972   case LookupResult::Found:
973   case LookupResult::FoundOverloaded:
974   case LookupResult::FoundUnresolvedValue:
975     break;
976 
977   case LookupResult::Ambiguous:
978     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
979         hasAnyAcceptableTemplateNames(Result)) {
980       // C++ [temp.local]p3:
981       //   A lookup that finds an injected-class-name (10.2) can result in an
982       //   ambiguity in certain cases (for example, if it is found in more than
983       //   one base class). If all of the injected-class-names that are found
984       //   refer to specializations of the same class template, and if the name
985       //   is followed by a template-argument-list, the reference refers to the
986       //   class template itself and not a specialization thereof, and is not
987       //   ambiguous.
988       //
989       // This filtering can make an ambiguous result into an unambiguous one,
990       // so try again after filtering out template names.
991       FilterAcceptableTemplateNames(Result);
992       if (!Result.isAmbiguous()) {
993         IsFilteredTemplateName = true;
994         break;
995       }
996     }
997 
998     // Diagnose the ambiguity and return an error.
999     return NameClassification::Error();
1000   }
1001 
1002   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1003       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1004     // C++ [temp.names]p3:
1005     //   After name lookup (3.4) finds that a name is a template-name or that
1006     //   an operator-function-id or a literal- operator-id refers to a set of
1007     //   overloaded functions any member of which is a function template if
1008     //   this is followed by a <, the < is always taken as the delimiter of a
1009     //   template-argument-list and never as the less-than operator.
1010     if (!IsFilteredTemplateName)
1011       FilterAcceptableTemplateNames(Result);
1012 
1013     if (!Result.empty()) {
1014       bool IsFunctionTemplate;
1015       bool IsVarTemplate;
1016       TemplateName Template;
1017       if (Result.end() - Result.begin() > 1) {
1018         IsFunctionTemplate = true;
1019         Template = Context.getOverloadedTemplateName(Result.begin(),
1020                                                      Result.end());
1021       } else {
1022         TemplateDecl *TD
1023           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1024         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1025         IsVarTemplate = isa<VarTemplateDecl>(TD);
1026 
1027         if (SS.isSet() && !SS.isInvalid())
1028           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1029                                                     /*TemplateKeyword=*/false,
1030                                                       TD);
1031         else
1032           Template = TemplateName(TD);
1033       }
1034 
1035       if (IsFunctionTemplate) {
1036         // Function templates always go through overload resolution, at which
1037         // point we'll perform the various checks (e.g., accessibility) we need
1038         // to based on which function we selected.
1039         Result.suppressDiagnostics();
1040 
1041         return NameClassification::FunctionTemplate(Template);
1042       }
1043 
1044       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1045                            : NameClassification::TypeTemplate(Template);
1046     }
1047   }
1048 
1049   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1050   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1051     DiagnoseUseOfDecl(Type, NameLoc);
1052     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1053     QualType T = Context.getTypeDeclType(Type);
1054     if (SS.isNotEmpty())
1055       return buildNestedType(*this, SS, T, NameLoc);
1056     return ParsedType::make(T);
1057   }
1058 
1059   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1060   if (!Class) {
1061     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1062     if (ObjCCompatibleAliasDecl *Alias =
1063             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1064       Class = Alias->getClassInterface();
1065   }
1066 
1067   if (Class) {
1068     DiagnoseUseOfDecl(Class, NameLoc);
1069 
1070     if (NextToken.is(tok::period)) {
1071       // Interface. <something> is parsed as a property reference expression.
1072       // Just return "unknown" as a fall-through for now.
1073       Result.suppressDiagnostics();
1074       return NameClassification::Unknown();
1075     }
1076 
1077     QualType T = Context.getObjCInterfaceType(Class);
1078     return ParsedType::make(T);
1079   }
1080 
1081   // We can have a type template here if we're classifying a template argument.
1082   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1083       !isa<VarTemplateDecl>(FirstDecl))
1084     return NameClassification::TypeTemplate(
1085         TemplateName(cast<TemplateDecl>(FirstDecl)));
1086 
1087   // Check for a tag type hidden by a non-type decl in a few cases where it
1088   // seems likely a type is wanted instead of the non-type that was found.
1089   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1090   if ((NextToken.is(tok::identifier) ||
1091        (NextIsOp &&
1092         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1093       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1094     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     QualType T = Context.getTypeDeclType(Type);
1097     if (SS.isNotEmpty())
1098       return buildNestedType(*this, SS, T, NameLoc);
1099     return ParsedType::make(T);
1100   }
1101 
1102   if (FirstDecl->isCXXClassMember())
1103     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1104                                            nullptr, S);
1105 
1106   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1107   return BuildDeclarationNameExpr(SS, Result, ADL);
1108 }
1109 
1110 Sema::TemplateNameKindForDiagnostics
1111 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1112   auto *TD = Name.getAsTemplateDecl();
1113   if (!TD)
1114     return TemplateNameKindForDiagnostics::DependentTemplate;
1115   if (isa<ClassTemplateDecl>(TD))
1116     return TemplateNameKindForDiagnostics::ClassTemplate;
1117   if (isa<FunctionTemplateDecl>(TD))
1118     return TemplateNameKindForDiagnostics::FunctionTemplate;
1119   if (isa<VarTemplateDecl>(TD))
1120     return TemplateNameKindForDiagnostics::VarTemplate;
1121   if (isa<TypeAliasTemplateDecl>(TD))
1122     return TemplateNameKindForDiagnostics::AliasTemplate;
1123   if (isa<TemplateTemplateParmDecl>(TD))
1124     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1125   return TemplateNameKindForDiagnostics::DependentTemplate;
1126 }
1127 
1128 // Determines the context to return to after temporarily entering a
1129 // context.  This depends in an unnecessarily complicated way on the
1130 // exact ordering of callbacks from the parser.
1131 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1132 
1133   // Functions defined inline within classes aren't parsed until we've
1134   // finished parsing the top-level class, so the top-level class is
1135   // the context we'll need to return to.
1136   // A Lambda call operator whose parent is a class must not be treated
1137   // as an inline member function.  A Lambda can be used legally
1138   // either as an in-class member initializer or a default argument.  These
1139   // are parsed once the class has been marked complete and so the containing
1140   // context would be the nested class (when the lambda is defined in one);
1141   // If the class is not complete, then the lambda is being used in an
1142   // ill-formed fashion (such as to specify the width of a bit-field, or
1143   // in an array-bound) - in which case we still want to return the
1144   // lexically containing DC (which could be a nested class).
1145   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1146     DC = DC->getLexicalParent();
1147 
1148     // A function not defined within a class will always return to its
1149     // lexical context.
1150     if (!isa<CXXRecordDecl>(DC))
1151       return DC;
1152 
1153     // A C++ inline method/friend is parsed *after* the topmost class
1154     // it was declared in is fully parsed ("complete");  the topmost
1155     // class is the context we need to return to.
1156     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1157       DC = RD;
1158 
1159     // Return the declaration context of the topmost class the inline method is
1160     // declared in.
1161     return DC;
1162   }
1163 
1164   return DC->getLexicalParent();
1165 }
1166 
1167 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1168   assert(getContainingDC(DC) == CurContext &&
1169       "The next DeclContext should be lexically contained in the current one.");
1170   CurContext = DC;
1171   S->setEntity(DC);
1172 }
1173 
1174 void Sema::PopDeclContext() {
1175   assert(CurContext && "DeclContext imbalance!");
1176 
1177   CurContext = getContainingDC(CurContext);
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180 
1181 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1182                                                                     Decl *D) {
1183   // Unlike PushDeclContext, the context to which we return is not necessarily
1184   // the containing DC of TD, because the new context will be some pre-existing
1185   // TagDecl definition instead of a fresh one.
1186   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1187   CurContext = cast<TagDecl>(D)->getDefinition();
1188   assert(CurContext && "skipping definition of undefined tag");
1189   // Start lookups from the parent of the current context; we don't want to look
1190   // into the pre-existing complete definition.
1191   S->setEntity(CurContext->getLookupParent());
1192   return Result;
1193 }
1194 
1195 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1196   CurContext = static_cast<decltype(CurContext)>(Context);
1197 }
1198 
1199 /// EnterDeclaratorContext - Used when we must lookup names in the context
1200 /// of a declarator's nested name specifier.
1201 ///
1202 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1203   // C++0x [basic.lookup.unqual]p13:
1204   //   A name used in the definition of a static data member of class
1205   //   X (after the qualified-id of the static member) is looked up as
1206   //   if the name was used in a member function of X.
1207   // C++0x [basic.lookup.unqual]p14:
1208   //   If a variable member of a namespace is defined outside of the
1209   //   scope of its namespace then any name used in the definition of
1210   //   the variable member (after the declarator-id) is looked up as
1211   //   if the definition of the variable member occurred in its
1212   //   namespace.
1213   // Both of these imply that we should push a scope whose context
1214   // is the semantic context of the declaration.  We can't use
1215   // PushDeclContext here because that context is not necessarily
1216   // lexically contained in the current context.  Fortunately,
1217   // the containing scope should have the appropriate information.
1218 
1219   assert(!S->getEntity() && "scope already has entity");
1220 
1221 #ifndef NDEBUG
1222   Scope *Ancestor = S->getParent();
1223   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1224   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1225 #endif
1226 
1227   CurContext = DC;
1228   S->setEntity(DC);
1229 }
1230 
1231 void Sema::ExitDeclaratorContext(Scope *S) {
1232   assert(S->getEntity() == CurContext && "Context imbalance!");
1233 
1234   // Switch back to the lexical context.  The safety of this is
1235   // enforced by an assert in EnterDeclaratorContext.
1236   Scope *Ancestor = S->getParent();
1237   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1238   CurContext = Ancestor->getEntity();
1239 
1240   // We don't need to do anything with the scope, which is going to
1241   // disappear.
1242 }
1243 
1244 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1245   // We assume that the caller has already called
1246   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1247   FunctionDecl *FD = D->getAsFunction();
1248   if (!FD)
1249     return;
1250 
1251   // Same implementation as PushDeclContext, but enters the context
1252   // from the lexical parent, rather than the top-level class.
1253   assert(CurContext == FD->getLexicalParent() &&
1254     "The next DeclContext should be lexically contained in the current one.");
1255   CurContext = FD;
1256   S->setEntity(CurContext);
1257 
1258   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1259     ParmVarDecl *Param = FD->getParamDecl(P);
1260     // If the parameter has an identifier, then add it to the scope
1261     if (Param->getIdentifier()) {
1262       S->AddDecl(Param);
1263       IdResolver.AddDecl(Param);
1264     }
1265   }
1266 }
1267 
1268 void Sema::ActOnExitFunctionContext() {
1269   // Same implementation as PopDeclContext, but returns to the lexical parent,
1270   // rather than the top-level class.
1271   assert(CurContext && "DeclContext imbalance!");
1272   CurContext = CurContext->getLexicalParent();
1273   assert(CurContext && "Popped translation unit!");
1274 }
1275 
1276 /// \brief Determine whether we allow overloading of the function
1277 /// PrevDecl with another declaration.
1278 ///
1279 /// This routine determines whether overloading is possible, not
1280 /// whether some new function is actually an overload. It will return
1281 /// true in C++ (where we can always provide overloads) or, as an
1282 /// extension, in C when the previous function is already an
1283 /// overloaded function declaration or has the "overloadable"
1284 /// attribute.
1285 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1286                                        ASTContext &Context) {
1287   if (Context.getLangOpts().CPlusPlus)
1288     return true;
1289 
1290   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1291     return true;
1292 
1293   return (Previous.getResultKind() == LookupResult::Found
1294           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1295 }
1296 
1297 /// Add this decl to the scope shadowed decl chains.
1298 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1299   // Move up the scope chain until we find the nearest enclosing
1300   // non-transparent context. The declaration will be introduced into this
1301   // scope.
1302   while (S->getEntity() && S->getEntity()->isTransparentContext())
1303     S = S->getParent();
1304 
1305   // Add scoped declarations into their context, so that they can be
1306   // found later. Declarations without a context won't be inserted
1307   // into any context.
1308   if (AddToContext)
1309     CurContext->addDecl(D);
1310 
1311   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1312   // are function-local declarations.
1313   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1314       !D->getDeclContext()->getRedeclContext()->Equals(
1315         D->getLexicalDeclContext()->getRedeclContext()) &&
1316       !D->getLexicalDeclContext()->isFunctionOrMethod())
1317     return;
1318 
1319   // Template instantiations should also not be pushed into scope.
1320   if (isa<FunctionDecl>(D) &&
1321       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1322     return;
1323 
1324   // If this replaces anything in the current scope,
1325   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1326                                IEnd = IdResolver.end();
1327   for (; I != IEnd; ++I) {
1328     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1329       S->RemoveDecl(*I);
1330       IdResolver.RemoveDecl(*I);
1331 
1332       // Should only need to replace one decl.
1333       break;
1334     }
1335   }
1336 
1337   S->AddDecl(D);
1338 
1339   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1340     // Implicitly-generated labels may end up getting generated in an order that
1341     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1342     // the label at the appropriate place in the identifier chain.
1343     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1344       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1345       if (IDC == CurContext) {
1346         if (!S->isDeclScope(*I))
1347           continue;
1348       } else if (IDC->Encloses(CurContext))
1349         break;
1350     }
1351 
1352     IdResolver.InsertDeclAfter(I, D);
1353   } else {
1354     IdResolver.AddDecl(D);
1355   }
1356 }
1357 
1358 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1359   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1360     TUScope->AddDecl(D);
1361 }
1362 
1363 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1364                          bool AllowInlineNamespace) {
1365   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1366 }
1367 
1368 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1369   DeclContext *TargetDC = DC->getPrimaryContext();
1370   do {
1371     if (DeclContext *ScopeDC = S->getEntity())
1372       if (ScopeDC->getPrimaryContext() == TargetDC)
1373         return S;
1374   } while ((S = S->getParent()));
1375 
1376   return nullptr;
1377 }
1378 
1379 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1380                                             DeclContext*,
1381                                             ASTContext&);
1382 
1383 /// Filters out lookup results that don't fall within the given scope
1384 /// as determined by isDeclInScope.
1385 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1386                                 bool ConsiderLinkage,
1387                                 bool AllowInlineNamespace) {
1388   LookupResult::Filter F = R.makeFilter();
1389   while (F.hasNext()) {
1390     NamedDecl *D = F.next();
1391 
1392     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1393       continue;
1394 
1395     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1396       continue;
1397 
1398     F.erase();
1399   }
1400 
1401   F.done();
1402 }
1403 
1404 static bool isUsingDecl(NamedDecl *D) {
1405   return isa<UsingShadowDecl>(D) ||
1406          isa<UnresolvedUsingTypenameDecl>(D) ||
1407          isa<UnresolvedUsingValueDecl>(D);
1408 }
1409 
1410 /// Removes using shadow declarations from the lookup results.
1411 static void RemoveUsingDecls(LookupResult &R) {
1412   LookupResult::Filter F = R.makeFilter();
1413   while (F.hasNext())
1414     if (isUsingDecl(F.next()))
1415       F.erase();
1416 
1417   F.done();
1418 }
1419 
1420 /// \brief Check for this common pattern:
1421 /// @code
1422 /// class S {
1423 ///   S(const S&); // DO NOT IMPLEMENT
1424 ///   void operator=(const S&); // DO NOT IMPLEMENT
1425 /// };
1426 /// @endcode
1427 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1428   // FIXME: Should check for private access too but access is set after we get
1429   // the decl here.
1430   if (D->doesThisDeclarationHaveABody())
1431     return false;
1432 
1433   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1434     return CD->isCopyConstructor();
1435   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1436     return Method->isCopyAssignmentOperator();
1437   return false;
1438 }
1439 
1440 // We need this to handle
1441 //
1442 // typedef struct {
1443 //   void *foo() { return 0; }
1444 // } A;
1445 //
1446 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1447 // for example. If 'A', foo will have external linkage. If we have '*A',
1448 // foo will have no linkage. Since we can't know until we get to the end
1449 // of the typedef, this function finds out if D might have non-external linkage.
1450 // Callers should verify at the end of the TU if it D has external linkage or
1451 // not.
1452 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1453   const DeclContext *DC = D->getDeclContext();
1454   while (!DC->isTranslationUnit()) {
1455     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1456       if (!RD->hasNameForLinkage())
1457         return true;
1458     }
1459     DC = DC->getParent();
1460   }
1461 
1462   return !D->isExternallyVisible();
1463 }
1464 
1465 // FIXME: This needs to be refactored; some other isInMainFile users want
1466 // these semantics.
1467 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1468   if (S.TUKind != TU_Complete)
1469     return false;
1470   return S.SourceMgr.isInMainFile(Loc);
1471 }
1472 
1473 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1474   assert(D);
1475 
1476   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1477     return false;
1478 
1479   // Ignore all entities declared within templates, and out-of-line definitions
1480   // of members of class templates.
1481   if (D->getDeclContext()->isDependentContext() ||
1482       D->getLexicalDeclContext()->isDependentContext())
1483     return false;
1484 
1485   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1486     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1487       return false;
1488 
1489     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1490       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1491         return false;
1492     } else {
1493       // 'static inline' functions are defined in headers; don't warn.
1494       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1495         return false;
1496     }
1497 
1498     if (FD->doesThisDeclarationHaveABody() &&
1499         Context.DeclMustBeEmitted(FD))
1500       return false;
1501   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1502     // Constants and utility variables are defined in headers with internal
1503     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1504     // like "inline".)
1505     if (!isMainFileLoc(*this, VD->getLocation()))
1506       return false;
1507 
1508     if (Context.DeclMustBeEmitted(VD))
1509       return false;
1510 
1511     if (VD->isStaticDataMember() &&
1512         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1513       return false;
1514 
1515     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1516       return false;
1517   } else {
1518     return false;
1519   }
1520 
1521   // Only warn for unused decls internal to the translation unit.
1522   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1523   // for inline functions defined in the main source file, for instance.
1524   return mightHaveNonExternalLinkage(D);
1525 }
1526 
1527 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1528   if (!D)
1529     return;
1530 
1531   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532     const FunctionDecl *First = FD->getFirstDecl();
1533     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1534       return; // First should already be in the vector.
1535   }
1536 
1537   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1538     const VarDecl *First = VD->getFirstDecl();
1539     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1540       return; // First should already be in the vector.
1541   }
1542 
1543   if (ShouldWarnIfUnusedFileScopedDecl(D))
1544     UnusedFileScopedDecls.push_back(D);
1545 }
1546 
1547 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1548   if (D->isInvalidDecl())
1549     return false;
1550 
1551   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1552       D->hasAttr<ObjCPreciseLifetimeAttr>())
1553     return false;
1554 
1555   if (isa<LabelDecl>(D))
1556     return true;
1557 
1558   // Except for labels, we only care about unused decls that are local to
1559   // functions.
1560   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1561   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1562     // For dependent types, the diagnostic is deferred.
1563     WithinFunction =
1564         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1565   if (!WithinFunction)
1566     return false;
1567 
1568   if (isa<TypedefNameDecl>(D))
1569     return true;
1570 
1571   // White-list anything that isn't a local variable.
1572   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1573     return false;
1574 
1575   // Types of valid local variables should be complete, so this should succeed.
1576   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1577 
1578     // White-list anything with an __attribute__((unused)) type.
1579     const auto *Ty = VD->getType().getTypePtr();
1580 
1581     // Only look at the outermost level of typedef.
1582     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1583       if (TT->getDecl()->hasAttr<UnusedAttr>())
1584         return false;
1585     }
1586 
1587     // If we failed to complete the type for some reason, or if the type is
1588     // dependent, don't diagnose the variable.
1589     if (Ty->isIncompleteType() || Ty->isDependentType())
1590       return false;
1591 
1592     // Look at the element type to ensure that the warning behaviour is
1593     // consistent for both scalars and arrays.
1594     Ty = Ty->getBaseElementTypeUnsafe();
1595 
1596     if (const TagType *TT = Ty->getAs<TagType>()) {
1597       const TagDecl *Tag = TT->getDecl();
1598       if (Tag->hasAttr<UnusedAttr>())
1599         return false;
1600 
1601       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1602         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1603           return false;
1604 
1605         if (const Expr *Init = VD->getInit()) {
1606           if (const ExprWithCleanups *Cleanups =
1607                   dyn_cast<ExprWithCleanups>(Init))
1608             Init = Cleanups->getSubExpr();
1609           const CXXConstructExpr *Construct =
1610             dyn_cast<CXXConstructExpr>(Init);
1611           if (Construct && !Construct->isElidable()) {
1612             CXXConstructorDecl *CD = Construct->getConstructor();
1613             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1614               return false;
1615           }
1616         }
1617       }
1618     }
1619 
1620     // TODO: __attribute__((unused)) templates?
1621   }
1622 
1623   return true;
1624 }
1625 
1626 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1627                                      FixItHint &Hint) {
1628   if (isa<LabelDecl>(D)) {
1629     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1630                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1631     if (AfterColon.isInvalid())
1632       return;
1633     Hint = FixItHint::CreateRemoval(CharSourceRange::
1634                                     getCharRange(D->getLocStart(), AfterColon));
1635   }
1636 }
1637 
1638 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1639   if (D->getTypeForDecl()->isDependentType())
1640     return;
1641 
1642   for (auto *TmpD : D->decls()) {
1643     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1644       DiagnoseUnusedDecl(T);
1645     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1646       DiagnoseUnusedNestedTypedefs(R);
1647   }
1648 }
1649 
1650 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1651 /// unless they are marked attr(unused).
1652 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1653   if (!ShouldDiagnoseUnusedDecl(D))
1654     return;
1655 
1656   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1657     // typedefs can be referenced later on, so the diagnostics are emitted
1658     // at end-of-translation-unit.
1659     UnusedLocalTypedefNameCandidates.insert(TD);
1660     return;
1661   }
1662 
1663   FixItHint Hint;
1664   GenerateFixForUnusedDecl(D, Context, Hint);
1665 
1666   unsigned DiagID;
1667   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1668     DiagID = diag::warn_unused_exception_param;
1669   else if (isa<LabelDecl>(D))
1670     DiagID = diag::warn_unused_label;
1671   else
1672     DiagID = diag::warn_unused_variable;
1673 
1674   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1675 }
1676 
1677 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1678   // Verify that we have no forward references left.  If so, there was a goto
1679   // or address of a label taken, but no definition of it.  Label fwd
1680   // definitions are indicated with a null substmt which is also not a resolved
1681   // MS inline assembly label name.
1682   bool Diagnose = false;
1683   if (L->isMSAsmLabel())
1684     Diagnose = !L->isResolvedMSAsmLabel();
1685   else
1686     Diagnose = L->getStmt() == nullptr;
1687   if (Diagnose)
1688     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1689 }
1690 
1691 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1692   S->mergeNRVOIntoParent();
1693 
1694   if (S->decl_empty()) return;
1695   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1696          "Scope shouldn't contain decls!");
1697 
1698   for (auto *TmpD : S->decls()) {
1699     assert(TmpD && "This decl didn't get pushed??");
1700 
1701     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1702     NamedDecl *D = cast<NamedDecl>(TmpD);
1703 
1704     if (!D->getDeclName()) continue;
1705 
1706     // Diagnose unused variables in this scope.
1707     if (!S->hasUnrecoverableErrorOccurred()) {
1708       DiagnoseUnusedDecl(D);
1709       if (const auto *RD = dyn_cast<RecordDecl>(D))
1710         DiagnoseUnusedNestedTypedefs(RD);
1711     }
1712 
1713     // If this was a forward reference to a label, verify it was defined.
1714     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1715       CheckPoppedLabel(LD, *this);
1716 
1717     // Remove this name from our lexical scope, and warn on it if we haven't
1718     // already.
1719     IdResolver.RemoveDecl(D);
1720     auto ShadowI = ShadowingDecls.find(D);
1721     if (ShadowI != ShadowingDecls.end()) {
1722       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1723         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1724             << D << FD << FD->getParent();
1725         Diag(FD->getLocation(), diag::note_previous_declaration);
1726       }
1727       ShadowingDecls.erase(ShadowI);
1728     }
1729   }
1730 }
1731 
1732 /// \brief Look for an Objective-C class in the translation unit.
1733 ///
1734 /// \param Id The name of the Objective-C class we're looking for. If
1735 /// typo-correction fixes this name, the Id will be updated
1736 /// to the fixed name.
1737 ///
1738 /// \param IdLoc The location of the name in the translation unit.
1739 ///
1740 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1741 /// if there is no class with the given name.
1742 ///
1743 /// \returns The declaration of the named Objective-C class, or NULL if the
1744 /// class could not be found.
1745 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1746                                               SourceLocation IdLoc,
1747                                               bool DoTypoCorrection) {
1748   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1749   // creation from this context.
1750   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1751 
1752   if (!IDecl && DoTypoCorrection) {
1753     // Perform typo correction at the given location, but only if we
1754     // find an Objective-C class name.
1755     if (TypoCorrection C = CorrectTypo(
1756             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1757             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1758             CTK_ErrorRecovery)) {
1759       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1760       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1761       Id = IDecl->getIdentifier();
1762     }
1763   }
1764   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1765   // This routine must always return a class definition, if any.
1766   if (Def && Def->getDefinition())
1767       Def = Def->getDefinition();
1768   return Def;
1769 }
1770 
1771 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1772 /// from S, where a non-field would be declared. This routine copes
1773 /// with the difference between C and C++ scoping rules in structs and
1774 /// unions. For example, the following code is well-formed in C but
1775 /// ill-formed in C++:
1776 /// @code
1777 /// struct S6 {
1778 ///   enum { BAR } e;
1779 /// };
1780 ///
1781 /// void test_S6() {
1782 ///   struct S6 a;
1783 ///   a.e = BAR;
1784 /// }
1785 /// @endcode
1786 /// For the declaration of BAR, this routine will return a different
1787 /// scope. The scope S will be the scope of the unnamed enumeration
1788 /// within S6. In C++, this routine will return the scope associated
1789 /// with S6, because the enumeration's scope is a transparent
1790 /// context but structures can contain non-field names. In C, this
1791 /// routine will return the translation unit scope, since the
1792 /// enumeration's scope is a transparent context and structures cannot
1793 /// contain non-field names.
1794 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1795   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1796          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1797          (S->isClassScope() && !getLangOpts().CPlusPlus))
1798     S = S->getParent();
1799   return S;
1800 }
1801 
1802 /// \brief Looks up the declaration of "struct objc_super" and
1803 /// saves it for later use in building builtin declaration of
1804 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1805 /// pre-existing declaration exists no action takes place.
1806 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1807                                         IdentifierInfo *II) {
1808   if (!II->isStr("objc_msgSendSuper"))
1809     return;
1810   ASTContext &Context = ThisSema.Context;
1811 
1812   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1813                       SourceLocation(), Sema::LookupTagName);
1814   ThisSema.LookupName(Result, S);
1815   if (Result.getResultKind() == LookupResult::Found)
1816     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1817       Context.setObjCSuperType(Context.getTagDeclType(TD));
1818 }
1819 
1820 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1821   switch (Error) {
1822   case ASTContext::GE_None:
1823     return "";
1824   case ASTContext::GE_Missing_stdio:
1825     return "stdio.h";
1826   case ASTContext::GE_Missing_setjmp:
1827     return "setjmp.h";
1828   case ASTContext::GE_Missing_ucontext:
1829     return "ucontext.h";
1830   }
1831   llvm_unreachable("unhandled error kind");
1832 }
1833 
1834 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1835 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1836 /// if we're creating this built-in in anticipation of redeclaring the
1837 /// built-in.
1838 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1839                                      Scope *S, bool ForRedeclaration,
1840                                      SourceLocation Loc) {
1841   LookupPredefedObjCSuperType(*this, S, II);
1842 
1843   ASTContext::GetBuiltinTypeError Error;
1844   QualType R = Context.GetBuiltinType(ID, Error);
1845   if (Error) {
1846     if (ForRedeclaration)
1847       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1848           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1849     return nullptr;
1850   }
1851 
1852   if (!ForRedeclaration &&
1853       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1854        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1855     Diag(Loc, diag::ext_implicit_lib_function_decl)
1856         << Context.BuiltinInfo.getName(ID) << R;
1857     if (Context.BuiltinInfo.getHeaderName(ID) &&
1858         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1859       Diag(Loc, diag::note_include_header_or_declare)
1860           << Context.BuiltinInfo.getHeaderName(ID)
1861           << Context.BuiltinInfo.getName(ID);
1862   }
1863 
1864   if (R.isNull())
1865     return nullptr;
1866 
1867   DeclContext *Parent = Context.getTranslationUnitDecl();
1868   if (getLangOpts().CPlusPlus) {
1869     LinkageSpecDecl *CLinkageDecl =
1870         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1871                                 LinkageSpecDecl::lang_c, false);
1872     CLinkageDecl->setImplicit();
1873     Parent->addDecl(CLinkageDecl);
1874     Parent = CLinkageDecl;
1875   }
1876 
1877   FunctionDecl *New = FunctionDecl::Create(Context,
1878                                            Parent,
1879                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1880                                            SC_Extern,
1881                                            false,
1882                                            R->isFunctionProtoType());
1883   New->setImplicit();
1884 
1885   // Create Decl objects for each parameter, adding them to the
1886   // FunctionDecl.
1887   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1888     SmallVector<ParmVarDecl*, 16> Params;
1889     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1890       ParmVarDecl *parm =
1891           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1892                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1893                               SC_None, nullptr);
1894       parm->setScopeInfo(0, i);
1895       Params.push_back(parm);
1896     }
1897     New->setParams(Params);
1898   }
1899 
1900   AddKnownFunctionAttributes(New);
1901   RegisterLocallyScopedExternCDecl(New, S);
1902 
1903   // TUScope is the translation-unit scope to insert this function into.
1904   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1905   // relate Scopes to DeclContexts, and probably eliminate CurContext
1906   // entirely, but we're not there yet.
1907   DeclContext *SavedContext = CurContext;
1908   CurContext = Parent;
1909   PushOnScopeChains(New, TUScope);
1910   CurContext = SavedContext;
1911   return New;
1912 }
1913 
1914 /// Typedef declarations don't have linkage, but they still denote the same
1915 /// entity if their types are the same.
1916 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1917 /// isSameEntity.
1918 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1919                                                      TypedefNameDecl *Decl,
1920                                                      LookupResult &Previous) {
1921   // This is only interesting when modules are enabled.
1922   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1923     return;
1924 
1925   // Empty sets are uninteresting.
1926   if (Previous.empty())
1927     return;
1928 
1929   LookupResult::Filter Filter = Previous.makeFilter();
1930   while (Filter.hasNext()) {
1931     NamedDecl *Old = Filter.next();
1932 
1933     // Non-hidden declarations are never ignored.
1934     if (S.isVisible(Old))
1935       continue;
1936 
1937     // Declarations of the same entity are not ignored, even if they have
1938     // different linkages.
1939     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1940       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1941                                 Decl->getUnderlyingType()))
1942         continue;
1943 
1944       // If both declarations give a tag declaration a typedef name for linkage
1945       // purposes, then they declare the same entity.
1946       if (S.getLangOpts().CPlusPlus &&
1947           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1948           Decl->getAnonDeclWithTypedefName())
1949         continue;
1950     }
1951 
1952     Filter.erase();
1953   }
1954 
1955   Filter.done();
1956 }
1957 
1958 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1959   QualType OldType;
1960   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1961     OldType = OldTypedef->getUnderlyingType();
1962   else
1963     OldType = Context.getTypeDeclType(Old);
1964   QualType NewType = New->getUnderlyingType();
1965 
1966   if (NewType->isVariablyModifiedType()) {
1967     // Must not redefine a typedef with a variably-modified type.
1968     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1969     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1970       << Kind << NewType;
1971     if (Old->getLocation().isValid())
1972       Diag(Old->getLocation(), diag::note_previous_definition);
1973     New->setInvalidDecl();
1974     return true;
1975   }
1976 
1977   if (OldType != NewType &&
1978       !OldType->isDependentType() &&
1979       !NewType->isDependentType() &&
1980       !Context.hasSameType(OldType, NewType)) {
1981     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1982     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1983       << Kind << NewType << OldType;
1984     if (Old->getLocation().isValid())
1985       Diag(Old->getLocation(), diag::note_previous_definition);
1986     New->setInvalidDecl();
1987     return true;
1988   }
1989   return false;
1990 }
1991 
1992 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1993 /// same name and scope as a previous declaration 'Old'.  Figure out
1994 /// how to resolve this situation, merging decls or emitting
1995 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1996 ///
1997 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1998                                 LookupResult &OldDecls) {
1999   // If the new decl is known invalid already, don't bother doing any
2000   // merging checks.
2001   if (New->isInvalidDecl()) return;
2002 
2003   // Allow multiple definitions for ObjC built-in typedefs.
2004   // FIXME: Verify the underlying types are equivalent!
2005   if (getLangOpts().ObjC1) {
2006     const IdentifierInfo *TypeID = New->getIdentifier();
2007     switch (TypeID->getLength()) {
2008     default: break;
2009     case 2:
2010       {
2011         if (!TypeID->isStr("id"))
2012           break;
2013         QualType T = New->getUnderlyingType();
2014         if (!T->isPointerType())
2015           break;
2016         if (!T->isVoidPointerType()) {
2017           QualType PT = T->getAs<PointerType>()->getPointeeType();
2018           if (!PT->isStructureType())
2019             break;
2020         }
2021         Context.setObjCIdRedefinitionType(T);
2022         // Install the built-in type for 'id', ignoring the current definition.
2023         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2024         return;
2025       }
2026     case 5:
2027       if (!TypeID->isStr("Class"))
2028         break;
2029       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2030       // Install the built-in type for 'Class', ignoring the current definition.
2031       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2032       return;
2033     case 3:
2034       if (!TypeID->isStr("SEL"))
2035         break;
2036       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2037       // Install the built-in type for 'SEL', ignoring the current definition.
2038       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2039       return;
2040     }
2041     // Fall through - the typedef name was not a builtin type.
2042   }
2043 
2044   // Verify the old decl was also a type.
2045   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2046   if (!Old) {
2047     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2048       << New->getDeclName();
2049 
2050     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2051     if (OldD->getLocation().isValid())
2052       Diag(OldD->getLocation(), diag::note_previous_definition);
2053 
2054     return New->setInvalidDecl();
2055   }
2056 
2057   // If the old declaration is invalid, just give up here.
2058   if (Old->isInvalidDecl())
2059     return New->setInvalidDecl();
2060 
2061   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2062     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2063     auto *NewTag = New->getAnonDeclWithTypedefName();
2064     NamedDecl *Hidden = nullptr;
2065     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2066         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2067         !hasVisibleDefinition(OldTag, &Hidden)) {
2068       // There is a definition of this tag, but it is not visible. Use it
2069       // instead of our tag.
2070       New->setTypeForDecl(OldTD->getTypeForDecl());
2071       if (OldTD->isModed())
2072         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2073                                     OldTD->getUnderlyingType());
2074       else
2075         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2076 
2077       // Make the old tag definition visible.
2078       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2079 
2080       // If this was an unscoped enumeration, yank all of its enumerators
2081       // out of the scope.
2082       if (isa<EnumDecl>(NewTag)) {
2083         Scope *EnumScope = getNonFieldDeclScope(S);
2084         for (auto *D : NewTag->decls()) {
2085           auto *ED = cast<EnumConstantDecl>(D);
2086           assert(EnumScope->isDeclScope(ED));
2087           EnumScope->RemoveDecl(ED);
2088           IdResolver.RemoveDecl(ED);
2089           ED->getLexicalDeclContext()->removeDecl(ED);
2090         }
2091       }
2092     }
2093   }
2094 
2095   // If the typedef types are not identical, reject them in all languages and
2096   // with any extensions enabled.
2097   if (isIncompatibleTypedef(Old, New))
2098     return;
2099 
2100   // The types match.  Link up the redeclaration chain and merge attributes if
2101   // the old declaration was a typedef.
2102   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2103     New->setPreviousDecl(Typedef);
2104     mergeDeclAttributes(New, Old);
2105   }
2106 
2107   if (getLangOpts().MicrosoftExt)
2108     return;
2109 
2110   if (getLangOpts().CPlusPlus) {
2111     // C++ [dcl.typedef]p2:
2112     //   In a given non-class scope, a typedef specifier can be used to
2113     //   redefine the name of any type declared in that scope to refer
2114     //   to the type to which it already refers.
2115     if (!isa<CXXRecordDecl>(CurContext))
2116       return;
2117 
2118     // C++0x [dcl.typedef]p4:
2119     //   In a given class scope, a typedef specifier can be used to redefine
2120     //   any class-name declared in that scope that is not also a typedef-name
2121     //   to refer to the type to which it already refers.
2122     //
2123     // This wording came in via DR424, which was a correction to the
2124     // wording in DR56, which accidentally banned code like:
2125     //
2126     //   struct S {
2127     //     typedef struct A { } A;
2128     //   };
2129     //
2130     // in the C++03 standard. We implement the C++0x semantics, which
2131     // allow the above but disallow
2132     //
2133     //   struct S {
2134     //     typedef int I;
2135     //     typedef int I;
2136     //   };
2137     //
2138     // since that was the intent of DR56.
2139     if (!isa<TypedefNameDecl>(Old))
2140       return;
2141 
2142     Diag(New->getLocation(), diag::err_redefinition)
2143       << New->getDeclName();
2144     Diag(Old->getLocation(), diag::note_previous_definition);
2145     return New->setInvalidDecl();
2146   }
2147 
2148   // Modules always permit redefinition of typedefs, as does C11.
2149   if (getLangOpts().Modules || getLangOpts().C11)
2150     return;
2151 
2152   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2153   // is normally mapped to an error, but can be controlled with
2154   // -Wtypedef-redefinition.  If either the original or the redefinition is
2155   // in a system header, don't emit this for compatibility with GCC.
2156   if (getDiagnostics().getSuppressSystemWarnings() &&
2157       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2158        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2159     return;
2160 
2161   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2162     << New->getDeclName();
2163   Diag(Old->getLocation(), diag::note_previous_definition);
2164 }
2165 
2166 /// DeclhasAttr - returns true if decl Declaration already has the target
2167 /// attribute.
2168 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2169   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2170   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2171   for (const auto *i : D->attrs())
2172     if (i->getKind() == A->getKind()) {
2173       if (Ann) {
2174         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2175           return true;
2176         continue;
2177       }
2178       // FIXME: Don't hardcode this check
2179       if (OA && isa<OwnershipAttr>(i))
2180         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2181       return true;
2182     }
2183 
2184   return false;
2185 }
2186 
2187 static bool isAttributeTargetADefinition(Decl *D) {
2188   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2189     return VD->isThisDeclarationADefinition();
2190   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2191     return TD->isCompleteDefinition() || TD->isBeingDefined();
2192   return true;
2193 }
2194 
2195 /// Merge alignment attributes from \p Old to \p New, taking into account the
2196 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2197 ///
2198 /// \return \c true if any attributes were added to \p New.
2199 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2200   // Look for alignas attributes on Old, and pick out whichever attribute
2201   // specifies the strictest alignment requirement.
2202   AlignedAttr *OldAlignasAttr = nullptr;
2203   AlignedAttr *OldStrictestAlignAttr = nullptr;
2204   unsigned OldAlign = 0;
2205   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2206     // FIXME: We have no way of representing inherited dependent alignments
2207     // in a case like:
2208     //   template<int A, int B> struct alignas(A) X;
2209     //   template<int A, int B> struct alignas(B) X {};
2210     // For now, we just ignore any alignas attributes which are not on the
2211     // definition in such a case.
2212     if (I->isAlignmentDependent())
2213       return false;
2214 
2215     if (I->isAlignas())
2216       OldAlignasAttr = I;
2217 
2218     unsigned Align = I->getAlignment(S.Context);
2219     if (Align > OldAlign) {
2220       OldAlign = Align;
2221       OldStrictestAlignAttr = I;
2222     }
2223   }
2224 
2225   // Look for alignas attributes on New.
2226   AlignedAttr *NewAlignasAttr = nullptr;
2227   unsigned NewAlign = 0;
2228   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2229     if (I->isAlignmentDependent())
2230       return false;
2231 
2232     if (I->isAlignas())
2233       NewAlignasAttr = I;
2234 
2235     unsigned Align = I->getAlignment(S.Context);
2236     if (Align > NewAlign)
2237       NewAlign = Align;
2238   }
2239 
2240   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2241     // Both declarations have 'alignas' attributes. We require them to match.
2242     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2243     // fall short. (If two declarations both have alignas, they must both match
2244     // every definition, and so must match each other if there is a definition.)
2245 
2246     // If either declaration only contains 'alignas(0)' specifiers, then it
2247     // specifies the natural alignment for the type.
2248     if (OldAlign == 0 || NewAlign == 0) {
2249       QualType Ty;
2250       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2251         Ty = VD->getType();
2252       else
2253         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2254 
2255       if (OldAlign == 0)
2256         OldAlign = S.Context.getTypeAlign(Ty);
2257       if (NewAlign == 0)
2258         NewAlign = S.Context.getTypeAlign(Ty);
2259     }
2260 
2261     if (OldAlign != NewAlign) {
2262       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2263         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2264         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2265       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2266     }
2267   }
2268 
2269   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2270     // C++11 [dcl.align]p6:
2271     //   if any declaration of an entity has an alignment-specifier,
2272     //   every defining declaration of that entity shall specify an
2273     //   equivalent alignment.
2274     // C11 6.7.5/7:
2275     //   If the definition of an object does not have an alignment
2276     //   specifier, any other declaration of that object shall also
2277     //   have no alignment specifier.
2278     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2279       << OldAlignasAttr;
2280     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2281       << OldAlignasAttr;
2282   }
2283 
2284   bool AnyAdded = false;
2285 
2286   // Ensure we have an attribute representing the strictest alignment.
2287   if (OldAlign > NewAlign) {
2288     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2289     Clone->setInherited(true);
2290     New->addAttr(Clone);
2291     AnyAdded = true;
2292   }
2293 
2294   // Ensure we have an alignas attribute if the old declaration had one.
2295   if (OldAlignasAttr && !NewAlignasAttr &&
2296       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2297     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2298     Clone->setInherited(true);
2299     New->addAttr(Clone);
2300     AnyAdded = true;
2301   }
2302 
2303   return AnyAdded;
2304 }
2305 
2306 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2307                                const InheritableAttr *Attr,
2308                                Sema::AvailabilityMergeKind AMK) {
2309   // This function copies an attribute Attr from a previous declaration to the
2310   // new declaration D if the new declaration doesn't itself have that attribute
2311   // yet or if that attribute allows duplicates.
2312   // If you're adding a new attribute that requires logic different from
2313   // "use explicit attribute on decl if present, else use attribute from
2314   // previous decl", for example if the attribute needs to be consistent
2315   // between redeclarations, you need to call a custom merge function here.
2316   InheritableAttr *NewAttr = nullptr;
2317   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2318   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2319     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2320                                       AA->isImplicit(), AA->getIntroduced(),
2321                                       AA->getDeprecated(),
2322                                       AA->getObsoleted(), AA->getUnavailable(),
2323                                       AA->getMessage(), AA->getStrict(),
2324                                       AA->getReplacement(), AMK,
2325                                       AttrSpellingListIndex);
2326   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2327     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2328                                     AttrSpellingListIndex);
2329   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2330     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2331                                         AttrSpellingListIndex);
2332   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2333     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2334                                    AttrSpellingListIndex);
2335   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2336     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2337                                    AttrSpellingListIndex);
2338   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2339     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2340                                 FA->getFormatIdx(), FA->getFirstArg(),
2341                                 AttrSpellingListIndex);
2342   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2343     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2344                                  AttrSpellingListIndex);
2345   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2346     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2347                                        AttrSpellingListIndex,
2348                                        IA->getSemanticSpelling());
2349   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2350     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2351                                       &S.Context.Idents.get(AA->getSpelling()),
2352                                       AttrSpellingListIndex);
2353   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2354            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2355             isa<CUDAGlobalAttr>(Attr))) {
2356     // CUDA target attributes are part of function signature for
2357     // overloading purposes and must not be merged.
2358     return false;
2359   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2360     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2361   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2362     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2363   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2364     NewAttr = S.mergeInternalLinkageAttr(
2365         D, InternalLinkageA->getRange(),
2366         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2367         AttrSpellingListIndex);
2368   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2369     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2370                                 &S.Context.Idents.get(CommonA->getSpelling()),
2371                                 AttrSpellingListIndex);
2372   else if (isa<AlignedAttr>(Attr))
2373     // AlignedAttrs are handled separately, because we need to handle all
2374     // such attributes on a declaration at the same time.
2375     NewAttr = nullptr;
2376   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2377            (AMK == Sema::AMK_Override ||
2378             AMK == Sema::AMK_ProtocolImplementation))
2379     NewAttr = nullptr;
2380   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2381     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2382                               UA->getGuid());
2383   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2384     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2385 
2386   if (NewAttr) {
2387     NewAttr->setInherited(true);
2388     D->addAttr(NewAttr);
2389     if (isa<MSInheritanceAttr>(NewAttr))
2390       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2391     return true;
2392   }
2393 
2394   return false;
2395 }
2396 
2397 static const Decl *getDefinition(const Decl *D) {
2398   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2399     return TD->getDefinition();
2400   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2401     const VarDecl *Def = VD->getDefinition();
2402     if (Def)
2403       return Def;
2404     return VD->getActingDefinition();
2405   }
2406   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2407     return FD->getDefinition();
2408   return nullptr;
2409 }
2410 
2411 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2412   for (const auto *Attribute : D->attrs())
2413     if (Attribute->getKind() == Kind)
2414       return true;
2415   return false;
2416 }
2417 
2418 /// checkNewAttributesAfterDef - If we already have a definition, check that
2419 /// there are no new attributes in this declaration.
2420 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2421   if (!New->hasAttrs())
2422     return;
2423 
2424   const Decl *Def = getDefinition(Old);
2425   if (!Def || Def == New)
2426     return;
2427 
2428   AttrVec &NewAttributes = New->getAttrs();
2429   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2430     const Attr *NewAttribute = NewAttributes[I];
2431 
2432     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2433       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2434         Sema::SkipBodyInfo SkipBody;
2435         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2436 
2437         // If we're skipping this definition, drop the "alias" attribute.
2438         if (SkipBody.ShouldSkip) {
2439           NewAttributes.erase(NewAttributes.begin() + I);
2440           --E;
2441           continue;
2442         }
2443       } else {
2444         VarDecl *VD = cast<VarDecl>(New);
2445         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2446                                 VarDecl::TentativeDefinition
2447                             ? diag::err_alias_after_tentative
2448                             : diag::err_redefinition;
2449         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2450         S.Diag(Def->getLocation(), diag::note_previous_definition);
2451         VD->setInvalidDecl();
2452       }
2453       ++I;
2454       continue;
2455     }
2456 
2457     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2458       // Tentative definitions are only interesting for the alias check above.
2459       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2460         ++I;
2461         continue;
2462       }
2463     }
2464 
2465     if (hasAttribute(Def, NewAttribute->getKind())) {
2466       ++I;
2467       continue; // regular attr merging will take care of validating this.
2468     }
2469 
2470     if (isa<C11NoReturnAttr>(NewAttribute)) {
2471       // C's _Noreturn is allowed to be added to a function after it is defined.
2472       ++I;
2473       continue;
2474     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2475       if (AA->isAlignas()) {
2476         // C++11 [dcl.align]p6:
2477         //   if any declaration of an entity has an alignment-specifier,
2478         //   every defining declaration of that entity shall specify an
2479         //   equivalent alignment.
2480         // C11 6.7.5/7:
2481         //   If the definition of an object does not have an alignment
2482         //   specifier, any other declaration of that object shall also
2483         //   have no alignment specifier.
2484         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2485           << AA;
2486         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2487           << AA;
2488         NewAttributes.erase(NewAttributes.begin() + I);
2489         --E;
2490         continue;
2491       }
2492     }
2493 
2494     S.Diag(NewAttribute->getLocation(),
2495            diag::warn_attribute_precede_definition);
2496     S.Diag(Def->getLocation(), diag::note_previous_definition);
2497     NewAttributes.erase(NewAttributes.begin() + I);
2498     --E;
2499   }
2500 }
2501 
2502 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2503 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2504                                AvailabilityMergeKind AMK) {
2505   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2506     UsedAttr *NewAttr = OldAttr->clone(Context);
2507     NewAttr->setInherited(true);
2508     New->addAttr(NewAttr);
2509   }
2510 
2511   if (!Old->hasAttrs() && !New->hasAttrs())
2512     return;
2513 
2514   // Attributes declared post-definition are currently ignored.
2515   checkNewAttributesAfterDef(*this, New, Old);
2516 
2517   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2518     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2519       if (OldA->getLabel() != NewA->getLabel()) {
2520         // This redeclaration changes __asm__ label.
2521         Diag(New->getLocation(), diag::err_different_asm_label);
2522         Diag(OldA->getLocation(), diag::note_previous_declaration);
2523       }
2524     } else if (Old->isUsed()) {
2525       // This redeclaration adds an __asm__ label to a declaration that has
2526       // already been ODR-used.
2527       Diag(New->getLocation(), diag::err_late_asm_label_name)
2528         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2529     }
2530   }
2531 
2532   // Re-declaration cannot add abi_tag's.
2533   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2534     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2535       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2536         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2537                       NewTag) == OldAbiTagAttr->tags_end()) {
2538           Diag(NewAbiTagAttr->getLocation(),
2539                diag::err_new_abi_tag_on_redeclaration)
2540               << NewTag;
2541           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2542         }
2543       }
2544     } else {
2545       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2546       Diag(Old->getLocation(), diag::note_previous_declaration);
2547     }
2548   }
2549 
2550   if (!Old->hasAttrs())
2551     return;
2552 
2553   bool foundAny = New->hasAttrs();
2554 
2555   // Ensure that any moving of objects within the allocated map is done before
2556   // we process them.
2557   if (!foundAny) New->setAttrs(AttrVec());
2558 
2559   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2560     // Ignore deprecated/unavailable/availability attributes if requested.
2561     AvailabilityMergeKind LocalAMK = AMK_None;
2562     if (isa<DeprecatedAttr>(I) ||
2563         isa<UnavailableAttr>(I) ||
2564         isa<AvailabilityAttr>(I)) {
2565       switch (AMK) {
2566       case AMK_None:
2567         continue;
2568 
2569       case AMK_Redeclaration:
2570       case AMK_Override:
2571       case AMK_ProtocolImplementation:
2572         LocalAMK = AMK;
2573         break;
2574       }
2575     }
2576 
2577     // Already handled.
2578     if (isa<UsedAttr>(I))
2579       continue;
2580 
2581     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2582       foundAny = true;
2583   }
2584 
2585   if (mergeAlignedAttrs(*this, New, Old))
2586     foundAny = true;
2587 
2588   if (!foundAny) New->dropAttrs();
2589 }
2590 
2591 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2592 /// to the new one.
2593 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2594                                      const ParmVarDecl *oldDecl,
2595                                      Sema &S) {
2596   // C++11 [dcl.attr.depend]p2:
2597   //   The first declaration of a function shall specify the
2598   //   carries_dependency attribute for its declarator-id if any declaration
2599   //   of the function specifies the carries_dependency attribute.
2600   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2601   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2602     S.Diag(CDA->getLocation(),
2603            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2604     // Find the first declaration of the parameter.
2605     // FIXME: Should we build redeclaration chains for function parameters?
2606     const FunctionDecl *FirstFD =
2607       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2608     const ParmVarDecl *FirstVD =
2609       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2610     S.Diag(FirstVD->getLocation(),
2611            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2612   }
2613 
2614   if (!oldDecl->hasAttrs())
2615     return;
2616 
2617   bool foundAny = newDecl->hasAttrs();
2618 
2619   // Ensure that any moving of objects within the allocated map is
2620   // done before we process them.
2621   if (!foundAny) newDecl->setAttrs(AttrVec());
2622 
2623   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2624     if (!DeclHasAttr(newDecl, I)) {
2625       InheritableAttr *newAttr =
2626         cast<InheritableParamAttr>(I->clone(S.Context));
2627       newAttr->setInherited(true);
2628       newDecl->addAttr(newAttr);
2629       foundAny = true;
2630     }
2631   }
2632 
2633   if (!foundAny) newDecl->dropAttrs();
2634 }
2635 
2636 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2637                                 const ParmVarDecl *OldParam,
2638                                 Sema &S) {
2639   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2640     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2641       if (*Oldnullability != *Newnullability) {
2642         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2643           << DiagNullabilityKind(
2644                *Newnullability,
2645                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2646                 != 0))
2647           << DiagNullabilityKind(
2648                *Oldnullability,
2649                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2650                 != 0));
2651         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2652       }
2653     } else {
2654       QualType NewT = NewParam->getType();
2655       NewT = S.Context.getAttributedType(
2656                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2657                          NewT, NewT);
2658       NewParam->setType(NewT);
2659     }
2660   }
2661 }
2662 
2663 namespace {
2664 
2665 /// Used in MergeFunctionDecl to keep track of function parameters in
2666 /// C.
2667 struct GNUCompatibleParamWarning {
2668   ParmVarDecl *OldParm;
2669   ParmVarDecl *NewParm;
2670   QualType PromotedType;
2671 };
2672 
2673 } // end anonymous namespace
2674 
2675 /// getSpecialMember - get the special member enum for a method.
2676 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2677   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2678     if (Ctor->isDefaultConstructor())
2679       return Sema::CXXDefaultConstructor;
2680 
2681     if (Ctor->isCopyConstructor())
2682       return Sema::CXXCopyConstructor;
2683 
2684     if (Ctor->isMoveConstructor())
2685       return Sema::CXXMoveConstructor;
2686   } else if (isa<CXXDestructorDecl>(MD)) {
2687     return Sema::CXXDestructor;
2688   } else if (MD->isCopyAssignmentOperator()) {
2689     return Sema::CXXCopyAssignment;
2690   } else if (MD->isMoveAssignmentOperator()) {
2691     return Sema::CXXMoveAssignment;
2692   }
2693 
2694   return Sema::CXXInvalid;
2695 }
2696 
2697 // Determine whether the previous declaration was a definition, implicit
2698 // declaration, or a declaration.
2699 template <typename T>
2700 static std::pair<diag::kind, SourceLocation>
2701 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2702   diag::kind PrevDiag;
2703   SourceLocation OldLocation = Old->getLocation();
2704   if (Old->isThisDeclarationADefinition())
2705     PrevDiag = diag::note_previous_definition;
2706   else if (Old->isImplicit()) {
2707     PrevDiag = diag::note_previous_implicit_declaration;
2708     if (OldLocation.isInvalid())
2709       OldLocation = New->getLocation();
2710   } else
2711     PrevDiag = diag::note_previous_declaration;
2712   return std::make_pair(PrevDiag, OldLocation);
2713 }
2714 
2715 /// canRedefineFunction - checks if a function can be redefined. Currently,
2716 /// only extern inline functions can be redefined, and even then only in
2717 /// GNU89 mode.
2718 static bool canRedefineFunction(const FunctionDecl *FD,
2719                                 const LangOptions& LangOpts) {
2720   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2721           !LangOpts.CPlusPlus &&
2722           FD->isInlineSpecified() &&
2723           FD->getStorageClass() == SC_Extern);
2724 }
2725 
2726 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2727   const AttributedType *AT = T->getAs<AttributedType>();
2728   while (AT && !AT->isCallingConv())
2729     AT = AT->getModifiedType()->getAs<AttributedType>();
2730   return AT;
2731 }
2732 
2733 template <typename T>
2734 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2735   const DeclContext *DC = Old->getDeclContext();
2736   if (DC->isRecord())
2737     return false;
2738 
2739   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2740   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2741     return true;
2742   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2743     return true;
2744   return false;
2745 }
2746 
2747 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2748 static bool isExternC(VarTemplateDecl *) { return false; }
2749 
2750 /// \brief Check whether a redeclaration of an entity introduced by a
2751 /// using-declaration is valid, given that we know it's not an overload
2752 /// (nor a hidden tag declaration).
2753 template<typename ExpectedDecl>
2754 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2755                                    ExpectedDecl *New) {
2756   // C++11 [basic.scope.declarative]p4:
2757   //   Given a set of declarations in a single declarative region, each of
2758   //   which specifies the same unqualified name,
2759   //   -- they shall all refer to the same entity, or all refer to functions
2760   //      and function templates; or
2761   //   -- exactly one declaration shall declare a class name or enumeration
2762   //      name that is not a typedef name and the other declarations shall all
2763   //      refer to the same variable or enumerator, or all refer to functions
2764   //      and function templates; in this case the class name or enumeration
2765   //      name is hidden (3.3.10).
2766 
2767   // C++11 [namespace.udecl]p14:
2768   //   If a function declaration in namespace scope or block scope has the
2769   //   same name and the same parameter-type-list as a function introduced
2770   //   by a using-declaration, and the declarations do not declare the same
2771   //   function, the program is ill-formed.
2772 
2773   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2774   if (Old &&
2775       !Old->getDeclContext()->getRedeclContext()->Equals(
2776           New->getDeclContext()->getRedeclContext()) &&
2777       !(isExternC(Old) && isExternC(New)))
2778     Old = nullptr;
2779 
2780   if (!Old) {
2781     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2782     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2783     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2784     return true;
2785   }
2786   return false;
2787 }
2788 
2789 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2790                                             const FunctionDecl *B) {
2791   assert(A->getNumParams() == B->getNumParams());
2792 
2793   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2794     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2795     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2796     if (AttrA == AttrB)
2797       return true;
2798     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2799   };
2800 
2801   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2802 }
2803 
2804 /// MergeFunctionDecl - We just parsed a function 'New' from
2805 /// declarator D which has the same name and scope as a previous
2806 /// declaration 'Old'.  Figure out how to resolve this situation,
2807 /// merging decls or emitting diagnostics as appropriate.
2808 ///
2809 /// In C++, New and Old must be declarations that are not
2810 /// overloaded. Use IsOverload to determine whether New and Old are
2811 /// overloaded, and to select the Old declaration that New should be
2812 /// merged with.
2813 ///
2814 /// Returns true if there was an error, false otherwise.
2815 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2816                              Scope *S, bool MergeTypeWithOld) {
2817   // Verify the old decl was also a function.
2818   FunctionDecl *Old = OldD->getAsFunction();
2819   if (!Old) {
2820     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2821       if (New->getFriendObjectKind()) {
2822         Diag(New->getLocation(), diag::err_using_decl_friend);
2823         Diag(Shadow->getTargetDecl()->getLocation(),
2824              diag::note_using_decl_target);
2825         Diag(Shadow->getUsingDecl()->getLocation(),
2826              diag::note_using_decl) << 0;
2827         return true;
2828       }
2829 
2830       // Check whether the two declarations might declare the same function.
2831       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2832         return true;
2833       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2834     } else {
2835       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2836         << New->getDeclName();
2837       Diag(OldD->getLocation(), diag::note_previous_definition);
2838       return true;
2839     }
2840   }
2841 
2842   // If the old declaration is invalid, just give up here.
2843   if (Old->isInvalidDecl())
2844     return true;
2845 
2846   diag::kind PrevDiag;
2847   SourceLocation OldLocation;
2848   std::tie(PrevDiag, OldLocation) =
2849       getNoteDiagForInvalidRedeclaration(Old, New);
2850 
2851   // Don't complain about this if we're in GNU89 mode and the old function
2852   // is an extern inline function.
2853   // Don't complain about specializations. They are not supposed to have
2854   // storage classes.
2855   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2856       New->getStorageClass() == SC_Static &&
2857       Old->hasExternalFormalLinkage() &&
2858       !New->getTemplateSpecializationInfo() &&
2859       !canRedefineFunction(Old, getLangOpts())) {
2860     if (getLangOpts().MicrosoftExt) {
2861       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2862       Diag(OldLocation, PrevDiag);
2863     } else {
2864       Diag(New->getLocation(), diag::err_static_non_static) << New;
2865       Diag(OldLocation, PrevDiag);
2866       return true;
2867     }
2868   }
2869 
2870   if (New->hasAttr<InternalLinkageAttr>() &&
2871       !Old->hasAttr<InternalLinkageAttr>()) {
2872     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2873         << New->getDeclName();
2874     Diag(Old->getLocation(), diag::note_previous_definition);
2875     New->dropAttr<InternalLinkageAttr>();
2876   }
2877 
2878   // If a function is first declared with a calling convention, but is later
2879   // declared or defined without one, all following decls assume the calling
2880   // convention of the first.
2881   //
2882   // It's OK if a function is first declared without a calling convention,
2883   // but is later declared or defined with the default calling convention.
2884   //
2885   // To test if either decl has an explicit calling convention, we look for
2886   // AttributedType sugar nodes on the type as written.  If they are missing or
2887   // were canonicalized away, we assume the calling convention was implicit.
2888   //
2889   // Note also that we DO NOT return at this point, because we still have
2890   // other tests to run.
2891   QualType OldQType = Context.getCanonicalType(Old->getType());
2892   QualType NewQType = Context.getCanonicalType(New->getType());
2893   const FunctionType *OldType = cast<FunctionType>(OldQType);
2894   const FunctionType *NewType = cast<FunctionType>(NewQType);
2895   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2896   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2897   bool RequiresAdjustment = false;
2898 
2899   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2900     FunctionDecl *First = Old->getFirstDecl();
2901     const FunctionType *FT =
2902         First->getType().getCanonicalType()->castAs<FunctionType>();
2903     FunctionType::ExtInfo FI = FT->getExtInfo();
2904     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2905     if (!NewCCExplicit) {
2906       // Inherit the CC from the previous declaration if it was specified
2907       // there but not here.
2908       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2909       RequiresAdjustment = true;
2910     } else {
2911       // Calling conventions aren't compatible, so complain.
2912       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2913       Diag(New->getLocation(), diag::err_cconv_change)
2914         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2915         << !FirstCCExplicit
2916         << (!FirstCCExplicit ? "" :
2917             FunctionType::getNameForCallConv(FI.getCC()));
2918 
2919       // Put the note on the first decl, since it is the one that matters.
2920       Diag(First->getLocation(), diag::note_previous_declaration);
2921       return true;
2922     }
2923   }
2924 
2925   // FIXME: diagnose the other way around?
2926   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2927     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2928     RequiresAdjustment = true;
2929   }
2930 
2931   // Merge regparm attribute.
2932   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2933       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2934     if (NewTypeInfo.getHasRegParm()) {
2935       Diag(New->getLocation(), diag::err_regparm_mismatch)
2936         << NewType->getRegParmType()
2937         << OldType->getRegParmType();
2938       Diag(OldLocation, diag::note_previous_declaration);
2939       return true;
2940     }
2941 
2942     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2943     RequiresAdjustment = true;
2944   }
2945 
2946   // Merge ns_returns_retained attribute.
2947   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2948     if (NewTypeInfo.getProducesResult()) {
2949       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2950       Diag(OldLocation, diag::note_previous_declaration);
2951       return true;
2952     }
2953 
2954     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2955     RequiresAdjustment = true;
2956   }
2957 
2958   if (RequiresAdjustment) {
2959     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2960     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2961     New->setType(QualType(AdjustedType, 0));
2962     NewQType = Context.getCanonicalType(New->getType());
2963     NewType = cast<FunctionType>(NewQType);
2964   }
2965 
2966   // If this redeclaration makes the function inline, we may need to add it to
2967   // UndefinedButUsed.
2968   if (!Old->isInlined() && New->isInlined() &&
2969       !New->hasAttr<GNUInlineAttr>() &&
2970       !getLangOpts().GNUInline &&
2971       Old->isUsed(false) &&
2972       !Old->isDefined() && !New->isThisDeclarationADefinition())
2973     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2974                                            SourceLocation()));
2975 
2976   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2977   // about it.
2978   if (New->hasAttr<GNUInlineAttr>() &&
2979       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2980     UndefinedButUsed.erase(Old->getCanonicalDecl());
2981   }
2982 
2983   // If pass_object_size params don't match up perfectly, this isn't a valid
2984   // redeclaration.
2985   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2986       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2987     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2988         << New->getDeclName();
2989     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2990     return true;
2991   }
2992 
2993   if (getLangOpts().CPlusPlus) {
2994     // C++1z [over.load]p2
2995     //   Certain function declarations cannot be overloaded:
2996     //     -- Function declarations that differ only in the return type,
2997     //        the exception specification, or both cannot be overloaded.
2998 
2999     // Check the exception specifications match. This may recompute the type of
3000     // both Old and New if it resolved exception specifications, so grab the
3001     // types again after this. Because this updates the type, we do this before
3002     // any of the other checks below, which may update the "de facto" NewQType
3003     // but do not necessarily update the type of New.
3004     if (CheckEquivalentExceptionSpec(Old, New))
3005       return true;
3006     OldQType = Context.getCanonicalType(Old->getType());
3007     NewQType = Context.getCanonicalType(New->getType());
3008 
3009     // Go back to the type source info to compare the declared return types,
3010     // per C++1y [dcl.type.auto]p13:
3011     //   Redeclarations or specializations of a function or function template
3012     //   with a declared return type that uses a placeholder type shall also
3013     //   use that placeholder, not a deduced type.
3014     QualType OldDeclaredReturnType =
3015         (Old->getTypeSourceInfo()
3016              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3017              : OldType)->getReturnType();
3018     QualType NewDeclaredReturnType =
3019         (New->getTypeSourceInfo()
3020              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3021              : NewType)->getReturnType();
3022     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3023         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3024           New->isLocalExternDecl())) {
3025       QualType ResQT;
3026       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3027           OldDeclaredReturnType->isObjCObjectPointerType())
3028         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3029       if (ResQT.isNull()) {
3030         if (New->isCXXClassMember() && New->isOutOfLine())
3031           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3032               << New << New->getReturnTypeSourceRange();
3033         else
3034           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3035               << New->getReturnTypeSourceRange();
3036         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3037                                     << Old->getReturnTypeSourceRange();
3038         return true;
3039       }
3040       else
3041         NewQType = ResQT;
3042     }
3043 
3044     QualType OldReturnType = OldType->getReturnType();
3045     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3046     if (OldReturnType != NewReturnType) {
3047       // If this function has a deduced return type and has already been
3048       // defined, copy the deduced value from the old declaration.
3049       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3050       if (OldAT && OldAT->isDeduced()) {
3051         New->setType(
3052             SubstAutoType(New->getType(),
3053                           OldAT->isDependentType() ? Context.DependentTy
3054                                                    : OldAT->getDeducedType()));
3055         NewQType = Context.getCanonicalType(
3056             SubstAutoType(NewQType,
3057                           OldAT->isDependentType() ? Context.DependentTy
3058                                                    : OldAT->getDeducedType()));
3059       }
3060     }
3061 
3062     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3063     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3064     if (OldMethod && NewMethod) {
3065       // Preserve triviality.
3066       NewMethod->setTrivial(OldMethod->isTrivial());
3067 
3068       // MSVC allows explicit template specialization at class scope:
3069       // 2 CXXMethodDecls referring to the same function will be injected.
3070       // We don't want a redeclaration error.
3071       bool IsClassScopeExplicitSpecialization =
3072                               OldMethod->isFunctionTemplateSpecialization() &&
3073                               NewMethod->isFunctionTemplateSpecialization();
3074       bool isFriend = NewMethod->getFriendObjectKind();
3075 
3076       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3077           !IsClassScopeExplicitSpecialization) {
3078         //    -- Member function declarations with the same name and the
3079         //       same parameter types cannot be overloaded if any of them
3080         //       is a static member function declaration.
3081         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3082           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3083           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3084           return true;
3085         }
3086 
3087         // C++ [class.mem]p1:
3088         //   [...] A member shall not be declared twice in the
3089         //   member-specification, except that a nested class or member
3090         //   class template can be declared and then later defined.
3091         if (ActiveTemplateInstantiations.empty()) {
3092           unsigned NewDiag;
3093           if (isa<CXXConstructorDecl>(OldMethod))
3094             NewDiag = diag::err_constructor_redeclared;
3095           else if (isa<CXXDestructorDecl>(NewMethod))
3096             NewDiag = diag::err_destructor_redeclared;
3097           else if (isa<CXXConversionDecl>(NewMethod))
3098             NewDiag = diag::err_conv_function_redeclared;
3099           else
3100             NewDiag = diag::err_member_redeclared;
3101 
3102           Diag(New->getLocation(), NewDiag);
3103         } else {
3104           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3105             << New << New->getType();
3106         }
3107         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3108         return true;
3109 
3110       // Complain if this is an explicit declaration of a special
3111       // member that was initially declared implicitly.
3112       //
3113       // As an exception, it's okay to befriend such methods in order
3114       // to permit the implicit constructor/destructor/operator calls.
3115       } else if (OldMethod->isImplicit()) {
3116         if (isFriend) {
3117           NewMethod->setImplicit();
3118         } else {
3119           Diag(NewMethod->getLocation(),
3120                diag::err_definition_of_implicitly_declared_member)
3121             << New << getSpecialMember(OldMethod);
3122           return true;
3123         }
3124       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3125         Diag(NewMethod->getLocation(),
3126              diag::err_definition_of_explicitly_defaulted_member)
3127           << getSpecialMember(OldMethod);
3128         return true;
3129       }
3130     }
3131 
3132     // C++11 [dcl.attr.noreturn]p1:
3133     //   The first declaration of a function shall specify the noreturn
3134     //   attribute if any declaration of that function specifies the noreturn
3135     //   attribute.
3136     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3137     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3138       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3139       Diag(Old->getFirstDecl()->getLocation(),
3140            diag::note_noreturn_missing_first_decl);
3141     }
3142 
3143     // C++11 [dcl.attr.depend]p2:
3144     //   The first declaration of a function shall specify the
3145     //   carries_dependency attribute for its declarator-id if any declaration
3146     //   of the function specifies the carries_dependency attribute.
3147     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3148     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3149       Diag(CDA->getLocation(),
3150            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3151       Diag(Old->getFirstDecl()->getLocation(),
3152            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3153     }
3154 
3155     // (C++98 8.3.5p3):
3156     //   All declarations for a function shall agree exactly in both the
3157     //   return type and the parameter-type-list.
3158     // We also want to respect all the extended bits except noreturn.
3159 
3160     // noreturn should now match unless the old type info didn't have it.
3161     QualType OldQTypeForComparison = OldQType;
3162     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3163       auto *OldType = OldQType->castAs<FunctionProtoType>();
3164       const FunctionType *OldTypeForComparison
3165         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3166       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3167       assert(OldQTypeForComparison.isCanonical());
3168     }
3169 
3170     if (haveIncompatibleLanguageLinkages(Old, New)) {
3171       // As a special case, retain the language linkage from previous
3172       // declarations of a friend function as an extension.
3173       //
3174       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3175       // and is useful because there's otherwise no way to specify language
3176       // linkage within class scope.
3177       //
3178       // Check cautiously as the friend object kind isn't yet complete.
3179       if (New->getFriendObjectKind() != Decl::FOK_None) {
3180         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3181         Diag(OldLocation, PrevDiag);
3182       } else {
3183         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3184         Diag(OldLocation, PrevDiag);
3185         return true;
3186       }
3187     }
3188 
3189     if (OldQTypeForComparison == NewQType)
3190       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3191 
3192     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3193         New->isLocalExternDecl()) {
3194       // It's OK if we couldn't merge types for a local function declaraton
3195       // if either the old or new type is dependent. We'll merge the types
3196       // when we instantiate the function.
3197       return false;
3198     }
3199 
3200     // Fall through for conflicting redeclarations and redefinitions.
3201   }
3202 
3203   // C: Function types need to be compatible, not identical. This handles
3204   // duplicate function decls like "void f(int); void f(enum X);" properly.
3205   if (!getLangOpts().CPlusPlus &&
3206       Context.typesAreCompatible(OldQType, NewQType)) {
3207     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3208     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3209     const FunctionProtoType *OldProto = nullptr;
3210     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3211         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3212       // The old declaration provided a function prototype, but the
3213       // new declaration does not. Merge in the prototype.
3214       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3215       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3216       NewQType =
3217           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3218                                   OldProto->getExtProtoInfo());
3219       New->setType(NewQType);
3220       New->setHasInheritedPrototype();
3221 
3222       // Synthesize parameters with the same types.
3223       SmallVector<ParmVarDecl*, 16> Params;
3224       for (const auto &ParamType : OldProto->param_types()) {
3225         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3226                                                  SourceLocation(), nullptr,
3227                                                  ParamType, /*TInfo=*/nullptr,
3228                                                  SC_None, nullptr);
3229         Param->setScopeInfo(0, Params.size());
3230         Param->setImplicit();
3231         Params.push_back(Param);
3232       }
3233 
3234       New->setParams(Params);
3235     }
3236 
3237     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3238   }
3239 
3240   // GNU C permits a K&R definition to follow a prototype declaration
3241   // if the declared types of the parameters in the K&R definition
3242   // match the types in the prototype declaration, even when the
3243   // promoted types of the parameters from the K&R definition differ
3244   // from the types in the prototype. GCC then keeps the types from
3245   // the prototype.
3246   //
3247   // If a variadic prototype is followed by a non-variadic K&R definition,
3248   // the K&R definition becomes variadic.  This is sort of an edge case, but
3249   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3250   // C99 6.9.1p8.
3251   if (!getLangOpts().CPlusPlus &&
3252       Old->hasPrototype() && !New->hasPrototype() &&
3253       New->getType()->getAs<FunctionProtoType>() &&
3254       Old->getNumParams() == New->getNumParams()) {
3255     SmallVector<QualType, 16> ArgTypes;
3256     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3257     const FunctionProtoType *OldProto
3258       = Old->getType()->getAs<FunctionProtoType>();
3259     const FunctionProtoType *NewProto
3260       = New->getType()->getAs<FunctionProtoType>();
3261 
3262     // Determine whether this is the GNU C extension.
3263     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3264                                                NewProto->getReturnType());
3265     bool LooseCompatible = !MergedReturn.isNull();
3266     for (unsigned Idx = 0, End = Old->getNumParams();
3267          LooseCompatible && Idx != End; ++Idx) {
3268       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3269       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3270       if (Context.typesAreCompatible(OldParm->getType(),
3271                                      NewProto->getParamType(Idx))) {
3272         ArgTypes.push_back(NewParm->getType());
3273       } else if (Context.typesAreCompatible(OldParm->getType(),
3274                                             NewParm->getType(),
3275                                             /*CompareUnqualified=*/true)) {
3276         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3277                                            NewProto->getParamType(Idx) };
3278         Warnings.push_back(Warn);
3279         ArgTypes.push_back(NewParm->getType());
3280       } else
3281         LooseCompatible = false;
3282     }
3283 
3284     if (LooseCompatible) {
3285       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3286         Diag(Warnings[Warn].NewParm->getLocation(),
3287              diag::ext_param_promoted_not_compatible_with_prototype)
3288           << Warnings[Warn].PromotedType
3289           << Warnings[Warn].OldParm->getType();
3290         if (Warnings[Warn].OldParm->getLocation().isValid())
3291           Diag(Warnings[Warn].OldParm->getLocation(),
3292                diag::note_previous_declaration);
3293       }
3294 
3295       if (MergeTypeWithOld)
3296         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3297                                              OldProto->getExtProtoInfo()));
3298       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3299     }
3300 
3301     // Fall through to diagnose conflicting types.
3302   }
3303 
3304   // A function that has already been declared has been redeclared or
3305   // defined with a different type; show an appropriate diagnostic.
3306 
3307   // If the previous declaration was an implicitly-generated builtin
3308   // declaration, then at the very least we should use a specialized note.
3309   unsigned BuiltinID;
3310   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3311     // If it's actually a library-defined builtin function like 'malloc'
3312     // or 'printf', just warn about the incompatible redeclaration.
3313     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3314       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3315       Diag(OldLocation, diag::note_previous_builtin_declaration)
3316         << Old << Old->getType();
3317 
3318       // If this is a global redeclaration, just forget hereafter
3319       // about the "builtin-ness" of the function.
3320       //
3321       // Doing this for local extern declarations is problematic.  If
3322       // the builtin declaration remains visible, a second invalid
3323       // local declaration will produce a hard error; if it doesn't
3324       // remain visible, a single bogus local redeclaration (which is
3325       // actually only a warning) could break all the downstream code.
3326       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3327         New->getIdentifier()->revertBuiltin();
3328 
3329       return false;
3330     }
3331 
3332     PrevDiag = diag::note_previous_builtin_declaration;
3333   }
3334 
3335   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3336   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3337   return true;
3338 }
3339 
3340 /// \brief Completes the merge of two function declarations that are
3341 /// known to be compatible.
3342 ///
3343 /// This routine handles the merging of attributes and other
3344 /// properties of function declarations from the old declaration to
3345 /// the new declaration, once we know that New is in fact a
3346 /// redeclaration of Old.
3347 ///
3348 /// \returns false
3349 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3350                                         Scope *S, bool MergeTypeWithOld) {
3351   // Merge the attributes
3352   mergeDeclAttributes(New, Old);
3353 
3354   // Merge "pure" flag.
3355   if (Old->isPure())
3356     New->setPure();
3357 
3358   // Merge "used" flag.
3359   if (Old->getMostRecentDecl()->isUsed(false))
3360     New->setIsUsed();
3361 
3362   // Merge attributes from the parameters.  These can mismatch with K&R
3363   // declarations.
3364   if (New->getNumParams() == Old->getNumParams())
3365       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3366         ParmVarDecl *NewParam = New->getParamDecl(i);
3367         ParmVarDecl *OldParam = Old->getParamDecl(i);
3368         mergeParamDeclAttributes(NewParam, OldParam, *this);
3369         mergeParamDeclTypes(NewParam, OldParam, *this);
3370       }
3371 
3372   if (getLangOpts().CPlusPlus)
3373     return MergeCXXFunctionDecl(New, Old, S);
3374 
3375   // Merge the function types so the we get the composite types for the return
3376   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3377   // was visible.
3378   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3379   if (!Merged.isNull() && MergeTypeWithOld)
3380     New->setType(Merged);
3381 
3382   return false;
3383 }
3384 
3385 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3386                                 ObjCMethodDecl *oldMethod) {
3387   // Merge the attributes, including deprecated/unavailable
3388   AvailabilityMergeKind MergeKind =
3389     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3390       ? AMK_ProtocolImplementation
3391       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3392                                                        : AMK_Override;
3393 
3394   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3395 
3396   // Merge attributes from the parameters.
3397   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3398                                        oe = oldMethod->param_end();
3399   for (ObjCMethodDecl::param_iterator
3400          ni = newMethod->param_begin(), ne = newMethod->param_end();
3401        ni != ne && oi != oe; ++ni, ++oi)
3402     mergeParamDeclAttributes(*ni, *oi, *this);
3403 
3404   CheckObjCMethodOverride(newMethod, oldMethod);
3405 }
3406 
3407 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3408   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3409 
3410   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3411          ? diag::err_redefinition_different_type
3412          : diag::err_redeclaration_different_type)
3413     << New->getDeclName() << New->getType() << Old->getType();
3414 
3415   diag::kind PrevDiag;
3416   SourceLocation OldLocation;
3417   std::tie(PrevDiag, OldLocation)
3418     = getNoteDiagForInvalidRedeclaration(Old, New);
3419   S.Diag(OldLocation, PrevDiag);
3420   New->setInvalidDecl();
3421 }
3422 
3423 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3424 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3425 /// emitting diagnostics as appropriate.
3426 ///
3427 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3428 /// to here in AddInitializerToDecl. We can't check them before the initializer
3429 /// is attached.
3430 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3431                              bool MergeTypeWithOld) {
3432   if (New->isInvalidDecl() || Old->isInvalidDecl())
3433     return;
3434 
3435   QualType MergedT;
3436   if (getLangOpts().CPlusPlus) {
3437     if (New->getType()->isUndeducedType()) {
3438       // We don't know what the new type is until the initializer is attached.
3439       return;
3440     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3441       // These could still be something that needs exception specs checked.
3442       return MergeVarDeclExceptionSpecs(New, Old);
3443     }
3444     // C++ [basic.link]p10:
3445     //   [...] the types specified by all declarations referring to a given
3446     //   object or function shall be identical, except that declarations for an
3447     //   array object can specify array types that differ by the presence or
3448     //   absence of a major array bound (8.3.4).
3449     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3450       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3451       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3452 
3453       // We are merging a variable declaration New into Old. If it has an array
3454       // bound, and that bound differs from Old's bound, we should diagnose the
3455       // mismatch.
3456       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3457         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3458              PrevVD = PrevVD->getPreviousDecl()) {
3459           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3460           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3461             continue;
3462 
3463           if (!Context.hasSameType(NewArray, PrevVDTy))
3464             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3465         }
3466       }
3467 
3468       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3469         if (Context.hasSameType(OldArray->getElementType(),
3470                                 NewArray->getElementType()))
3471           MergedT = New->getType();
3472       }
3473       // FIXME: Check visibility. New is hidden but has a complete type. If New
3474       // has no array bound, it should not inherit one from Old, if Old is not
3475       // visible.
3476       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3477         if (Context.hasSameType(OldArray->getElementType(),
3478                                 NewArray->getElementType()))
3479           MergedT = Old->getType();
3480       }
3481     }
3482     else if (New->getType()->isObjCObjectPointerType() &&
3483                Old->getType()->isObjCObjectPointerType()) {
3484       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3485                                               Old->getType());
3486     }
3487   } else {
3488     // C 6.2.7p2:
3489     //   All declarations that refer to the same object or function shall have
3490     //   compatible type.
3491     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3492   }
3493   if (MergedT.isNull()) {
3494     // It's OK if we couldn't merge types if either type is dependent, for a
3495     // block-scope variable. In other cases (static data members of class
3496     // templates, variable templates, ...), we require the types to be
3497     // equivalent.
3498     // FIXME: The C++ standard doesn't say anything about this.
3499     if ((New->getType()->isDependentType() ||
3500          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3501       // If the old type was dependent, we can't merge with it, so the new type
3502       // becomes dependent for now. We'll reproduce the original type when we
3503       // instantiate the TypeSourceInfo for the variable.
3504       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3505         New->setType(Context.DependentTy);
3506       return;
3507     }
3508     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3509   }
3510 
3511   // Don't actually update the type on the new declaration if the old
3512   // declaration was an extern declaration in a different scope.
3513   if (MergeTypeWithOld)
3514     New->setType(MergedT);
3515 }
3516 
3517 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3518                                   LookupResult &Previous) {
3519   // C11 6.2.7p4:
3520   //   For an identifier with internal or external linkage declared
3521   //   in a scope in which a prior declaration of that identifier is
3522   //   visible, if the prior declaration specifies internal or
3523   //   external linkage, the type of the identifier at the later
3524   //   declaration becomes the composite type.
3525   //
3526   // If the variable isn't visible, we do not merge with its type.
3527   if (Previous.isShadowed())
3528     return false;
3529 
3530   if (S.getLangOpts().CPlusPlus) {
3531     // C++11 [dcl.array]p3:
3532     //   If there is a preceding declaration of the entity in the same
3533     //   scope in which the bound was specified, an omitted array bound
3534     //   is taken to be the same as in that earlier declaration.
3535     return NewVD->isPreviousDeclInSameBlockScope() ||
3536            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3537             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3538   } else {
3539     // If the old declaration was function-local, don't merge with its
3540     // type unless we're in the same function.
3541     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3542            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3543   }
3544 }
3545 
3546 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3547 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3548 /// situation, merging decls or emitting diagnostics as appropriate.
3549 ///
3550 /// Tentative definition rules (C99 6.9.2p2) are checked by
3551 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3552 /// definitions here, since the initializer hasn't been attached.
3553 ///
3554 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3555   // If the new decl is already invalid, don't do any other checking.
3556   if (New->isInvalidDecl())
3557     return;
3558 
3559   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3560     return;
3561 
3562   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3563 
3564   // Verify the old decl was also a variable or variable template.
3565   VarDecl *Old = nullptr;
3566   VarTemplateDecl *OldTemplate = nullptr;
3567   if (Previous.isSingleResult()) {
3568     if (NewTemplate) {
3569       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3570       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3571 
3572       if (auto *Shadow =
3573               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3574         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3575           return New->setInvalidDecl();
3576     } else {
3577       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3578 
3579       if (auto *Shadow =
3580               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3581         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3582           return New->setInvalidDecl();
3583     }
3584   }
3585   if (!Old) {
3586     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3587       << New->getDeclName();
3588     Diag(Previous.getRepresentativeDecl()->getLocation(),
3589          diag::note_previous_definition);
3590     return New->setInvalidDecl();
3591   }
3592 
3593   // Ensure the template parameters are compatible.
3594   if (NewTemplate &&
3595       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3596                                       OldTemplate->getTemplateParameters(),
3597                                       /*Complain=*/true, TPL_TemplateMatch))
3598     return New->setInvalidDecl();
3599 
3600   // C++ [class.mem]p1:
3601   //   A member shall not be declared twice in the member-specification [...]
3602   //
3603   // Here, we need only consider static data members.
3604   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3605     Diag(New->getLocation(), diag::err_duplicate_member)
3606       << New->getIdentifier();
3607     Diag(Old->getLocation(), diag::note_previous_declaration);
3608     New->setInvalidDecl();
3609   }
3610 
3611   mergeDeclAttributes(New, Old);
3612   // Warn if an already-declared variable is made a weak_import in a subsequent
3613   // declaration
3614   if (New->hasAttr<WeakImportAttr>() &&
3615       Old->getStorageClass() == SC_None &&
3616       !Old->hasAttr<WeakImportAttr>()) {
3617     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3618     Diag(Old->getLocation(), diag::note_previous_definition);
3619     // Remove weak_import attribute on new declaration.
3620     New->dropAttr<WeakImportAttr>();
3621   }
3622 
3623   if (New->hasAttr<InternalLinkageAttr>() &&
3624       !Old->hasAttr<InternalLinkageAttr>()) {
3625     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3626         << New->getDeclName();
3627     Diag(Old->getLocation(), diag::note_previous_definition);
3628     New->dropAttr<InternalLinkageAttr>();
3629   }
3630 
3631   // Merge the types.
3632   VarDecl *MostRecent = Old->getMostRecentDecl();
3633   if (MostRecent != Old) {
3634     MergeVarDeclTypes(New, MostRecent,
3635                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3636     if (New->isInvalidDecl())
3637       return;
3638   }
3639 
3640   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3641   if (New->isInvalidDecl())
3642     return;
3643 
3644   diag::kind PrevDiag;
3645   SourceLocation OldLocation;
3646   std::tie(PrevDiag, OldLocation) =
3647       getNoteDiagForInvalidRedeclaration(Old, New);
3648 
3649   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3650   if (New->getStorageClass() == SC_Static &&
3651       !New->isStaticDataMember() &&
3652       Old->hasExternalFormalLinkage()) {
3653     if (getLangOpts().MicrosoftExt) {
3654       Diag(New->getLocation(), diag::ext_static_non_static)
3655           << New->getDeclName();
3656       Diag(OldLocation, PrevDiag);
3657     } else {
3658       Diag(New->getLocation(), diag::err_static_non_static)
3659           << New->getDeclName();
3660       Diag(OldLocation, PrevDiag);
3661       return New->setInvalidDecl();
3662     }
3663   }
3664   // C99 6.2.2p4:
3665   //   For an identifier declared with the storage-class specifier
3666   //   extern in a scope in which a prior declaration of that
3667   //   identifier is visible,23) if the prior declaration specifies
3668   //   internal or external linkage, the linkage of the identifier at
3669   //   the later declaration is the same as the linkage specified at
3670   //   the prior declaration. If no prior declaration is visible, or
3671   //   if the prior declaration specifies no linkage, then the
3672   //   identifier has external linkage.
3673   if (New->hasExternalStorage() && Old->hasLinkage())
3674     /* Okay */;
3675   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3676            !New->isStaticDataMember() &&
3677            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3678     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3679     Diag(OldLocation, PrevDiag);
3680     return New->setInvalidDecl();
3681   }
3682 
3683   // Check if extern is followed by non-extern and vice-versa.
3684   if (New->hasExternalStorage() &&
3685       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3686     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3687     Diag(OldLocation, PrevDiag);
3688     return New->setInvalidDecl();
3689   }
3690   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3691       !New->hasExternalStorage()) {
3692     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3693     Diag(OldLocation, PrevDiag);
3694     return New->setInvalidDecl();
3695   }
3696 
3697   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3698 
3699   // FIXME: The test for external storage here seems wrong? We still
3700   // need to check for mismatches.
3701   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3702       // Don't complain about out-of-line definitions of static members.
3703       !(Old->getLexicalDeclContext()->isRecord() &&
3704         !New->getLexicalDeclContext()->isRecord())) {
3705     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3706     Diag(OldLocation, PrevDiag);
3707     return New->setInvalidDecl();
3708   }
3709 
3710   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3711     if (VarDecl *Def = Old->getDefinition()) {
3712       // C++1z [dcl.fcn.spec]p4:
3713       //   If the definition of a variable appears in a translation unit before
3714       //   its first declaration as inline, the program is ill-formed.
3715       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3716       Diag(Def->getLocation(), diag::note_previous_definition);
3717     }
3718   }
3719 
3720   // If this redeclaration makes the function inline, we may need to add it to
3721   // UndefinedButUsed.
3722   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3723       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3724     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3725                                            SourceLocation()));
3726 
3727   if (New->getTLSKind() != Old->getTLSKind()) {
3728     if (!Old->getTLSKind()) {
3729       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3730       Diag(OldLocation, PrevDiag);
3731     } else if (!New->getTLSKind()) {
3732       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3733       Diag(OldLocation, PrevDiag);
3734     } else {
3735       // Do not allow redeclaration to change the variable between requiring
3736       // static and dynamic initialization.
3737       // FIXME: GCC allows this, but uses the TLS keyword on the first
3738       // declaration to determine the kind. Do we need to be compatible here?
3739       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3740         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3741       Diag(OldLocation, PrevDiag);
3742     }
3743   }
3744 
3745   // C++ doesn't have tentative definitions, so go right ahead and check here.
3746   if (getLangOpts().CPlusPlus &&
3747       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3748     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3749         Old->getCanonicalDecl()->isConstexpr()) {
3750       // This definition won't be a definition any more once it's been merged.
3751       Diag(New->getLocation(),
3752            diag::warn_deprecated_redundant_constexpr_static_def);
3753     } else if (VarDecl *Def = Old->getDefinition()) {
3754       if (checkVarDeclRedefinition(Def, New))
3755         return;
3756     }
3757   }
3758 
3759   if (haveIncompatibleLanguageLinkages(Old, New)) {
3760     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3761     Diag(OldLocation, PrevDiag);
3762     New->setInvalidDecl();
3763     return;
3764   }
3765 
3766   // Merge "used" flag.
3767   if (Old->getMostRecentDecl()->isUsed(false))
3768     New->setIsUsed();
3769 
3770   // Keep a chain of previous declarations.
3771   New->setPreviousDecl(Old);
3772   if (NewTemplate)
3773     NewTemplate->setPreviousDecl(OldTemplate);
3774 
3775   // Inherit access appropriately.
3776   New->setAccess(Old->getAccess());
3777   if (NewTemplate)
3778     NewTemplate->setAccess(New->getAccess());
3779 
3780   if (Old->isInline())
3781     New->setImplicitlyInline();
3782 }
3783 
3784 /// We've just determined that \p Old and \p New both appear to be definitions
3785 /// of the same variable. Either diagnose or fix the problem.
3786 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3787   if (!hasVisibleDefinition(Old) &&
3788       (New->getFormalLinkage() == InternalLinkage ||
3789        New->isInline() ||
3790        New->getDescribedVarTemplate() ||
3791        New->getNumTemplateParameterLists() ||
3792        New->getDeclContext()->isDependentContext())) {
3793     // The previous definition is hidden, and multiple definitions are
3794     // permitted (in separate TUs). Demote this to a declaration.
3795     New->demoteThisDefinitionToDeclaration();
3796 
3797     // Make the canonical definition visible.
3798     if (auto *OldTD = Old->getDescribedVarTemplate())
3799       makeMergedDefinitionVisible(OldTD, New->getLocation());
3800     makeMergedDefinitionVisible(Old, New->getLocation());
3801     return false;
3802   } else {
3803     Diag(New->getLocation(), diag::err_redefinition) << New;
3804     Diag(Old->getLocation(), diag::note_previous_definition);
3805     New->setInvalidDecl();
3806     return true;
3807   }
3808 }
3809 
3810 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3811 /// no declarator (e.g. "struct foo;") is parsed.
3812 Decl *
3813 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3814                                  RecordDecl *&AnonRecord) {
3815   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3816                                     AnonRecord);
3817 }
3818 
3819 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3820 // disambiguate entities defined in different scopes.
3821 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3822 // compatibility.
3823 // We will pick our mangling number depending on which version of MSVC is being
3824 // targeted.
3825 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3826   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3827              ? S->getMSCurManglingNumber()
3828              : S->getMSLastManglingNumber();
3829 }
3830 
3831 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3832   if (!Context.getLangOpts().CPlusPlus)
3833     return;
3834 
3835   if (isa<CXXRecordDecl>(Tag->getParent())) {
3836     // If this tag is the direct child of a class, number it if
3837     // it is anonymous.
3838     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3839       return;
3840     MangleNumberingContext &MCtx =
3841         Context.getManglingNumberContext(Tag->getParent());
3842     Context.setManglingNumber(
3843         Tag, MCtx.getManglingNumber(
3844                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3845     return;
3846   }
3847 
3848   // If this tag isn't a direct child of a class, number it if it is local.
3849   Decl *ManglingContextDecl;
3850   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3851           Tag->getDeclContext(), ManglingContextDecl)) {
3852     Context.setManglingNumber(
3853         Tag, MCtx->getManglingNumber(
3854                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3855   }
3856 }
3857 
3858 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3859                                         TypedefNameDecl *NewTD) {
3860   if (TagFromDeclSpec->isInvalidDecl())
3861     return;
3862 
3863   // Do nothing if the tag already has a name for linkage purposes.
3864   if (TagFromDeclSpec->hasNameForLinkage())
3865     return;
3866 
3867   // A well-formed anonymous tag must always be a TUK_Definition.
3868   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3869 
3870   // The type must match the tag exactly;  no qualifiers allowed.
3871   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3872                            Context.getTagDeclType(TagFromDeclSpec))) {
3873     if (getLangOpts().CPlusPlus)
3874       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3875     return;
3876   }
3877 
3878   // If we've already computed linkage for the anonymous tag, then
3879   // adding a typedef name for the anonymous decl can change that
3880   // linkage, which might be a serious problem.  Diagnose this as
3881   // unsupported and ignore the typedef name.  TODO: we should
3882   // pursue this as a language defect and establish a formal rule
3883   // for how to handle it.
3884   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3885     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3886 
3887     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3888     tagLoc = getLocForEndOfToken(tagLoc);
3889 
3890     llvm::SmallString<40> textToInsert;
3891     textToInsert += ' ';
3892     textToInsert += NewTD->getIdentifier()->getName();
3893     Diag(tagLoc, diag::note_typedef_changes_linkage)
3894         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3895     return;
3896   }
3897 
3898   // Otherwise, set this is the anon-decl typedef for the tag.
3899   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3900 }
3901 
3902 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3903   switch (T) {
3904   case DeclSpec::TST_class:
3905     return 0;
3906   case DeclSpec::TST_struct:
3907     return 1;
3908   case DeclSpec::TST_interface:
3909     return 2;
3910   case DeclSpec::TST_union:
3911     return 3;
3912   case DeclSpec::TST_enum:
3913     return 4;
3914   default:
3915     llvm_unreachable("unexpected type specifier");
3916   }
3917 }
3918 
3919 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3920 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3921 /// parameters to cope with template friend declarations.
3922 Decl *
3923 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3924                                  MultiTemplateParamsArg TemplateParams,
3925                                  bool IsExplicitInstantiation,
3926                                  RecordDecl *&AnonRecord) {
3927   Decl *TagD = nullptr;
3928   TagDecl *Tag = nullptr;
3929   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3930       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3931       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3932       DS.getTypeSpecType() == DeclSpec::TST_union ||
3933       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3934     TagD = DS.getRepAsDecl();
3935 
3936     if (!TagD) // We probably had an error
3937       return nullptr;
3938 
3939     // Note that the above type specs guarantee that the
3940     // type rep is a Decl, whereas in many of the others
3941     // it's a Type.
3942     if (isa<TagDecl>(TagD))
3943       Tag = cast<TagDecl>(TagD);
3944     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3945       Tag = CTD->getTemplatedDecl();
3946   }
3947 
3948   if (Tag) {
3949     handleTagNumbering(Tag, S);
3950     Tag->setFreeStanding();
3951     if (Tag->isInvalidDecl())
3952       return Tag;
3953   }
3954 
3955   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3956     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3957     // or incomplete types shall not be restrict-qualified."
3958     if (TypeQuals & DeclSpec::TQ_restrict)
3959       Diag(DS.getRestrictSpecLoc(),
3960            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3961            << DS.getSourceRange();
3962   }
3963 
3964   if (DS.isInlineSpecified())
3965     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3966         << getLangOpts().CPlusPlus1z;
3967 
3968   if (DS.isConstexprSpecified()) {
3969     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3970     // and definitions of functions and variables.
3971     if (Tag)
3972       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3973           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3974     else
3975       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3976     // Don't emit warnings after this error.
3977     return TagD;
3978   }
3979 
3980   if (DS.isConceptSpecified()) {
3981     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3982     // either a function concept and its definition or a variable concept and
3983     // its initializer.
3984     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3985     return TagD;
3986   }
3987 
3988   DiagnoseFunctionSpecifiers(DS);
3989 
3990   if (DS.isFriendSpecified()) {
3991     // If we're dealing with a decl but not a TagDecl, assume that
3992     // whatever routines created it handled the friendship aspect.
3993     if (TagD && !Tag)
3994       return nullptr;
3995     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3996   }
3997 
3998   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3999   bool IsExplicitSpecialization =
4000     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4001   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4002       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4003       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4004     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4005     // nested-name-specifier unless it is an explicit instantiation
4006     // or an explicit specialization.
4007     //
4008     // FIXME: We allow class template partial specializations here too, per the
4009     // obvious intent of DR1819.
4010     //
4011     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4012     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4013         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4014     return nullptr;
4015   }
4016 
4017   // Track whether this decl-specifier declares anything.
4018   bool DeclaresAnything = true;
4019 
4020   // Handle anonymous struct definitions.
4021   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4022     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4023         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4024       if (getLangOpts().CPlusPlus ||
4025           Record->getDeclContext()->isRecord()) {
4026         // If CurContext is a DeclContext that can contain statements,
4027         // RecursiveASTVisitor won't visit the decls that
4028         // BuildAnonymousStructOrUnion() will put into CurContext.
4029         // Also store them here so that they can be part of the
4030         // DeclStmt that gets created in this case.
4031         // FIXME: Also return the IndirectFieldDecls created by
4032         // BuildAnonymousStructOr union, for the same reason?
4033         if (CurContext->isFunctionOrMethod())
4034           AnonRecord = Record;
4035         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4036                                            Context.getPrintingPolicy());
4037       }
4038 
4039       DeclaresAnything = false;
4040     }
4041   }
4042 
4043   // C11 6.7.2.1p2:
4044   //   A struct-declaration that does not declare an anonymous structure or
4045   //   anonymous union shall contain a struct-declarator-list.
4046   //
4047   // This rule also existed in C89 and C99; the grammar for struct-declaration
4048   // did not permit a struct-declaration without a struct-declarator-list.
4049   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4050       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4051     // Check for Microsoft C extension: anonymous struct/union member.
4052     // Handle 2 kinds of anonymous struct/union:
4053     //   struct STRUCT;
4054     //   union UNION;
4055     // and
4056     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4057     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4058     if ((Tag && Tag->getDeclName()) ||
4059         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4060       RecordDecl *Record = nullptr;
4061       if (Tag)
4062         Record = dyn_cast<RecordDecl>(Tag);
4063       else if (const RecordType *RT =
4064                    DS.getRepAsType().get()->getAsStructureType())
4065         Record = RT->getDecl();
4066       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4067         Record = UT->getDecl();
4068 
4069       if (Record && getLangOpts().MicrosoftExt) {
4070         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4071           << Record->isUnion() << DS.getSourceRange();
4072         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4073       }
4074 
4075       DeclaresAnything = false;
4076     }
4077   }
4078 
4079   // Skip all the checks below if we have a type error.
4080   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4081       (TagD && TagD->isInvalidDecl()))
4082     return TagD;
4083 
4084   if (getLangOpts().CPlusPlus &&
4085       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4086     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4087       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4088           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4089         DeclaresAnything = false;
4090 
4091   if (!DS.isMissingDeclaratorOk()) {
4092     // Customize diagnostic for a typedef missing a name.
4093     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4094       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4095         << DS.getSourceRange();
4096     else
4097       DeclaresAnything = false;
4098   }
4099 
4100   if (DS.isModulePrivateSpecified() &&
4101       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4102     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4103       << Tag->getTagKind()
4104       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4105 
4106   ActOnDocumentableDecl(TagD);
4107 
4108   // C 6.7/2:
4109   //   A declaration [...] shall declare at least a declarator [...], a tag,
4110   //   or the members of an enumeration.
4111   // C++ [dcl.dcl]p3:
4112   //   [If there are no declarators], and except for the declaration of an
4113   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4114   //   names into the program, or shall redeclare a name introduced by a
4115   //   previous declaration.
4116   if (!DeclaresAnything) {
4117     // In C, we allow this as a (popular) extension / bug. Don't bother
4118     // producing further diagnostics for redundant qualifiers after this.
4119     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4120     return TagD;
4121   }
4122 
4123   // C++ [dcl.stc]p1:
4124   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4125   //   init-declarator-list of the declaration shall not be empty.
4126   // C++ [dcl.fct.spec]p1:
4127   //   If a cv-qualifier appears in a decl-specifier-seq, the
4128   //   init-declarator-list of the declaration shall not be empty.
4129   //
4130   // Spurious qualifiers here appear to be valid in C.
4131   unsigned DiagID = diag::warn_standalone_specifier;
4132   if (getLangOpts().CPlusPlus)
4133     DiagID = diag::ext_standalone_specifier;
4134 
4135   // Note that a linkage-specification sets a storage class, but
4136   // 'extern "C" struct foo;' is actually valid and not theoretically
4137   // useless.
4138   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4139     if (SCS == DeclSpec::SCS_mutable)
4140       // Since mutable is not a viable storage class specifier in C, there is
4141       // no reason to treat it as an extension. Instead, diagnose as an error.
4142       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4143     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4144       Diag(DS.getStorageClassSpecLoc(), DiagID)
4145         << DeclSpec::getSpecifierName(SCS);
4146   }
4147 
4148   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4149     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4150       << DeclSpec::getSpecifierName(TSCS);
4151   if (DS.getTypeQualifiers()) {
4152     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4153       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4154     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4155       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4156     // Restrict is covered above.
4157     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4158       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4159     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4160       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4161   }
4162 
4163   // Warn about ignored type attributes, for example:
4164   // __attribute__((aligned)) struct A;
4165   // Attributes should be placed after tag to apply to type declaration.
4166   if (!DS.getAttributes().empty()) {
4167     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4168     if (TypeSpecType == DeclSpec::TST_class ||
4169         TypeSpecType == DeclSpec::TST_struct ||
4170         TypeSpecType == DeclSpec::TST_interface ||
4171         TypeSpecType == DeclSpec::TST_union ||
4172         TypeSpecType == DeclSpec::TST_enum) {
4173       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4174            attrs = attrs->getNext())
4175         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4176             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4177     }
4178   }
4179 
4180   return TagD;
4181 }
4182 
4183 /// We are trying to inject an anonymous member into the given scope;
4184 /// check if there's an existing declaration that can't be overloaded.
4185 ///
4186 /// \return true if this is a forbidden redeclaration
4187 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4188                                          Scope *S,
4189                                          DeclContext *Owner,
4190                                          DeclarationName Name,
4191                                          SourceLocation NameLoc,
4192                                          bool IsUnion) {
4193   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4194                  Sema::ForRedeclaration);
4195   if (!SemaRef.LookupName(R, S)) return false;
4196 
4197   // Pick a representative declaration.
4198   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4199   assert(PrevDecl && "Expected a non-null Decl");
4200 
4201   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4202     return false;
4203 
4204   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4205     << IsUnion << Name;
4206   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4207 
4208   return true;
4209 }
4210 
4211 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4212 /// anonymous struct or union AnonRecord into the owning context Owner
4213 /// and scope S. This routine will be invoked just after we realize
4214 /// that an unnamed union or struct is actually an anonymous union or
4215 /// struct, e.g.,
4216 ///
4217 /// @code
4218 /// union {
4219 ///   int i;
4220 ///   float f;
4221 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4222 ///    // f into the surrounding scope.x
4223 /// @endcode
4224 ///
4225 /// This routine is recursive, injecting the names of nested anonymous
4226 /// structs/unions into the owning context and scope as well.
4227 static bool
4228 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4229                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4230                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4231   bool Invalid = false;
4232 
4233   // Look every FieldDecl and IndirectFieldDecl with a name.
4234   for (auto *D : AnonRecord->decls()) {
4235     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4236         cast<NamedDecl>(D)->getDeclName()) {
4237       ValueDecl *VD = cast<ValueDecl>(D);
4238       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4239                                        VD->getLocation(),
4240                                        AnonRecord->isUnion())) {
4241         // C++ [class.union]p2:
4242         //   The names of the members of an anonymous union shall be
4243         //   distinct from the names of any other entity in the
4244         //   scope in which the anonymous union is declared.
4245         Invalid = true;
4246       } else {
4247         // C++ [class.union]p2:
4248         //   For the purpose of name lookup, after the anonymous union
4249         //   definition, the members of the anonymous union are
4250         //   considered to have been defined in the scope in which the
4251         //   anonymous union is declared.
4252         unsigned OldChainingSize = Chaining.size();
4253         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4254           Chaining.append(IF->chain_begin(), IF->chain_end());
4255         else
4256           Chaining.push_back(VD);
4257 
4258         assert(Chaining.size() >= 2);
4259         NamedDecl **NamedChain =
4260           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4261         for (unsigned i = 0; i < Chaining.size(); i++)
4262           NamedChain[i] = Chaining[i];
4263 
4264         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4265             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4266             VD->getType(), {NamedChain, Chaining.size()});
4267 
4268         for (const auto *Attr : VD->attrs())
4269           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4270 
4271         IndirectField->setAccess(AS);
4272         IndirectField->setImplicit();
4273         SemaRef.PushOnScopeChains(IndirectField, S);
4274 
4275         // That includes picking up the appropriate access specifier.
4276         if (AS != AS_none) IndirectField->setAccess(AS);
4277 
4278         Chaining.resize(OldChainingSize);
4279       }
4280     }
4281   }
4282 
4283   return Invalid;
4284 }
4285 
4286 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4287 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4288 /// illegal input values are mapped to SC_None.
4289 static StorageClass
4290 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4291   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4292   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4293          "Parser allowed 'typedef' as storage class VarDecl.");
4294   switch (StorageClassSpec) {
4295   case DeclSpec::SCS_unspecified:    return SC_None;
4296   case DeclSpec::SCS_extern:
4297     if (DS.isExternInLinkageSpec())
4298       return SC_None;
4299     return SC_Extern;
4300   case DeclSpec::SCS_static:         return SC_Static;
4301   case DeclSpec::SCS_auto:           return SC_Auto;
4302   case DeclSpec::SCS_register:       return SC_Register;
4303   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4304     // Illegal SCSs map to None: error reporting is up to the caller.
4305   case DeclSpec::SCS_mutable:        // Fall through.
4306   case DeclSpec::SCS_typedef:        return SC_None;
4307   }
4308   llvm_unreachable("unknown storage class specifier");
4309 }
4310 
4311 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4312   assert(Record->hasInClassInitializer());
4313 
4314   for (const auto *I : Record->decls()) {
4315     const auto *FD = dyn_cast<FieldDecl>(I);
4316     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4317       FD = IFD->getAnonField();
4318     if (FD && FD->hasInClassInitializer())
4319       return FD->getLocation();
4320   }
4321 
4322   llvm_unreachable("couldn't find in-class initializer");
4323 }
4324 
4325 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4326                                       SourceLocation DefaultInitLoc) {
4327   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4328     return;
4329 
4330   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4331   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4332 }
4333 
4334 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4335                                       CXXRecordDecl *AnonUnion) {
4336   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4337     return;
4338 
4339   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4340 }
4341 
4342 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4343 /// anonymous structure or union. Anonymous unions are a C++ feature
4344 /// (C++ [class.union]) and a C11 feature; anonymous structures
4345 /// are a C11 feature and GNU C++ extension.
4346 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4347                                         AccessSpecifier AS,
4348                                         RecordDecl *Record,
4349                                         const PrintingPolicy &Policy) {
4350   DeclContext *Owner = Record->getDeclContext();
4351 
4352   // Diagnose whether this anonymous struct/union is an extension.
4353   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4354     Diag(Record->getLocation(), diag::ext_anonymous_union);
4355   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4356     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4357   else if (!Record->isUnion() && !getLangOpts().C11)
4358     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4359 
4360   // C and C++ require different kinds of checks for anonymous
4361   // structs/unions.
4362   bool Invalid = false;
4363   if (getLangOpts().CPlusPlus) {
4364     const char *PrevSpec = nullptr;
4365     unsigned DiagID;
4366     if (Record->isUnion()) {
4367       // C++ [class.union]p6:
4368       //   Anonymous unions declared in a named namespace or in the
4369       //   global namespace shall be declared static.
4370       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4371           (isa<TranslationUnitDecl>(Owner) ||
4372            (isa<NamespaceDecl>(Owner) &&
4373             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4374         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4375           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4376 
4377         // Recover by adding 'static'.
4378         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4379                                PrevSpec, DiagID, Policy);
4380       }
4381       // C++ [class.union]p6:
4382       //   A storage class is not allowed in a declaration of an
4383       //   anonymous union in a class scope.
4384       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4385                isa<RecordDecl>(Owner)) {
4386         Diag(DS.getStorageClassSpecLoc(),
4387              diag::err_anonymous_union_with_storage_spec)
4388           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4389 
4390         // Recover by removing the storage specifier.
4391         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4392                                SourceLocation(),
4393                                PrevSpec, DiagID, Context.getPrintingPolicy());
4394       }
4395     }
4396 
4397     // Ignore const/volatile/restrict qualifiers.
4398     if (DS.getTypeQualifiers()) {
4399       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4400         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4401           << Record->isUnion() << "const"
4402           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4403       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4404         Diag(DS.getVolatileSpecLoc(),
4405              diag::ext_anonymous_struct_union_qualified)
4406           << Record->isUnion() << "volatile"
4407           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4408       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4409         Diag(DS.getRestrictSpecLoc(),
4410              diag::ext_anonymous_struct_union_qualified)
4411           << Record->isUnion() << "restrict"
4412           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4413       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4414         Diag(DS.getAtomicSpecLoc(),
4415              diag::ext_anonymous_struct_union_qualified)
4416           << Record->isUnion() << "_Atomic"
4417           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4418       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4419         Diag(DS.getUnalignedSpecLoc(),
4420              diag::ext_anonymous_struct_union_qualified)
4421           << Record->isUnion() << "__unaligned"
4422           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4423 
4424       DS.ClearTypeQualifiers();
4425     }
4426 
4427     // C++ [class.union]p2:
4428     //   The member-specification of an anonymous union shall only
4429     //   define non-static data members. [Note: nested types and
4430     //   functions cannot be declared within an anonymous union. ]
4431     for (auto *Mem : Record->decls()) {
4432       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4433         // C++ [class.union]p3:
4434         //   An anonymous union shall not have private or protected
4435         //   members (clause 11).
4436         assert(FD->getAccess() != AS_none);
4437         if (FD->getAccess() != AS_public) {
4438           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4439             << Record->isUnion() << (FD->getAccess() == AS_protected);
4440           Invalid = true;
4441         }
4442 
4443         // C++ [class.union]p1
4444         //   An object of a class with a non-trivial constructor, a non-trivial
4445         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4446         //   assignment operator cannot be a member of a union, nor can an
4447         //   array of such objects.
4448         if (CheckNontrivialField(FD))
4449           Invalid = true;
4450       } else if (Mem->isImplicit()) {
4451         // Any implicit members are fine.
4452       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4453         // This is a type that showed up in an
4454         // elaborated-type-specifier inside the anonymous struct or
4455         // union, but which actually declares a type outside of the
4456         // anonymous struct or union. It's okay.
4457       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4458         if (!MemRecord->isAnonymousStructOrUnion() &&
4459             MemRecord->getDeclName()) {
4460           // Visual C++ allows type definition in anonymous struct or union.
4461           if (getLangOpts().MicrosoftExt)
4462             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4463               << Record->isUnion();
4464           else {
4465             // This is a nested type declaration.
4466             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4467               << Record->isUnion();
4468             Invalid = true;
4469           }
4470         } else {
4471           // This is an anonymous type definition within another anonymous type.
4472           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4473           // not part of standard C++.
4474           Diag(MemRecord->getLocation(),
4475                diag::ext_anonymous_record_with_anonymous_type)
4476             << Record->isUnion();
4477         }
4478       } else if (isa<AccessSpecDecl>(Mem)) {
4479         // Any access specifier is fine.
4480       } else if (isa<StaticAssertDecl>(Mem)) {
4481         // In C++1z, static_assert declarations are also fine.
4482       } else {
4483         // We have something that isn't a non-static data
4484         // member. Complain about it.
4485         unsigned DK = diag::err_anonymous_record_bad_member;
4486         if (isa<TypeDecl>(Mem))
4487           DK = diag::err_anonymous_record_with_type;
4488         else if (isa<FunctionDecl>(Mem))
4489           DK = diag::err_anonymous_record_with_function;
4490         else if (isa<VarDecl>(Mem))
4491           DK = diag::err_anonymous_record_with_static;
4492 
4493         // Visual C++ allows type definition in anonymous struct or union.
4494         if (getLangOpts().MicrosoftExt &&
4495             DK == diag::err_anonymous_record_with_type)
4496           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4497             << Record->isUnion();
4498         else {
4499           Diag(Mem->getLocation(), DK) << Record->isUnion();
4500           Invalid = true;
4501         }
4502       }
4503     }
4504 
4505     // C++11 [class.union]p8 (DR1460):
4506     //   At most one variant member of a union may have a
4507     //   brace-or-equal-initializer.
4508     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4509         Owner->isRecord())
4510       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4511                                 cast<CXXRecordDecl>(Record));
4512   }
4513 
4514   if (!Record->isUnion() && !Owner->isRecord()) {
4515     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4516       << getLangOpts().CPlusPlus;
4517     Invalid = true;
4518   }
4519 
4520   // Mock up a declarator.
4521   Declarator Dc(DS, Declarator::MemberContext);
4522   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4523   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4524 
4525   // Create a declaration for this anonymous struct/union.
4526   NamedDecl *Anon = nullptr;
4527   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4528     Anon = FieldDecl::Create(Context, OwningClass,
4529                              DS.getLocStart(),
4530                              Record->getLocation(),
4531                              /*IdentifierInfo=*/nullptr,
4532                              Context.getTypeDeclType(Record),
4533                              TInfo,
4534                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4535                              /*InitStyle=*/ICIS_NoInit);
4536     Anon->setAccess(AS);
4537     if (getLangOpts().CPlusPlus)
4538       FieldCollector->Add(cast<FieldDecl>(Anon));
4539   } else {
4540     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4541     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4542     if (SCSpec == DeclSpec::SCS_mutable) {
4543       // mutable can only appear on non-static class members, so it's always
4544       // an error here
4545       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4546       Invalid = true;
4547       SC = SC_None;
4548     }
4549 
4550     Anon = VarDecl::Create(Context, Owner,
4551                            DS.getLocStart(),
4552                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4553                            Context.getTypeDeclType(Record),
4554                            TInfo, SC);
4555 
4556     // Default-initialize the implicit variable. This initialization will be
4557     // trivial in almost all cases, except if a union member has an in-class
4558     // initializer:
4559     //   union { int n = 0; };
4560     ActOnUninitializedDecl(Anon);
4561   }
4562   Anon->setImplicit();
4563 
4564   // Mark this as an anonymous struct/union type.
4565   Record->setAnonymousStructOrUnion(true);
4566 
4567   // Add the anonymous struct/union object to the current
4568   // context. We'll be referencing this object when we refer to one of
4569   // its members.
4570   Owner->addDecl(Anon);
4571 
4572   // Inject the members of the anonymous struct/union into the owning
4573   // context and into the identifier resolver chain for name lookup
4574   // purposes.
4575   SmallVector<NamedDecl*, 2> Chain;
4576   Chain.push_back(Anon);
4577 
4578   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4579     Invalid = true;
4580 
4581   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4582     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4583       Decl *ManglingContextDecl;
4584       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4585               NewVD->getDeclContext(), ManglingContextDecl)) {
4586         Context.setManglingNumber(
4587             NewVD, MCtx->getManglingNumber(
4588                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4589         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4590       }
4591     }
4592   }
4593 
4594   if (Invalid)
4595     Anon->setInvalidDecl();
4596 
4597   return Anon;
4598 }
4599 
4600 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4601 /// Microsoft C anonymous structure.
4602 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4603 /// Example:
4604 ///
4605 /// struct A { int a; };
4606 /// struct B { struct A; int b; };
4607 ///
4608 /// void foo() {
4609 ///   B var;
4610 ///   var.a = 3;
4611 /// }
4612 ///
4613 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4614                                            RecordDecl *Record) {
4615   assert(Record && "expected a record!");
4616 
4617   // Mock up a declarator.
4618   Declarator Dc(DS, Declarator::TypeNameContext);
4619   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4620   assert(TInfo && "couldn't build declarator info for anonymous struct");
4621 
4622   auto *ParentDecl = cast<RecordDecl>(CurContext);
4623   QualType RecTy = Context.getTypeDeclType(Record);
4624 
4625   // Create a declaration for this anonymous struct.
4626   NamedDecl *Anon = FieldDecl::Create(Context,
4627                              ParentDecl,
4628                              DS.getLocStart(),
4629                              DS.getLocStart(),
4630                              /*IdentifierInfo=*/nullptr,
4631                              RecTy,
4632                              TInfo,
4633                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4634                              /*InitStyle=*/ICIS_NoInit);
4635   Anon->setImplicit();
4636 
4637   // Add the anonymous struct object to the current context.
4638   CurContext->addDecl(Anon);
4639 
4640   // Inject the members of the anonymous struct into the current
4641   // context and into the identifier resolver chain for name lookup
4642   // purposes.
4643   SmallVector<NamedDecl*, 2> Chain;
4644   Chain.push_back(Anon);
4645 
4646   RecordDecl *RecordDef = Record->getDefinition();
4647   if (RequireCompleteType(Anon->getLocation(), RecTy,
4648                           diag::err_field_incomplete) ||
4649       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4650                                           AS_none, Chain)) {
4651     Anon->setInvalidDecl();
4652     ParentDecl->setInvalidDecl();
4653   }
4654 
4655   return Anon;
4656 }
4657 
4658 /// GetNameForDeclarator - Determine the full declaration name for the
4659 /// given Declarator.
4660 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4661   return GetNameFromUnqualifiedId(D.getName());
4662 }
4663 
4664 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4665 DeclarationNameInfo
4666 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4667   DeclarationNameInfo NameInfo;
4668   NameInfo.setLoc(Name.StartLocation);
4669 
4670   switch (Name.getKind()) {
4671 
4672   case UnqualifiedId::IK_ImplicitSelfParam:
4673   case UnqualifiedId::IK_Identifier:
4674     NameInfo.setName(Name.Identifier);
4675     NameInfo.setLoc(Name.StartLocation);
4676     return NameInfo;
4677 
4678   case UnqualifiedId::IK_DeductionGuideName: {
4679     // C++ [temp.deduct.guide]p3:
4680     //   The simple-template-id shall name a class template specialization.
4681     //   The template-name shall be the same identifier as the template-name
4682     //   of the simple-template-id.
4683     // These together intend to imply that the template-name shall name a
4684     // class template.
4685     // FIXME: template<typename T> struct X {};
4686     //        template<typename T> using Y = X<T>;
4687     //        Y(int) -> Y<int>;
4688     //   satisfies these rules but does not name a class template.
4689     TemplateName TN = Name.TemplateName.get().get();
4690     auto *Template = TN.getAsTemplateDecl();
4691     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4692       Diag(Name.StartLocation,
4693            diag::err_deduction_guide_name_not_class_template)
4694         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4695       if (Template)
4696         Diag(Template->getLocation(), diag::note_template_decl_here);
4697       return DeclarationNameInfo();
4698     }
4699 
4700     NameInfo.setName(
4701         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4702     NameInfo.setLoc(Name.StartLocation);
4703     return NameInfo;
4704   }
4705 
4706   case UnqualifiedId::IK_OperatorFunctionId:
4707     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4708                                            Name.OperatorFunctionId.Operator));
4709     NameInfo.setLoc(Name.StartLocation);
4710     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4711       = Name.OperatorFunctionId.SymbolLocations[0];
4712     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4713       = Name.EndLocation.getRawEncoding();
4714     return NameInfo;
4715 
4716   case UnqualifiedId::IK_LiteralOperatorId:
4717     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4718                                                            Name.Identifier));
4719     NameInfo.setLoc(Name.StartLocation);
4720     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4721     return NameInfo;
4722 
4723   case UnqualifiedId::IK_ConversionFunctionId: {
4724     TypeSourceInfo *TInfo;
4725     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4726     if (Ty.isNull())
4727       return DeclarationNameInfo();
4728     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4729                                                Context.getCanonicalType(Ty)));
4730     NameInfo.setLoc(Name.StartLocation);
4731     NameInfo.setNamedTypeInfo(TInfo);
4732     return NameInfo;
4733   }
4734 
4735   case UnqualifiedId::IK_ConstructorName: {
4736     TypeSourceInfo *TInfo;
4737     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4738     if (Ty.isNull())
4739       return DeclarationNameInfo();
4740     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4741                                               Context.getCanonicalType(Ty)));
4742     NameInfo.setLoc(Name.StartLocation);
4743     NameInfo.setNamedTypeInfo(TInfo);
4744     return NameInfo;
4745   }
4746 
4747   case UnqualifiedId::IK_ConstructorTemplateId: {
4748     // In well-formed code, we can only have a constructor
4749     // template-id that refers to the current context, so go there
4750     // to find the actual type being constructed.
4751     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4752     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4753       return DeclarationNameInfo();
4754 
4755     // Determine the type of the class being constructed.
4756     QualType CurClassType = Context.getTypeDeclType(CurClass);
4757 
4758     // FIXME: Check two things: that the template-id names the same type as
4759     // CurClassType, and that the template-id does not occur when the name
4760     // was qualified.
4761 
4762     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4763                                     Context.getCanonicalType(CurClassType)));
4764     NameInfo.setLoc(Name.StartLocation);
4765     // FIXME: should we retrieve TypeSourceInfo?
4766     NameInfo.setNamedTypeInfo(nullptr);
4767     return NameInfo;
4768   }
4769 
4770   case UnqualifiedId::IK_DestructorName: {
4771     TypeSourceInfo *TInfo;
4772     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4773     if (Ty.isNull())
4774       return DeclarationNameInfo();
4775     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4776                                               Context.getCanonicalType(Ty)));
4777     NameInfo.setLoc(Name.StartLocation);
4778     NameInfo.setNamedTypeInfo(TInfo);
4779     return NameInfo;
4780   }
4781 
4782   case UnqualifiedId::IK_TemplateId: {
4783     TemplateName TName = Name.TemplateId->Template.get();
4784     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4785     return Context.getNameForTemplate(TName, TNameLoc);
4786   }
4787 
4788   } // switch (Name.getKind())
4789 
4790   llvm_unreachable("Unknown name kind");
4791 }
4792 
4793 static QualType getCoreType(QualType Ty) {
4794   do {
4795     if (Ty->isPointerType() || Ty->isReferenceType())
4796       Ty = Ty->getPointeeType();
4797     else if (Ty->isArrayType())
4798       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4799     else
4800       return Ty.withoutLocalFastQualifiers();
4801   } while (true);
4802 }
4803 
4804 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4805 /// and Definition have "nearly" matching parameters. This heuristic is
4806 /// used to improve diagnostics in the case where an out-of-line function
4807 /// definition doesn't match any declaration within the class or namespace.
4808 /// Also sets Params to the list of indices to the parameters that differ
4809 /// between the declaration and the definition. If hasSimilarParameters
4810 /// returns true and Params is empty, then all of the parameters match.
4811 static bool hasSimilarParameters(ASTContext &Context,
4812                                      FunctionDecl *Declaration,
4813                                      FunctionDecl *Definition,
4814                                      SmallVectorImpl<unsigned> &Params) {
4815   Params.clear();
4816   if (Declaration->param_size() != Definition->param_size())
4817     return false;
4818   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4819     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4820     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4821 
4822     // The parameter types are identical
4823     if (Context.hasSameType(DefParamTy, DeclParamTy))
4824       continue;
4825 
4826     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4827     QualType DefParamBaseTy = getCoreType(DefParamTy);
4828     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4829     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4830 
4831     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4832         (DeclTyName && DeclTyName == DefTyName))
4833       Params.push_back(Idx);
4834     else  // The two parameters aren't even close
4835       return false;
4836   }
4837 
4838   return true;
4839 }
4840 
4841 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4842 /// declarator needs to be rebuilt in the current instantiation.
4843 /// Any bits of declarator which appear before the name are valid for
4844 /// consideration here.  That's specifically the type in the decl spec
4845 /// and the base type in any member-pointer chunks.
4846 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4847                                                     DeclarationName Name) {
4848   // The types we specifically need to rebuild are:
4849   //   - typenames, typeofs, and decltypes
4850   //   - types which will become injected class names
4851   // Of course, we also need to rebuild any type referencing such a
4852   // type.  It's safest to just say "dependent", but we call out a
4853   // few cases here.
4854 
4855   DeclSpec &DS = D.getMutableDeclSpec();
4856   switch (DS.getTypeSpecType()) {
4857   case DeclSpec::TST_typename:
4858   case DeclSpec::TST_typeofType:
4859   case DeclSpec::TST_underlyingType:
4860   case DeclSpec::TST_atomic: {
4861     // Grab the type from the parser.
4862     TypeSourceInfo *TSI = nullptr;
4863     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4864     if (T.isNull() || !T->isDependentType()) break;
4865 
4866     // Make sure there's a type source info.  This isn't really much
4867     // of a waste; most dependent types should have type source info
4868     // attached already.
4869     if (!TSI)
4870       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4871 
4872     // Rebuild the type in the current instantiation.
4873     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4874     if (!TSI) return true;
4875 
4876     // Store the new type back in the decl spec.
4877     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4878     DS.UpdateTypeRep(LocType);
4879     break;
4880   }
4881 
4882   case DeclSpec::TST_decltype:
4883   case DeclSpec::TST_typeofExpr: {
4884     Expr *E = DS.getRepAsExpr();
4885     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4886     if (Result.isInvalid()) return true;
4887     DS.UpdateExprRep(Result.get());
4888     break;
4889   }
4890 
4891   default:
4892     // Nothing to do for these decl specs.
4893     break;
4894   }
4895 
4896   // It doesn't matter what order we do this in.
4897   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4898     DeclaratorChunk &Chunk = D.getTypeObject(I);
4899 
4900     // The only type information in the declarator which can come
4901     // before the declaration name is the base type of a member
4902     // pointer.
4903     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4904       continue;
4905 
4906     // Rebuild the scope specifier in-place.
4907     CXXScopeSpec &SS = Chunk.Mem.Scope();
4908     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4909       return true;
4910   }
4911 
4912   return false;
4913 }
4914 
4915 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4916   D.setFunctionDefinitionKind(FDK_Declaration);
4917   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4918 
4919   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4920       Dcl && Dcl->getDeclContext()->isFileContext())
4921     Dcl->setTopLevelDeclInObjCContainer();
4922 
4923   if (getLangOpts().OpenCL)
4924     setCurrentOpenCLExtensionForDecl(Dcl);
4925 
4926   return Dcl;
4927 }
4928 
4929 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4930 ///   If T is the name of a class, then each of the following shall have a
4931 ///   name different from T:
4932 ///     - every static data member of class T;
4933 ///     - every member function of class T
4934 ///     - every member of class T that is itself a type;
4935 /// \returns true if the declaration name violates these rules.
4936 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4937                                    DeclarationNameInfo NameInfo) {
4938   DeclarationName Name = NameInfo.getName();
4939 
4940   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4941   while (Record && Record->isAnonymousStructOrUnion())
4942     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4943   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4944     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4945     return true;
4946   }
4947 
4948   return false;
4949 }
4950 
4951 /// \brief Diagnose a declaration whose declarator-id has the given
4952 /// nested-name-specifier.
4953 ///
4954 /// \param SS The nested-name-specifier of the declarator-id.
4955 ///
4956 /// \param DC The declaration context to which the nested-name-specifier
4957 /// resolves.
4958 ///
4959 /// \param Name The name of the entity being declared.
4960 ///
4961 /// \param Loc The location of the name of the entity being declared.
4962 ///
4963 /// \returns true if we cannot safely recover from this error, false otherwise.
4964 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4965                                         DeclarationName Name,
4966                                         SourceLocation Loc) {
4967   DeclContext *Cur = CurContext;
4968   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4969     Cur = Cur->getParent();
4970 
4971   // If the user provided a superfluous scope specifier that refers back to the
4972   // class in which the entity is already declared, diagnose and ignore it.
4973   //
4974   // class X {
4975   //   void X::f();
4976   // };
4977   //
4978   // Note, it was once ill-formed to give redundant qualification in all
4979   // contexts, but that rule was removed by DR482.
4980   if (Cur->Equals(DC)) {
4981     if (Cur->isRecord()) {
4982       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4983                                       : diag::err_member_extra_qualification)
4984         << Name << FixItHint::CreateRemoval(SS.getRange());
4985       SS.clear();
4986     } else {
4987       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4988     }
4989     return false;
4990   }
4991 
4992   // Check whether the qualifying scope encloses the scope of the original
4993   // declaration.
4994   if (!Cur->Encloses(DC)) {
4995     if (Cur->isRecord())
4996       Diag(Loc, diag::err_member_qualification)
4997         << Name << SS.getRange();
4998     else if (isa<TranslationUnitDecl>(DC))
4999       Diag(Loc, diag::err_invalid_declarator_global_scope)
5000         << Name << SS.getRange();
5001     else if (isa<FunctionDecl>(Cur))
5002       Diag(Loc, diag::err_invalid_declarator_in_function)
5003         << Name << SS.getRange();
5004     else if (isa<BlockDecl>(Cur))
5005       Diag(Loc, diag::err_invalid_declarator_in_block)
5006         << Name << SS.getRange();
5007     else
5008       Diag(Loc, diag::err_invalid_declarator_scope)
5009       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5010 
5011     return true;
5012   }
5013 
5014   if (Cur->isRecord()) {
5015     // Cannot qualify members within a class.
5016     Diag(Loc, diag::err_member_qualification)
5017       << Name << SS.getRange();
5018     SS.clear();
5019 
5020     // C++ constructors and destructors with incorrect scopes can break
5021     // our AST invariants by having the wrong underlying types. If
5022     // that's the case, then drop this declaration entirely.
5023     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5024          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5025         !Context.hasSameType(Name.getCXXNameType(),
5026                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5027       return true;
5028 
5029     return false;
5030   }
5031 
5032   // C++11 [dcl.meaning]p1:
5033   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5034   //   not begin with a decltype-specifer"
5035   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5036   while (SpecLoc.getPrefix())
5037     SpecLoc = SpecLoc.getPrefix();
5038   if (dyn_cast_or_null<DecltypeType>(
5039         SpecLoc.getNestedNameSpecifier()->getAsType()))
5040     Diag(Loc, diag::err_decltype_in_declarator)
5041       << SpecLoc.getTypeLoc().getSourceRange();
5042 
5043   return false;
5044 }
5045 
5046 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5047                                   MultiTemplateParamsArg TemplateParamLists) {
5048   // TODO: consider using NameInfo for diagnostic.
5049   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5050   DeclarationName Name = NameInfo.getName();
5051 
5052   // All of these full declarators require an identifier.  If it doesn't have
5053   // one, the ParsedFreeStandingDeclSpec action should be used.
5054   if (D.isDecompositionDeclarator()) {
5055     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5056   } else if (!Name) {
5057     if (!D.isInvalidType())  // Reject this if we think it is valid.
5058       Diag(D.getDeclSpec().getLocStart(),
5059            diag::err_declarator_need_ident)
5060         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5061     return nullptr;
5062   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5063     return nullptr;
5064 
5065   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5066   // we find one that is.
5067   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5068          (S->getFlags() & Scope::TemplateParamScope) != 0)
5069     S = S->getParent();
5070 
5071   DeclContext *DC = CurContext;
5072   if (D.getCXXScopeSpec().isInvalid())
5073     D.setInvalidType();
5074   else if (D.getCXXScopeSpec().isSet()) {
5075     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5076                                         UPPC_DeclarationQualifier))
5077       return nullptr;
5078 
5079     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5080     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5081     if (!DC || isa<EnumDecl>(DC)) {
5082       // If we could not compute the declaration context, it's because the
5083       // declaration context is dependent but does not refer to a class,
5084       // class template, or class template partial specialization. Complain
5085       // and return early, to avoid the coming semantic disaster.
5086       Diag(D.getIdentifierLoc(),
5087            diag::err_template_qualified_declarator_no_match)
5088         << D.getCXXScopeSpec().getScopeRep()
5089         << D.getCXXScopeSpec().getRange();
5090       return nullptr;
5091     }
5092     bool IsDependentContext = DC->isDependentContext();
5093 
5094     if (!IsDependentContext &&
5095         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5096       return nullptr;
5097 
5098     // If a class is incomplete, do not parse entities inside it.
5099     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5100       Diag(D.getIdentifierLoc(),
5101            diag::err_member_def_undefined_record)
5102         << Name << DC << D.getCXXScopeSpec().getRange();
5103       return nullptr;
5104     }
5105     if (!D.getDeclSpec().isFriendSpecified()) {
5106       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5107                                       Name, D.getIdentifierLoc())) {
5108         if (DC->isRecord())
5109           return nullptr;
5110 
5111         D.setInvalidType();
5112       }
5113     }
5114 
5115     // Check whether we need to rebuild the type of the given
5116     // declaration in the current instantiation.
5117     if (EnteringContext && IsDependentContext &&
5118         TemplateParamLists.size() != 0) {
5119       ContextRAII SavedContext(*this, DC);
5120       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5121         D.setInvalidType();
5122     }
5123   }
5124 
5125   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5126   QualType R = TInfo->getType();
5127 
5128   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5129     // If this is a typedef, we'll end up spewing multiple diagnostics.
5130     // Just return early; it's safer. If this is a function, let the
5131     // "constructor cannot have a return type" diagnostic handle it.
5132     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5133       return nullptr;
5134 
5135   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5136                                       UPPC_DeclarationType))
5137     D.setInvalidType();
5138 
5139   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5140                         ForRedeclaration);
5141 
5142   // See if this is a redefinition of a variable in the same scope.
5143   if (!D.getCXXScopeSpec().isSet()) {
5144     bool IsLinkageLookup = false;
5145     bool CreateBuiltins = false;
5146 
5147     // If the declaration we're planning to build will be a function
5148     // or object with linkage, then look for another declaration with
5149     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5150     //
5151     // If the declaration we're planning to build will be declared with
5152     // external linkage in the translation unit, create any builtin with
5153     // the same name.
5154     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5155       /* Do nothing*/;
5156     else if (CurContext->isFunctionOrMethod() &&
5157              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5158               R->isFunctionType())) {
5159       IsLinkageLookup = true;
5160       CreateBuiltins =
5161           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5162     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5163                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5164       CreateBuiltins = true;
5165 
5166     if (IsLinkageLookup)
5167       Previous.clear(LookupRedeclarationWithLinkage);
5168 
5169     LookupName(Previous, S, CreateBuiltins);
5170   } else { // Something like "int foo::x;"
5171     LookupQualifiedName(Previous, DC);
5172 
5173     // C++ [dcl.meaning]p1:
5174     //   When the declarator-id is qualified, the declaration shall refer to a
5175     //  previously declared member of the class or namespace to which the
5176     //  qualifier refers (or, in the case of a namespace, of an element of the
5177     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5178     //  thereof; [...]
5179     //
5180     // Note that we already checked the context above, and that we do not have
5181     // enough information to make sure that Previous contains the declaration
5182     // we want to match. For example, given:
5183     //
5184     //   class X {
5185     //     void f();
5186     //     void f(float);
5187     //   };
5188     //
5189     //   void X::f(int) { } // ill-formed
5190     //
5191     // In this case, Previous will point to the overload set
5192     // containing the two f's declared in X, but neither of them
5193     // matches.
5194 
5195     // C++ [dcl.meaning]p1:
5196     //   [...] the member shall not merely have been introduced by a
5197     //   using-declaration in the scope of the class or namespace nominated by
5198     //   the nested-name-specifier of the declarator-id.
5199     RemoveUsingDecls(Previous);
5200   }
5201 
5202   if (Previous.isSingleResult() &&
5203       Previous.getFoundDecl()->isTemplateParameter()) {
5204     // Maybe we will complain about the shadowed template parameter.
5205     if (!D.isInvalidType())
5206       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5207                                       Previous.getFoundDecl());
5208 
5209     // Just pretend that we didn't see the previous declaration.
5210     Previous.clear();
5211   }
5212 
5213   // In C++, the previous declaration we find might be a tag type
5214   // (class or enum). In this case, the new declaration will hide the
5215   // tag type. Note that this does does not apply if we're declaring a
5216   // typedef (C++ [dcl.typedef]p4).
5217   if (Previous.isSingleTagDecl() &&
5218       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5219     Previous.clear();
5220 
5221   // Check that there are no default arguments other than in the parameters
5222   // of a function declaration (C++ only).
5223   if (getLangOpts().CPlusPlus)
5224     CheckExtraCXXDefaultArguments(D);
5225 
5226   if (D.getDeclSpec().isConceptSpecified()) {
5227     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5228     // applied only to the definition of a function template or variable
5229     // template, declared in namespace scope
5230     if (!TemplateParamLists.size()) {
5231       Diag(D.getDeclSpec().getConceptSpecLoc(),
5232            diag:: err_concept_wrong_decl_kind);
5233       return nullptr;
5234     }
5235 
5236     if (!DC->getRedeclContext()->isFileContext()) {
5237       Diag(D.getIdentifierLoc(),
5238            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5239       return nullptr;
5240     }
5241   }
5242 
5243   NamedDecl *New;
5244 
5245   bool AddToScope = true;
5246   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5247     if (TemplateParamLists.size()) {
5248       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5249       return nullptr;
5250     }
5251 
5252     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5253   } else if (R->isFunctionType()) {
5254     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5255                                   TemplateParamLists,
5256                                   AddToScope);
5257   } else {
5258     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5259                                   AddToScope);
5260   }
5261 
5262   if (!New)
5263     return nullptr;
5264 
5265   // If this has an identifier and is not a function template specialization,
5266   // add it to the scope stack.
5267   if (New->getDeclName() && AddToScope) {
5268     // Only make a locally-scoped extern declaration visible if it is the first
5269     // declaration of this entity. Qualified lookup for such an entity should
5270     // only find this declaration if there is no visible declaration of it.
5271     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5272     PushOnScopeChains(New, S, AddToContext);
5273     if (!AddToContext)
5274       CurContext->addHiddenDecl(New);
5275   }
5276 
5277   if (isInOpenMPDeclareTargetContext())
5278     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5279 
5280   return New;
5281 }
5282 
5283 /// Helper method to turn variable array types into constant array
5284 /// types in certain situations which would otherwise be errors (for
5285 /// GCC compatibility).
5286 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5287                                                     ASTContext &Context,
5288                                                     bool &SizeIsNegative,
5289                                                     llvm::APSInt &Oversized) {
5290   // This method tries to turn a variable array into a constant
5291   // array even when the size isn't an ICE.  This is necessary
5292   // for compatibility with code that depends on gcc's buggy
5293   // constant expression folding, like struct {char x[(int)(char*)2];}
5294   SizeIsNegative = false;
5295   Oversized = 0;
5296 
5297   if (T->isDependentType())
5298     return QualType();
5299 
5300   QualifierCollector Qs;
5301   const Type *Ty = Qs.strip(T);
5302 
5303   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5304     QualType Pointee = PTy->getPointeeType();
5305     QualType FixedType =
5306         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5307                                             Oversized);
5308     if (FixedType.isNull()) return FixedType;
5309     FixedType = Context.getPointerType(FixedType);
5310     return Qs.apply(Context, FixedType);
5311   }
5312   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5313     QualType Inner = PTy->getInnerType();
5314     QualType FixedType =
5315         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5316                                             Oversized);
5317     if (FixedType.isNull()) return FixedType;
5318     FixedType = Context.getParenType(FixedType);
5319     return Qs.apply(Context, FixedType);
5320   }
5321 
5322   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5323   if (!VLATy)
5324     return QualType();
5325   // FIXME: We should probably handle this case
5326   if (VLATy->getElementType()->isVariablyModifiedType())
5327     return QualType();
5328 
5329   llvm::APSInt Res;
5330   if (!VLATy->getSizeExpr() ||
5331       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5332     return QualType();
5333 
5334   // Check whether the array size is negative.
5335   if (Res.isSigned() && Res.isNegative()) {
5336     SizeIsNegative = true;
5337     return QualType();
5338   }
5339 
5340   // Check whether the array is too large to be addressed.
5341   unsigned ActiveSizeBits
5342     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5343                                               Res);
5344   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5345     Oversized = Res;
5346     return QualType();
5347   }
5348 
5349   return Context.getConstantArrayType(VLATy->getElementType(),
5350                                       Res, ArrayType::Normal, 0);
5351 }
5352 
5353 static void
5354 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5355   SrcTL = SrcTL.getUnqualifiedLoc();
5356   DstTL = DstTL.getUnqualifiedLoc();
5357   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5358     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5359     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5360                                       DstPTL.getPointeeLoc());
5361     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5362     return;
5363   }
5364   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5365     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5366     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5367                                       DstPTL.getInnerLoc());
5368     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5369     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5370     return;
5371   }
5372   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5373   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5374   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5375   TypeLoc DstElemTL = DstATL.getElementLoc();
5376   DstElemTL.initializeFullCopy(SrcElemTL);
5377   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5378   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5379   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5380 }
5381 
5382 /// Helper method to turn variable array types into constant array
5383 /// types in certain situations which would otherwise be errors (for
5384 /// GCC compatibility).
5385 static TypeSourceInfo*
5386 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5387                                               ASTContext &Context,
5388                                               bool &SizeIsNegative,
5389                                               llvm::APSInt &Oversized) {
5390   QualType FixedTy
5391     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5392                                           SizeIsNegative, Oversized);
5393   if (FixedTy.isNull())
5394     return nullptr;
5395   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5396   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5397                                     FixedTInfo->getTypeLoc());
5398   return FixedTInfo;
5399 }
5400 
5401 /// \brief Register the given locally-scoped extern "C" declaration so
5402 /// that it can be found later for redeclarations. We include any extern "C"
5403 /// declaration that is not visible in the translation unit here, not just
5404 /// function-scope declarations.
5405 void
5406 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5407   if (!getLangOpts().CPlusPlus &&
5408       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5409     // Don't need to track declarations in the TU in C.
5410     return;
5411 
5412   // Note that we have a locally-scoped external with this name.
5413   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5414 }
5415 
5416 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5417   // FIXME: We can have multiple results via __attribute__((overloadable)).
5418   auto Result = Context.getExternCContextDecl()->lookup(Name);
5419   return Result.empty() ? nullptr : *Result.begin();
5420 }
5421 
5422 /// \brief Diagnose function specifiers on a declaration of an identifier that
5423 /// does not identify a function.
5424 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5425   // FIXME: We should probably indicate the identifier in question to avoid
5426   // confusion for constructs like "virtual int a(), b;"
5427   if (DS.isVirtualSpecified())
5428     Diag(DS.getVirtualSpecLoc(),
5429          diag::err_virtual_non_function);
5430 
5431   if (DS.isExplicitSpecified())
5432     Diag(DS.getExplicitSpecLoc(),
5433          diag::err_explicit_non_function);
5434 
5435   if (DS.isNoreturnSpecified())
5436     Diag(DS.getNoreturnSpecLoc(),
5437          diag::err_noreturn_non_function);
5438 }
5439 
5440 NamedDecl*
5441 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5442                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5443   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5444   if (D.getCXXScopeSpec().isSet()) {
5445     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5446       << D.getCXXScopeSpec().getRange();
5447     D.setInvalidType();
5448     // Pretend we didn't see the scope specifier.
5449     DC = CurContext;
5450     Previous.clear();
5451   }
5452 
5453   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5454 
5455   if (D.getDeclSpec().isInlineSpecified())
5456     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5457         << getLangOpts().CPlusPlus1z;
5458   if (D.getDeclSpec().isConstexprSpecified())
5459     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5460       << 1;
5461   if (D.getDeclSpec().isConceptSpecified())
5462     Diag(D.getDeclSpec().getConceptSpecLoc(),
5463          diag::err_concept_wrong_decl_kind);
5464 
5465   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5466     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5467       Diag(D.getName().StartLocation,
5468            diag::err_deduction_guide_invalid_specifier)
5469           << "typedef";
5470     else
5471       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5472           << D.getName().getSourceRange();
5473     return nullptr;
5474   }
5475 
5476   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5477   if (!NewTD) return nullptr;
5478 
5479   // Handle attributes prior to checking for duplicates in MergeVarDecl
5480   ProcessDeclAttributes(S, NewTD, D);
5481 
5482   CheckTypedefForVariablyModifiedType(S, NewTD);
5483 
5484   bool Redeclaration = D.isRedeclaration();
5485   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5486   D.setRedeclaration(Redeclaration);
5487   return ND;
5488 }
5489 
5490 void
5491 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5492   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5493   // then it shall have block scope.
5494   // Note that variably modified types must be fixed before merging the decl so
5495   // that redeclarations will match.
5496   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5497   QualType T = TInfo->getType();
5498   if (T->isVariablyModifiedType()) {
5499     getCurFunction()->setHasBranchProtectedScope();
5500 
5501     if (S->getFnParent() == nullptr) {
5502       bool SizeIsNegative;
5503       llvm::APSInt Oversized;
5504       TypeSourceInfo *FixedTInfo =
5505         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5506                                                       SizeIsNegative,
5507                                                       Oversized);
5508       if (FixedTInfo) {
5509         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5510         NewTD->setTypeSourceInfo(FixedTInfo);
5511       } else {
5512         if (SizeIsNegative)
5513           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5514         else if (T->isVariableArrayType())
5515           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5516         else if (Oversized.getBoolValue())
5517           Diag(NewTD->getLocation(), diag::err_array_too_large)
5518             << Oversized.toString(10);
5519         else
5520           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5521         NewTD->setInvalidDecl();
5522       }
5523     }
5524   }
5525 }
5526 
5527 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5528 /// declares a typedef-name, either using the 'typedef' type specifier or via
5529 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5530 NamedDecl*
5531 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5532                            LookupResult &Previous, bool &Redeclaration) {
5533   // Merge the decl with the existing one if appropriate. If the decl is
5534   // in an outer scope, it isn't the same thing.
5535   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5536                        /*AllowInlineNamespace*/false);
5537   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5538   if (!Previous.empty()) {
5539     Redeclaration = true;
5540     MergeTypedefNameDecl(S, NewTD, Previous);
5541   }
5542 
5543   // If this is the C FILE type, notify the AST context.
5544   if (IdentifierInfo *II = NewTD->getIdentifier())
5545     if (!NewTD->isInvalidDecl() &&
5546         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5547       if (II->isStr("FILE"))
5548         Context.setFILEDecl(NewTD);
5549       else if (II->isStr("jmp_buf"))
5550         Context.setjmp_bufDecl(NewTD);
5551       else if (II->isStr("sigjmp_buf"))
5552         Context.setsigjmp_bufDecl(NewTD);
5553       else if (II->isStr("ucontext_t"))
5554         Context.setucontext_tDecl(NewTD);
5555     }
5556 
5557   return NewTD;
5558 }
5559 
5560 /// \brief Determines whether the given declaration is an out-of-scope
5561 /// previous declaration.
5562 ///
5563 /// This routine should be invoked when name lookup has found a
5564 /// previous declaration (PrevDecl) that is not in the scope where a
5565 /// new declaration by the same name is being introduced. If the new
5566 /// declaration occurs in a local scope, previous declarations with
5567 /// linkage may still be considered previous declarations (C99
5568 /// 6.2.2p4-5, C++ [basic.link]p6).
5569 ///
5570 /// \param PrevDecl the previous declaration found by name
5571 /// lookup
5572 ///
5573 /// \param DC the context in which the new declaration is being
5574 /// declared.
5575 ///
5576 /// \returns true if PrevDecl is an out-of-scope previous declaration
5577 /// for a new delcaration with the same name.
5578 static bool
5579 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5580                                 ASTContext &Context) {
5581   if (!PrevDecl)
5582     return false;
5583 
5584   if (!PrevDecl->hasLinkage())
5585     return false;
5586 
5587   if (Context.getLangOpts().CPlusPlus) {
5588     // C++ [basic.link]p6:
5589     //   If there is a visible declaration of an entity with linkage
5590     //   having the same name and type, ignoring entities declared
5591     //   outside the innermost enclosing namespace scope, the block
5592     //   scope declaration declares that same entity and receives the
5593     //   linkage of the previous declaration.
5594     DeclContext *OuterContext = DC->getRedeclContext();
5595     if (!OuterContext->isFunctionOrMethod())
5596       // This rule only applies to block-scope declarations.
5597       return false;
5598 
5599     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5600     if (PrevOuterContext->isRecord())
5601       // We found a member function: ignore it.
5602       return false;
5603 
5604     // Find the innermost enclosing namespace for the new and
5605     // previous declarations.
5606     OuterContext = OuterContext->getEnclosingNamespaceContext();
5607     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5608 
5609     // The previous declaration is in a different namespace, so it
5610     // isn't the same function.
5611     if (!OuterContext->Equals(PrevOuterContext))
5612       return false;
5613   }
5614 
5615   return true;
5616 }
5617 
5618 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5619   CXXScopeSpec &SS = D.getCXXScopeSpec();
5620   if (!SS.isSet()) return;
5621   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5622 }
5623 
5624 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5625   QualType type = decl->getType();
5626   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5627   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5628     // Various kinds of declaration aren't allowed to be __autoreleasing.
5629     unsigned kind = -1U;
5630     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5631       if (var->hasAttr<BlocksAttr>())
5632         kind = 0; // __block
5633       else if (!var->hasLocalStorage())
5634         kind = 1; // global
5635     } else if (isa<ObjCIvarDecl>(decl)) {
5636       kind = 3; // ivar
5637     } else if (isa<FieldDecl>(decl)) {
5638       kind = 2; // field
5639     }
5640 
5641     if (kind != -1U) {
5642       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5643         << kind;
5644     }
5645   } else if (lifetime == Qualifiers::OCL_None) {
5646     // Try to infer lifetime.
5647     if (!type->isObjCLifetimeType())
5648       return false;
5649 
5650     lifetime = type->getObjCARCImplicitLifetime();
5651     type = Context.getLifetimeQualifiedType(type, lifetime);
5652     decl->setType(type);
5653   }
5654 
5655   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5656     // Thread-local variables cannot have lifetime.
5657     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5658         var->getTLSKind()) {
5659       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5660         << var->getType();
5661       return true;
5662     }
5663   }
5664 
5665   return false;
5666 }
5667 
5668 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5669   // Ensure that an auto decl is deduced otherwise the checks below might cache
5670   // the wrong linkage.
5671   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5672 
5673   // 'weak' only applies to declarations with external linkage.
5674   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5675     if (!ND.isExternallyVisible()) {
5676       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5677       ND.dropAttr<WeakAttr>();
5678     }
5679   }
5680   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5681     if (ND.isExternallyVisible()) {
5682       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5683       ND.dropAttr<WeakRefAttr>();
5684       ND.dropAttr<AliasAttr>();
5685     }
5686   }
5687 
5688   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5689     if (VD->hasInit()) {
5690       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5691         assert(VD->isThisDeclarationADefinition() &&
5692                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5693         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5694         VD->dropAttr<AliasAttr>();
5695       }
5696     }
5697   }
5698 
5699   // 'selectany' only applies to externally visible variable declarations.
5700   // It does not apply to functions.
5701   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5702     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5703       S.Diag(Attr->getLocation(),
5704              diag::err_attribute_selectany_non_extern_data);
5705       ND.dropAttr<SelectAnyAttr>();
5706     }
5707   }
5708 
5709   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5710     // dll attributes require external linkage. Static locals may have external
5711     // linkage but still cannot be explicitly imported or exported.
5712     auto *VD = dyn_cast<VarDecl>(&ND);
5713     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5714       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5715         << &ND << Attr;
5716       ND.setInvalidDecl();
5717     }
5718   }
5719 
5720   // Virtual functions cannot be marked as 'notail'.
5721   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5722     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5723       if (MD->isVirtual()) {
5724         S.Diag(ND.getLocation(),
5725                diag::err_invalid_attribute_on_virtual_function)
5726             << Attr;
5727         ND.dropAttr<NotTailCalledAttr>();
5728       }
5729 }
5730 
5731 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5732                                            NamedDecl *NewDecl,
5733                                            bool IsSpecialization,
5734                                            bool IsDefinition) {
5735   if (OldDecl->isInvalidDecl())
5736     return;
5737 
5738   bool IsTemplate = false;
5739   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5740     OldDecl = OldTD->getTemplatedDecl();
5741     IsTemplate = true;
5742     if (!IsSpecialization)
5743       IsDefinition = false;
5744   }
5745   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5746     NewDecl = NewTD->getTemplatedDecl();
5747     IsTemplate = true;
5748   }
5749 
5750   if (!OldDecl || !NewDecl)
5751     return;
5752 
5753   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5754   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5755   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5756   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5757 
5758   // dllimport and dllexport are inheritable attributes so we have to exclude
5759   // inherited attribute instances.
5760   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5761                     (NewExportAttr && !NewExportAttr->isInherited());
5762 
5763   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5764   // the only exception being explicit specializations.
5765   // Implicitly generated declarations are also excluded for now because there
5766   // is no other way to switch these to use dllimport or dllexport.
5767   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5768 
5769   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5770     // Allow with a warning for free functions and global variables.
5771     bool JustWarn = false;
5772     if (!OldDecl->isCXXClassMember()) {
5773       auto *VD = dyn_cast<VarDecl>(OldDecl);
5774       if (VD && !VD->getDescribedVarTemplate())
5775         JustWarn = true;
5776       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5777       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5778         JustWarn = true;
5779     }
5780 
5781     // We cannot change a declaration that's been used because IR has already
5782     // been emitted. Dllimported functions will still work though (modulo
5783     // address equality) as they can use the thunk.
5784     if (OldDecl->isUsed())
5785       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5786         JustWarn = false;
5787 
5788     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5789                                : diag::err_attribute_dll_redeclaration;
5790     S.Diag(NewDecl->getLocation(), DiagID)
5791         << NewDecl
5792         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5793     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5794     if (!JustWarn) {
5795       NewDecl->setInvalidDecl();
5796       return;
5797     }
5798   }
5799 
5800   // A redeclaration is not allowed to drop a dllimport attribute, the only
5801   // exceptions being inline function definitions (except for function
5802   // templates), local extern declarations, qualified friend declarations or
5803   // special MSVC extension: in the last case, the declaration is treated as if
5804   // it were marked dllexport.
5805   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5806   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5807   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5808     // Ignore static data because out-of-line definitions are diagnosed
5809     // separately.
5810     IsStaticDataMember = VD->isStaticDataMember();
5811     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5812                    VarDecl::DeclarationOnly;
5813   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5814     IsInline = FD->isInlined();
5815     IsQualifiedFriend = FD->getQualifier() &&
5816                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5817   }
5818 
5819   if (OldImportAttr && !HasNewAttr &&
5820       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5821       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5822     if (IsMicrosoft && IsDefinition) {
5823       S.Diag(NewDecl->getLocation(),
5824              diag::warn_redeclaration_without_import_attribute)
5825           << NewDecl;
5826       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5827       NewDecl->dropAttr<DLLImportAttr>();
5828       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5829           NewImportAttr->getRange(), S.Context,
5830           NewImportAttr->getSpellingListIndex()));
5831     } else {
5832       S.Diag(NewDecl->getLocation(),
5833              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5834           << NewDecl << OldImportAttr;
5835       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5836       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5837       OldDecl->dropAttr<DLLImportAttr>();
5838       NewDecl->dropAttr<DLLImportAttr>();
5839     }
5840   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5841     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5842     OldDecl->dropAttr<DLLImportAttr>();
5843     NewDecl->dropAttr<DLLImportAttr>();
5844     S.Diag(NewDecl->getLocation(),
5845            diag::warn_dllimport_dropped_from_inline_function)
5846         << NewDecl << OldImportAttr;
5847   }
5848 }
5849 
5850 /// Given that we are within the definition of the given function,
5851 /// will that definition behave like C99's 'inline', where the
5852 /// definition is discarded except for optimization purposes?
5853 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5854   // Try to avoid calling GetGVALinkageForFunction.
5855 
5856   // All cases of this require the 'inline' keyword.
5857   if (!FD->isInlined()) return false;
5858 
5859   // This is only possible in C++ with the gnu_inline attribute.
5860   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5861     return false;
5862 
5863   // Okay, go ahead and call the relatively-more-expensive function.
5864   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5865 }
5866 
5867 /// Determine whether a variable is extern "C" prior to attaching
5868 /// an initializer. We can't just call isExternC() here, because that
5869 /// will also compute and cache whether the declaration is externally
5870 /// visible, which might change when we attach the initializer.
5871 ///
5872 /// This can only be used if the declaration is known to not be a
5873 /// redeclaration of an internal linkage declaration.
5874 ///
5875 /// For instance:
5876 ///
5877 ///   auto x = []{};
5878 ///
5879 /// Attaching the initializer here makes this declaration not externally
5880 /// visible, because its type has internal linkage.
5881 ///
5882 /// FIXME: This is a hack.
5883 template<typename T>
5884 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5885   if (S.getLangOpts().CPlusPlus) {
5886     // In C++, the overloadable attribute negates the effects of extern "C".
5887     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5888       return false;
5889 
5890     // So do CUDA's host/device attributes.
5891     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5892                                  D->template hasAttr<CUDAHostAttr>()))
5893       return false;
5894   }
5895   return D->isExternC();
5896 }
5897 
5898 static bool shouldConsiderLinkage(const VarDecl *VD) {
5899   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5900   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5901     return VD->hasExternalStorage();
5902   if (DC->isFileContext())
5903     return true;
5904   if (DC->isRecord())
5905     return false;
5906   llvm_unreachable("Unexpected context");
5907 }
5908 
5909 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5910   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5911   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5912       isa<OMPDeclareReductionDecl>(DC))
5913     return true;
5914   if (DC->isRecord())
5915     return false;
5916   llvm_unreachable("Unexpected context");
5917 }
5918 
5919 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5920                           AttributeList::Kind Kind) {
5921   for (const AttributeList *L = AttrList; L; L = L->getNext())
5922     if (L->getKind() == Kind)
5923       return true;
5924   return false;
5925 }
5926 
5927 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5928                           AttributeList::Kind Kind) {
5929   // Check decl attributes on the DeclSpec.
5930   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5931     return true;
5932 
5933   // Walk the declarator structure, checking decl attributes that were in a type
5934   // position to the decl itself.
5935   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5936     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5937       return true;
5938   }
5939 
5940   // Finally, check attributes on the decl itself.
5941   return hasParsedAttr(S, PD.getAttributes(), Kind);
5942 }
5943 
5944 /// Adjust the \c DeclContext for a function or variable that might be a
5945 /// function-local external declaration.
5946 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5947   if (!DC->isFunctionOrMethod())
5948     return false;
5949 
5950   // If this is a local extern function or variable declared within a function
5951   // template, don't add it into the enclosing namespace scope until it is
5952   // instantiated; it might have a dependent type right now.
5953   if (DC->isDependentContext())
5954     return true;
5955 
5956   // C++11 [basic.link]p7:
5957   //   When a block scope declaration of an entity with linkage is not found to
5958   //   refer to some other declaration, then that entity is a member of the
5959   //   innermost enclosing namespace.
5960   //
5961   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5962   // semantically-enclosing namespace, not a lexically-enclosing one.
5963   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5964     DC = DC->getParent();
5965   return true;
5966 }
5967 
5968 /// \brief Returns true if given declaration has external C language linkage.
5969 static bool isDeclExternC(const Decl *D) {
5970   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5971     return FD->isExternC();
5972   if (const auto *VD = dyn_cast<VarDecl>(D))
5973     return VD->isExternC();
5974 
5975   llvm_unreachable("Unknown type of decl!");
5976 }
5977 
5978 NamedDecl *Sema::ActOnVariableDeclarator(
5979     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5980     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5981     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5982   QualType R = TInfo->getType();
5983   DeclarationName Name = GetNameForDeclarator(D).getName();
5984 
5985   IdentifierInfo *II = Name.getAsIdentifierInfo();
5986 
5987   if (D.isDecompositionDeclarator()) {
5988     AddToScope = false;
5989     // Take the name of the first declarator as our name for diagnostic
5990     // purposes.
5991     auto &Decomp = D.getDecompositionDeclarator();
5992     if (!Decomp.bindings().empty()) {
5993       II = Decomp.bindings()[0].Name;
5994       Name = II;
5995     }
5996   } else if (!II) {
5997     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
5998     return nullptr;
5999   }
6000 
6001   if (getLangOpts().OpenCL) {
6002     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6003     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6004     // argument.
6005     if (R->isImageType() || R->isPipeType()) {
6006       Diag(D.getIdentifierLoc(),
6007            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6008           << R;
6009       D.setInvalidType();
6010       return nullptr;
6011     }
6012 
6013     // OpenCL v1.2 s6.9.r:
6014     // The event type cannot be used to declare a program scope variable.
6015     // OpenCL v2.0 s6.9.q:
6016     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6017     if (NULL == S->getParent()) {
6018       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6019         Diag(D.getIdentifierLoc(),
6020              diag::err_invalid_type_for_program_scope_var) << R;
6021         D.setInvalidType();
6022         return nullptr;
6023       }
6024     }
6025 
6026     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6027     QualType NR = R;
6028     while (NR->isPointerType()) {
6029       if (NR->isFunctionPointerType()) {
6030         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6031         D.setInvalidType();
6032         break;
6033       }
6034       NR = NR->getPointeeType();
6035     }
6036 
6037     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6038       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6039       // half array type (unless the cl_khr_fp16 extension is enabled).
6040       if (Context.getBaseElementType(R)->isHalfType()) {
6041         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6042         D.setInvalidType();
6043       }
6044     }
6045 
6046     // OpenCL v1.2 s6.9.b p4:
6047     // The sampler type cannot be used with the __local and __global address
6048     // space qualifiers.
6049     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6050       R.getAddressSpace() == LangAS::opencl_global)) {
6051       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6052     }
6053 
6054     // OpenCL v1.2 s6.9.r:
6055     // The event type cannot be used with the __local, __constant and __global
6056     // address space qualifiers.
6057     if (R->isEventT()) {
6058       if (R.getAddressSpace()) {
6059         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6060         D.setInvalidType();
6061       }
6062     }
6063   }
6064 
6065   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6066   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6067 
6068   // dllimport globals without explicit storage class are treated as extern. We
6069   // have to change the storage class this early to get the right DeclContext.
6070   if (SC == SC_None && !DC->isRecord() &&
6071       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6072       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6073     SC = SC_Extern;
6074 
6075   DeclContext *OriginalDC = DC;
6076   bool IsLocalExternDecl = SC == SC_Extern &&
6077                            adjustContextForLocalExternDecl(DC);
6078 
6079   if (SCSpec == DeclSpec::SCS_mutable) {
6080     // mutable can only appear on non-static class members, so it's always
6081     // an error here
6082     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6083     D.setInvalidType();
6084     SC = SC_None;
6085   }
6086 
6087   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6088       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6089                               D.getDeclSpec().getStorageClassSpecLoc())) {
6090     // In C++11, the 'register' storage class specifier is deprecated.
6091     // Suppress the warning in system macros, it's used in macros in some
6092     // popular C system headers, such as in glibc's htonl() macro.
6093     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6094          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6095                                    : diag::warn_deprecated_register)
6096       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6097   }
6098 
6099   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6100 
6101   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6102     // C99 6.9p2: The storage-class specifiers auto and register shall not
6103     // appear in the declaration specifiers in an external declaration.
6104     // Global Register+Asm is a GNU extension we support.
6105     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6106       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6107       D.setInvalidType();
6108     }
6109   }
6110 
6111   bool IsMemberSpecialization = false;
6112   bool IsVariableTemplateSpecialization = false;
6113   bool IsPartialSpecialization = false;
6114   bool IsVariableTemplate = false;
6115   VarDecl *NewVD = nullptr;
6116   VarTemplateDecl *NewTemplate = nullptr;
6117   TemplateParameterList *TemplateParams = nullptr;
6118   if (!getLangOpts().CPlusPlus) {
6119     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6120                             D.getIdentifierLoc(), II,
6121                             R, TInfo, SC);
6122 
6123     if (R->getContainedDeducedType())
6124       ParsingInitForAutoVars.insert(NewVD);
6125 
6126     if (D.isInvalidType())
6127       NewVD->setInvalidDecl();
6128   } else {
6129     bool Invalid = false;
6130 
6131     if (DC->isRecord() && !CurContext->isRecord()) {
6132       // This is an out-of-line definition of a static data member.
6133       switch (SC) {
6134       case SC_None:
6135         break;
6136       case SC_Static:
6137         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6138              diag::err_static_out_of_line)
6139           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6140         break;
6141       case SC_Auto:
6142       case SC_Register:
6143       case SC_Extern:
6144         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6145         // to names of variables declared in a block or to function parameters.
6146         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6147         // of class members
6148 
6149         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6150              diag::err_storage_class_for_static_member)
6151           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6152         break;
6153       case SC_PrivateExtern:
6154         llvm_unreachable("C storage class in c++!");
6155       }
6156     }
6157 
6158     if (SC == SC_Static && CurContext->isRecord()) {
6159       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6160         if (RD->isLocalClass())
6161           Diag(D.getIdentifierLoc(),
6162                diag::err_static_data_member_not_allowed_in_local_class)
6163             << Name << RD->getDeclName();
6164 
6165         // C++98 [class.union]p1: If a union contains a static data member,
6166         // the program is ill-formed. C++11 drops this restriction.
6167         if (RD->isUnion())
6168           Diag(D.getIdentifierLoc(),
6169                getLangOpts().CPlusPlus11
6170                  ? diag::warn_cxx98_compat_static_data_member_in_union
6171                  : diag::ext_static_data_member_in_union) << Name;
6172         // We conservatively disallow static data members in anonymous structs.
6173         else if (!RD->getDeclName())
6174           Diag(D.getIdentifierLoc(),
6175                diag::err_static_data_member_not_allowed_in_anon_struct)
6176             << Name << RD->isUnion();
6177       }
6178     }
6179 
6180     // Match up the template parameter lists with the scope specifier, then
6181     // determine whether we have a template or a template specialization.
6182     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6183         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6184         D.getCXXScopeSpec(),
6185         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6186             ? D.getName().TemplateId
6187             : nullptr,
6188         TemplateParamLists,
6189         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6190 
6191     if (TemplateParams) {
6192       if (!TemplateParams->size() &&
6193           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6194         // There is an extraneous 'template<>' for this variable. Complain
6195         // about it, but allow the declaration of the variable.
6196         Diag(TemplateParams->getTemplateLoc(),
6197              diag::err_template_variable_noparams)
6198           << II
6199           << SourceRange(TemplateParams->getTemplateLoc(),
6200                          TemplateParams->getRAngleLoc());
6201         TemplateParams = nullptr;
6202       } else {
6203         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6204           // This is an explicit specialization or a partial specialization.
6205           // FIXME: Check that we can declare a specialization here.
6206           IsVariableTemplateSpecialization = true;
6207           IsPartialSpecialization = TemplateParams->size() > 0;
6208         } else { // if (TemplateParams->size() > 0)
6209           // This is a template declaration.
6210           IsVariableTemplate = true;
6211 
6212           // Check that we can declare a template here.
6213           if (CheckTemplateDeclScope(S, TemplateParams))
6214             return nullptr;
6215 
6216           // Only C++1y supports variable templates (N3651).
6217           Diag(D.getIdentifierLoc(),
6218                getLangOpts().CPlusPlus14
6219                    ? diag::warn_cxx11_compat_variable_template
6220                    : diag::ext_variable_template);
6221         }
6222       }
6223     } else {
6224       assert(
6225           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6226           "should have a 'template<>' for this decl");
6227     }
6228 
6229     if (IsVariableTemplateSpecialization) {
6230       SourceLocation TemplateKWLoc =
6231           TemplateParamLists.size() > 0
6232               ? TemplateParamLists[0]->getTemplateLoc()
6233               : SourceLocation();
6234       DeclResult Res = ActOnVarTemplateSpecialization(
6235           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6236           IsPartialSpecialization);
6237       if (Res.isInvalid())
6238         return nullptr;
6239       NewVD = cast<VarDecl>(Res.get());
6240       AddToScope = false;
6241     } else if (D.isDecompositionDeclarator()) {
6242       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6243                                         D.getIdentifierLoc(), R, TInfo, SC,
6244                                         Bindings);
6245     } else
6246       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6247                               D.getIdentifierLoc(), II, R, TInfo, SC);
6248 
6249     // If this is supposed to be a variable template, create it as such.
6250     if (IsVariableTemplate) {
6251       NewTemplate =
6252           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6253                                   TemplateParams, NewVD);
6254       NewVD->setDescribedVarTemplate(NewTemplate);
6255     }
6256 
6257     // If this decl has an auto type in need of deduction, make a note of the
6258     // Decl so we can diagnose uses of it in its own initializer.
6259     if (R->getContainedDeducedType())
6260       ParsingInitForAutoVars.insert(NewVD);
6261 
6262     if (D.isInvalidType() || Invalid) {
6263       NewVD->setInvalidDecl();
6264       if (NewTemplate)
6265         NewTemplate->setInvalidDecl();
6266     }
6267 
6268     SetNestedNameSpecifier(NewVD, D);
6269 
6270     // If we have any template parameter lists that don't directly belong to
6271     // the variable (matching the scope specifier), store them.
6272     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6273     if (TemplateParamLists.size() > VDTemplateParamLists)
6274       NewVD->setTemplateParameterListsInfo(
6275           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6276 
6277     if (D.getDeclSpec().isConstexprSpecified()) {
6278       NewVD->setConstexpr(true);
6279       // C++1z [dcl.spec.constexpr]p1:
6280       //   A static data member declared with the constexpr specifier is
6281       //   implicitly an inline variable.
6282       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6283         NewVD->setImplicitlyInline();
6284     }
6285 
6286     if (D.getDeclSpec().isConceptSpecified()) {
6287       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6288         VTD->setConcept();
6289 
6290       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6291       // be declared with the thread_local, inline, friend, or constexpr
6292       // specifiers, [...]
6293       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6294         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6295              diag::err_concept_decl_invalid_specifiers)
6296             << 0 << 0;
6297         NewVD->setInvalidDecl(true);
6298       }
6299 
6300       if (D.getDeclSpec().isConstexprSpecified()) {
6301         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6302              diag::err_concept_decl_invalid_specifiers)
6303             << 0 << 3;
6304         NewVD->setInvalidDecl(true);
6305       }
6306 
6307       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6308       // applied only to the definition of a function template or variable
6309       // template, declared in namespace scope.
6310       if (IsVariableTemplateSpecialization) {
6311         Diag(D.getDeclSpec().getConceptSpecLoc(),
6312              diag::err_concept_specified_specialization)
6313             << (IsPartialSpecialization ? 2 : 1);
6314       }
6315 
6316       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6317       // following restrictions:
6318       // - The declared type shall have the type bool.
6319       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6320           !NewVD->isInvalidDecl()) {
6321         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6322         NewVD->setInvalidDecl(true);
6323       }
6324     }
6325   }
6326 
6327   if (D.getDeclSpec().isInlineSpecified()) {
6328     if (!getLangOpts().CPlusPlus) {
6329       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6330           << 0;
6331     } else if (CurContext->isFunctionOrMethod()) {
6332       // 'inline' is not allowed on block scope variable declaration.
6333       Diag(D.getDeclSpec().getInlineSpecLoc(),
6334            diag::err_inline_declaration_block_scope) << Name
6335         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6336     } else {
6337       Diag(D.getDeclSpec().getInlineSpecLoc(),
6338            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6339                                      : diag::ext_inline_variable);
6340       NewVD->setInlineSpecified();
6341     }
6342   }
6343 
6344   // Set the lexical context. If the declarator has a C++ scope specifier, the
6345   // lexical context will be different from the semantic context.
6346   NewVD->setLexicalDeclContext(CurContext);
6347   if (NewTemplate)
6348     NewTemplate->setLexicalDeclContext(CurContext);
6349 
6350   if (IsLocalExternDecl) {
6351     if (D.isDecompositionDeclarator())
6352       for (auto *B : Bindings)
6353         B->setLocalExternDecl();
6354     else
6355       NewVD->setLocalExternDecl();
6356   }
6357 
6358   bool EmitTLSUnsupportedError = false;
6359   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6360     // C++11 [dcl.stc]p4:
6361     //   When thread_local is applied to a variable of block scope the
6362     //   storage-class-specifier static is implied if it does not appear
6363     //   explicitly.
6364     // Core issue: 'static' is not implied if the variable is declared
6365     //   'extern'.
6366     if (NewVD->hasLocalStorage() &&
6367         (SCSpec != DeclSpec::SCS_unspecified ||
6368          TSCS != DeclSpec::TSCS_thread_local ||
6369          !DC->isFunctionOrMethod()))
6370       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6371            diag::err_thread_non_global)
6372         << DeclSpec::getSpecifierName(TSCS);
6373     else if (!Context.getTargetInfo().isTLSSupported()) {
6374       if (getLangOpts().CUDA) {
6375         // Postpone error emission until we've collected attributes required to
6376         // figure out whether it's a host or device variable and whether the
6377         // error should be ignored.
6378         EmitTLSUnsupportedError = true;
6379         // We still need to mark the variable as TLS so it shows up in AST with
6380         // proper storage class for other tools to use even if we're not going
6381         // to emit any code for it.
6382         NewVD->setTSCSpec(TSCS);
6383       } else
6384         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6385              diag::err_thread_unsupported);
6386     } else
6387       NewVD->setTSCSpec(TSCS);
6388   }
6389 
6390   // C99 6.7.4p3
6391   //   An inline definition of a function with external linkage shall
6392   //   not contain a definition of a modifiable object with static or
6393   //   thread storage duration...
6394   // We only apply this when the function is required to be defined
6395   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6396   // that a local variable with thread storage duration still has to
6397   // be marked 'static'.  Also note that it's possible to get these
6398   // semantics in C++ using __attribute__((gnu_inline)).
6399   if (SC == SC_Static && S->getFnParent() != nullptr &&
6400       !NewVD->getType().isConstQualified()) {
6401     FunctionDecl *CurFD = getCurFunctionDecl();
6402     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6403       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6404            diag::warn_static_local_in_extern_inline);
6405       MaybeSuggestAddingStaticToDecl(CurFD);
6406     }
6407   }
6408 
6409   if (D.getDeclSpec().isModulePrivateSpecified()) {
6410     if (IsVariableTemplateSpecialization)
6411       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6412           << (IsPartialSpecialization ? 1 : 0)
6413           << FixItHint::CreateRemoval(
6414                  D.getDeclSpec().getModulePrivateSpecLoc());
6415     else if (IsMemberSpecialization)
6416       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6417         << 2
6418         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6419     else if (NewVD->hasLocalStorage())
6420       Diag(NewVD->getLocation(), diag::err_module_private_local)
6421         << 0 << NewVD->getDeclName()
6422         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6423         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6424     else {
6425       NewVD->setModulePrivate();
6426       if (NewTemplate)
6427         NewTemplate->setModulePrivate();
6428       for (auto *B : Bindings)
6429         B->setModulePrivate();
6430     }
6431   }
6432 
6433   // Handle attributes prior to checking for duplicates in MergeVarDecl
6434   ProcessDeclAttributes(S, NewVD, D);
6435 
6436   if (getLangOpts().CUDA) {
6437     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6438       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6439            diag::err_thread_unsupported);
6440     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6441     // storage [duration]."
6442     if (SC == SC_None && S->getFnParent() != nullptr &&
6443         (NewVD->hasAttr<CUDASharedAttr>() ||
6444          NewVD->hasAttr<CUDAConstantAttr>())) {
6445       NewVD->setStorageClass(SC_Static);
6446     }
6447   }
6448 
6449   // Ensure that dllimport globals without explicit storage class are treated as
6450   // extern. The storage class is set above using parsed attributes. Now we can
6451   // check the VarDecl itself.
6452   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6453          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6454          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6455 
6456   // In auto-retain/release, infer strong retension for variables of
6457   // retainable type.
6458   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6459     NewVD->setInvalidDecl();
6460 
6461   // Handle GNU asm-label extension (encoded as an attribute).
6462   if (Expr *E = (Expr*)D.getAsmLabel()) {
6463     // The parser guarantees this is a string.
6464     StringLiteral *SE = cast<StringLiteral>(E);
6465     StringRef Label = SE->getString();
6466     if (S->getFnParent() != nullptr) {
6467       switch (SC) {
6468       case SC_None:
6469       case SC_Auto:
6470         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6471         break;
6472       case SC_Register:
6473         // Local Named register
6474         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6475             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6476           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6477         break;
6478       case SC_Static:
6479       case SC_Extern:
6480       case SC_PrivateExtern:
6481         break;
6482       }
6483     } else if (SC == SC_Register) {
6484       // Global Named register
6485       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6486         const auto &TI = Context.getTargetInfo();
6487         bool HasSizeMismatch;
6488 
6489         if (!TI.isValidGCCRegisterName(Label))
6490           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6491         else if (!TI.validateGlobalRegisterVariable(Label,
6492                                                     Context.getTypeSize(R),
6493                                                     HasSizeMismatch))
6494           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6495         else if (HasSizeMismatch)
6496           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6497       }
6498 
6499       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6500         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6501         NewVD->setInvalidDecl(true);
6502       }
6503     }
6504 
6505     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6506                                                 Context, Label, 0));
6507   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6508     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6509       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6510     if (I != ExtnameUndeclaredIdentifiers.end()) {
6511       if (isDeclExternC(NewVD)) {
6512         NewVD->addAttr(I->second);
6513         ExtnameUndeclaredIdentifiers.erase(I);
6514       } else
6515         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6516             << /*Variable*/1 << NewVD;
6517     }
6518   }
6519 
6520   // Find the shadowed declaration before filtering for scope.
6521   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6522                                 ? getShadowedDeclaration(NewVD, Previous)
6523                                 : nullptr;
6524 
6525   // Don't consider existing declarations that are in a different
6526   // scope and are out-of-semantic-context declarations (if the new
6527   // declaration has linkage).
6528   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6529                        D.getCXXScopeSpec().isNotEmpty() ||
6530                        IsMemberSpecialization ||
6531                        IsVariableTemplateSpecialization);
6532 
6533   // Check whether the previous declaration is in the same block scope. This
6534   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6535   if (getLangOpts().CPlusPlus &&
6536       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6537     NewVD->setPreviousDeclInSameBlockScope(
6538         Previous.isSingleResult() && !Previous.isShadowed() &&
6539         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6540 
6541   if (!getLangOpts().CPlusPlus) {
6542     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6543   } else {
6544     // If this is an explicit specialization of a static data member, check it.
6545     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6546         CheckMemberSpecialization(NewVD, Previous))
6547       NewVD->setInvalidDecl();
6548 
6549     // Merge the decl with the existing one if appropriate.
6550     if (!Previous.empty()) {
6551       if (Previous.isSingleResult() &&
6552           isa<FieldDecl>(Previous.getFoundDecl()) &&
6553           D.getCXXScopeSpec().isSet()) {
6554         // The user tried to define a non-static data member
6555         // out-of-line (C++ [dcl.meaning]p1).
6556         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6557           << D.getCXXScopeSpec().getRange();
6558         Previous.clear();
6559         NewVD->setInvalidDecl();
6560       }
6561     } else if (D.getCXXScopeSpec().isSet()) {
6562       // No previous declaration in the qualifying scope.
6563       Diag(D.getIdentifierLoc(), diag::err_no_member)
6564         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6565         << D.getCXXScopeSpec().getRange();
6566       NewVD->setInvalidDecl();
6567     }
6568 
6569     if (!IsVariableTemplateSpecialization)
6570       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6571 
6572     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6573     // an explicit specialization (14.8.3) or a partial specialization of a
6574     // concept definition.
6575     if (IsVariableTemplateSpecialization &&
6576         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6577         Previous.isSingleResult()) {
6578       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6579       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6580         if (VarTmpl->isConcept()) {
6581           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6582               << 1                            /*variable*/
6583               << (IsPartialSpecialization ? 2 /*partially specialized*/
6584                                           : 1 /*explicitly specialized*/);
6585           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6586           NewVD->setInvalidDecl();
6587         }
6588       }
6589     }
6590 
6591     if (NewTemplate) {
6592       VarTemplateDecl *PrevVarTemplate =
6593           NewVD->getPreviousDecl()
6594               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6595               : nullptr;
6596 
6597       // Check the template parameter list of this declaration, possibly
6598       // merging in the template parameter list from the previous variable
6599       // template declaration.
6600       if (CheckTemplateParameterList(
6601               TemplateParams,
6602               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6603                               : nullptr,
6604               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6605                DC->isDependentContext())
6606                   ? TPC_ClassTemplateMember
6607                   : TPC_VarTemplate))
6608         NewVD->setInvalidDecl();
6609 
6610       // If we are providing an explicit specialization of a static variable
6611       // template, make a note of that.
6612       if (PrevVarTemplate &&
6613           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6614         PrevVarTemplate->setMemberSpecialization();
6615     }
6616   }
6617 
6618   // Diagnose shadowed variables iff this isn't a redeclaration.
6619   if (ShadowedDecl && !D.isRedeclaration())
6620     CheckShadow(NewVD, ShadowedDecl, Previous);
6621 
6622   ProcessPragmaWeak(S, NewVD);
6623 
6624   // If this is the first declaration of an extern C variable, update
6625   // the map of such variables.
6626   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6627       isIncompleteDeclExternC(*this, NewVD))
6628     RegisterLocallyScopedExternCDecl(NewVD, S);
6629 
6630   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6631     Decl *ManglingContextDecl;
6632     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6633             NewVD->getDeclContext(), ManglingContextDecl)) {
6634       Context.setManglingNumber(
6635           NewVD, MCtx->getManglingNumber(
6636                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6637       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6638     }
6639   }
6640 
6641   // Special handling of variable named 'main'.
6642   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6643       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6644       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6645 
6646     // C++ [basic.start.main]p3
6647     // A program that declares a variable main at global scope is ill-formed.
6648     if (getLangOpts().CPlusPlus)
6649       Diag(D.getLocStart(), diag::err_main_global_variable);
6650 
6651     // In C, and external-linkage variable named main results in undefined
6652     // behavior.
6653     else if (NewVD->hasExternalFormalLinkage())
6654       Diag(D.getLocStart(), diag::warn_main_redefined);
6655   }
6656 
6657   if (D.isRedeclaration() && !Previous.empty()) {
6658     checkDLLAttributeRedeclaration(
6659         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6660         IsMemberSpecialization, D.isFunctionDefinition());
6661   }
6662 
6663   if (NewTemplate) {
6664     if (NewVD->isInvalidDecl())
6665       NewTemplate->setInvalidDecl();
6666     ActOnDocumentableDecl(NewTemplate);
6667     return NewTemplate;
6668   }
6669 
6670   return NewVD;
6671 }
6672 
6673 /// Enum describing the %select options in diag::warn_decl_shadow.
6674 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6675 
6676 /// Determine what kind of declaration we're shadowing.
6677 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6678                                                 const DeclContext *OldDC) {
6679   if (isa<RecordDecl>(OldDC))
6680     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6681   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6682 }
6683 
6684 /// Return the location of the capture if the given lambda captures the given
6685 /// variable \p VD, or an invalid source location otherwise.
6686 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6687                                          const VarDecl *VD) {
6688   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6689     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6690       return Capture.getLocation();
6691   }
6692   return SourceLocation();
6693 }
6694 
6695 /// \brief Return the declaration shadowed by the given variable \p D, or null
6696 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6697 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6698                                         const LookupResult &R) {
6699   // Return if warning is ignored.
6700   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6701     return nullptr;
6702 
6703   // Don't diagnose declarations at file scope.
6704   if (D->hasGlobalStorage())
6705     return nullptr;
6706 
6707   // Only diagnose if we're shadowing an unambiguous field or variable.
6708   if (R.getResultKind() != LookupResult::Found)
6709     return nullptr;
6710 
6711   NamedDecl *ShadowedDecl = R.getFoundDecl();
6712   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6713              ? ShadowedDecl
6714              : nullptr;
6715 }
6716 
6717 /// \brief Diagnose variable or built-in function shadowing.  Implements
6718 /// -Wshadow.
6719 ///
6720 /// This method is called whenever a VarDecl is added to a "useful"
6721 /// scope.
6722 ///
6723 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6724 /// \param R the lookup of the name
6725 ///
6726 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl,
6727                        const LookupResult &R) {
6728   DeclContext *NewDC = D->getDeclContext();
6729 
6730   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6731     // Fields are not shadowed by variables in C++ static methods.
6732     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6733       if (MD->isStatic())
6734         return;
6735 
6736     // Fields shadowed by constructor parameters are a special case. Usually
6737     // the constructor initializes the field with the parameter.
6738     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6739       // Remember that this was shadowed so we can either warn about its
6740       // modification or its existence depending on warning settings.
6741       D = D->getCanonicalDecl();
6742       ShadowingDecls.insert({D, FD});
6743       return;
6744     }
6745   }
6746 
6747   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6748     if (shadowedVar->isExternC()) {
6749       // For shadowing external vars, make sure that we point to the global
6750       // declaration, not a locally scoped extern declaration.
6751       for (auto I : shadowedVar->redecls())
6752         if (I->isFileVarDecl()) {
6753           ShadowedDecl = I;
6754           break;
6755         }
6756     }
6757 
6758   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6759 
6760   unsigned WarningDiag = diag::warn_decl_shadow;
6761   SourceLocation CaptureLoc;
6762   if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
6763     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6764       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6765         if (RD->getLambdaCaptureDefault() == LCD_None) {
6766           // Try to avoid warnings for lambdas with an explicit capture list.
6767           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6768           // Warn only when the lambda captures the shadowed decl explicitly.
6769           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6770           if (CaptureLoc.isInvalid())
6771             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6772         } else {
6773           // Remember that this was shadowed so we can avoid the warning if the
6774           // shadowed decl isn't captured and the warning settings allow it.
6775           cast<LambdaScopeInfo>(getCurFunction())
6776               ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
6777           return;
6778         }
6779       }
6780     }
6781   }
6782 
6783   // Only warn about certain kinds of shadowing for class members.
6784   if (NewDC && NewDC->isRecord()) {
6785     // In particular, don't warn about shadowing non-class members.
6786     if (!OldDC->isRecord())
6787       return;
6788 
6789     // TODO: should we warn about static data members shadowing
6790     // static data members from base classes?
6791 
6792     // TODO: don't diagnose for inaccessible shadowed members.
6793     // This is hard to do perfectly because we might friend the
6794     // shadowing context, but that's just a false negative.
6795   }
6796 
6797 
6798   DeclarationName Name = R.getLookupName();
6799 
6800   // Emit warning and note.
6801   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6802     return;
6803   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6804   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6805   if (!CaptureLoc.isInvalid())
6806     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6807         << Name << /*explicitly*/ 1;
6808   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6809 }
6810 
6811 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6812 /// when these variables are captured by the lambda.
6813 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6814   for (const auto &Shadow : LSI->ShadowingDecls) {
6815     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6816     // Try to avoid the warning when the shadowed decl isn't captured.
6817     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6818     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6819     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6820                                        ? diag::warn_decl_shadow_uncaptured_local
6821                                        : diag::warn_decl_shadow)
6822         << Shadow.VD->getDeclName()
6823         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6824     if (!CaptureLoc.isInvalid())
6825       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6826           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6827     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6828   }
6829 }
6830 
6831 /// \brief Check -Wshadow without the advantage of a previous lookup.
6832 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6833   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6834     return;
6835 
6836   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6837                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6838   LookupName(R, S);
6839   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6840     CheckShadow(D, ShadowedDecl, R);
6841 }
6842 
6843 /// Check if 'E', which is an expression that is about to be modified, refers
6844 /// to a constructor parameter that shadows a field.
6845 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6846   // Quickly ignore expressions that can't be shadowing ctor parameters.
6847   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6848     return;
6849   E = E->IgnoreParenImpCasts();
6850   auto *DRE = dyn_cast<DeclRefExpr>(E);
6851   if (!DRE)
6852     return;
6853   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6854   auto I = ShadowingDecls.find(D);
6855   if (I == ShadowingDecls.end())
6856     return;
6857   const NamedDecl *ShadowedDecl = I->second;
6858   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6859   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6860   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6861   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6862 
6863   // Avoid issuing multiple warnings about the same decl.
6864   ShadowingDecls.erase(I);
6865 }
6866 
6867 /// Check for conflict between this global or extern "C" declaration and
6868 /// previous global or extern "C" declarations. This is only used in C++.
6869 template<typename T>
6870 static bool checkGlobalOrExternCConflict(
6871     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6872   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6873   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6874 
6875   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6876     // The common case: this global doesn't conflict with any extern "C"
6877     // declaration.
6878     return false;
6879   }
6880 
6881   if (Prev) {
6882     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6883       // Both the old and new declarations have C language linkage. This is a
6884       // redeclaration.
6885       Previous.clear();
6886       Previous.addDecl(Prev);
6887       return true;
6888     }
6889 
6890     // This is a global, non-extern "C" declaration, and there is a previous
6891     // non-global extern "C" declaration. Diagnose if this is a variable
6892     // declaration.
6893     if (!isa<VarDecl>(ND))
6894       return false;
6895   } else {
6896     // The declaration is extern "C". Check for any declaration in the
6897     // translation unit which might conflict.
6898     if (IsGlobal) {
6899       // We have already performed the lookup into the translation unit.
6900       IsGlobal = false;
6901       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6902            I != E; ++I) {
6903         if (isa<VarDecl>(*I)) {
6904           Prev = *I;
6905           break;
6906         }
6907       }
6908     } else {
6909       DeclContext::lookup_result R =
6910           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6911       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6912            I != E; ++I) {
6913         if (isa<VarDecl>(*I)) {
6914           Prev = *I;
6915           break;
6916         }
6917         // FIXME: If we have any other entity with this name in global scope,
6918         // the declaration is ill-formed, but that is a defect: it breaks the
6919         // 'stat' hack, for instance. Only variables can have mangled name
6920         // clashes with extern "C" declarations, so only they deserve a
6921         // diagnostic.
6922       }
6923     }
6924 
6925     if (!Prev)
6926       return false;
6927   }
6928 
6929   // Use the first declaration's location to ensure we point at something which
6930   // is lexically inside an extern "C" linkage-spec.
6931   assert(Prev && "should have found a previous declaration to diagnose");
6932   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6933     Prev = FD->getFirstDecl();
6934   else
6935     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6936 
6937   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6938     << IsGlobal << ND;
6939   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6940     << IsGlobal;
6941   return false;
6942 }
6943 
6944 /// Apply special rules for handling extern "C" declarations. Returns \c true
6945 /// if we have found that this is a redeclaration of some prior entity.
6946 ///
6947 /// Per C++ [dcl.link]p6:
6948 ///   Two declarations [for a function or variable] with C language linkage
6949 ///   with the same name that appear in different scopes refer to the same
6950 ///   [entity]. An entity with C language linkage shall not be declared with
6951 ///   the same name as an entity in global scope.
6952 template<typename T>
6953 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6954                                                   LookupResult &Previous) {
6955   if (!S.getLangOpts().CPlusPlus) {
6956     // In C, when declaring a global variable, look for a corresponding 'extern'
6957     // variable declared in function scope. We don't need this in C++, because
6958     // we find local extern decls in the surrounding file-scope DeclContext.
6959     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6960       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6961         Previous.clear();
6962         Previous.addDecl(Prev);
6963         return true;
6964       }
6965     }
6966     return false;
6967   }
6968 
6969   // A declaration in the translation unit can conflict with an extern "C"
6970   // declaration.
6971   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6972     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6973 
6974   // An extern "C" declaration can conflict with a declaration in the
6975   // translation unit or can be a redeclaration of an extern "C" declaration
6976   // in another scope.
6977   if (isIncompleteDeclExternC(S,ND))
6978     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6979 
6980   // Neither global nor extern "C": nothing to do.
6981   return false;
6982 }
6983 
6984 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6985   // If the decl is already known invalid, don't check it.
6986   if (NewVD->isInvalidDecl())
6987     return;
6988 
6989   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6990   QualType T = TInfo->getType();
6991 
6992   // Defer checking an 'auto' type until its initializer is attached.
6993   if (T->isUndeducedType())
6994     return;
6995 
6996   if (NewVD->hasAttrs())
6997     CheckAlignasUnderalignment(NewVD);
6998 
6999   if (T->isObjCObjectType()) {
7000     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7001       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7002     T = Context.getObjCObjectPointerType(T);
7003     NewVD->setType(T);
7004   }
7005 
7006   // Emit an error if an address space was applied to decl with local storage.
7007   // This includes arrays of objects with address space qualifiers, but not
7008   // automatic variables that point to other address spaces.
7009   // ISO/IEC TR 18037 S5.1.2
7010   if (!getLangOpts().OpenCL
7011       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7012     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7013     NewVD->setInvalidDecl();
7014     return;
7015   }
7016 
7017   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7018   // scope.
7019   if (getLangOpts().OpenCLVersion == 120 &&
7020       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7021       NewVD->isStaticLocal()) {
7022     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7023     NewVD->setInvalidDecl();
7024     return;
7025   }
7026 
7027   if (getLangOpts().OpenCL) {
7028     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7029     if (NewVD->hasAttr<BlocksAttr>()) {
7030       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7031       return;
7032     }
7033 
7034     if (T->isBlockPointerType()) {
7035       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7036       // can't use 'extern' storage class.
7037       if (!T.isConstQualified()) {
7038         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7039             << 0 /*const*/;
7040         NewVD->setInvalidDecl();
7041         return;
7042       }
7043       if (NewVD->hasExternalStorage()) {
7044         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7045         NewVD->setInvalidDecl();
7046         return;
7047       }
7048     }
7049     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7050     // __constant address space.
7051     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7052     // variables inside a function can also be declared in the global
7053     // address space.
7054     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7055         NewVD->hasExternalStorage()) {
7056       if (!T->isSamplerT() &&
7057           !(T.getAddressSpace() == LangAS::opencl_constant ||
7058             (T.getAddressSpace() == LangAS::opencl_global &&
7059              getLangOpts().OpenCLVersion == 200))) {
7060         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7061         if (getLangOpts().OpenCLVersion == 200)
7062           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7063               << Scope << "global or constant";
7064         else
7065           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7066               << Scope << "constant";
7067         NewVD->setInvalidDecl();
7068         return;
7069       }
7070     } else {
7071       if (T.getAddressSpace() == LangAS::opencl_global) {
7072         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7073             << 1 /*is any function*/ << "global";
7074         NewVD->setInvalidDecl();
7075         return;
7076       }
7077       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7078       // in functions.
7079       if (T.getAddressSpace() == LangAS::opencl_constant ||
7080           T.getAddressSpace() == LangAS::opencl_local) {
7081         FunctionDecl *FD = getCurFunctionDecl();
7082         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7083           if (T.getAddressSpace() == LangAS::opencl_constant)
7084             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7085                 << 0 /*non-kernel only*/ << "constant";
7086           else
7087             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7088                 << 0 /*non-kernel only*/ << "local";
7089           NewVD->setInvalidDecl();
7090           return;
7091         }
7092       }
7093     }
7094   }
7095 
7096   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7097       && !NewVD->hasAttr<BlocksAttr>()) {
7098     if (getLangOpts().getGC() != LangOptions::NonGC)
7099       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7100     else {
7101       assert(!getLangOpts().ObjCAutoRefCount);
7102       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7103     }
7104   }
7105 
7106   bool isVM = T->isVariablyModifiedType();
7107   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7108       NewVD->hasAttr<BlocksAttr>())
7109     getCurFunction()->setHasBranchProtectedScope();
7110 
7111   if ((isVM && NewVD->hasLinkage()) ||
7112       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7113     bool SizeIsNegative;
7114     llvm::APSInt Oversized;
7115     TypeSourceInfo *FixedTInfo =
7116       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7117                                                     SizeIsNegative, Oversized);
7118     if (!FixedTInfo && T->isVariableArrayType()) {
7119       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7120       // FIXME: This won't give the correct result for
7121       // int a[10][n];
7122       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7123 
7124       if (NewVD->isFileVarDecl())
7125         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7126         << SizeRange;
7127       else if (NewVD->isStaticLocal())
7128         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7129         << SizeRange;
7130       else
7131         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7132         << SizeRange;
7133       NewVD->setInvalidDecl();
7134       return;
7135     }
7136 
7137     if (!FixedTInfo) {
7138       if (NewVD->isFileVarDecl())
7139         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7140       else
7141         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7142       NewVD->setInvalidDecl();
7143       return;
7144     }
7145 
7146     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7147     NewVD->setType(FixedTInfo->getType());
7148     NewVD->setTypeSourceInfo(FixedTInfo);
7149   }
7150 
7151   if (T->isVoidType()) {
7152     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7153     //                    of objects and functions.
7154     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7155       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7156         << T;
7157       NewVD->setInvalidDecl();
7158       return;
7159     }
7160   }
7161 
7162   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7163     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7164     NewVD->setInvalidDecl();
7165     return;
7166   }
7167 
7168   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7169     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7170     NewVD->setInvalidDecl();
7171     return;
7172   }
7173 
7174   if (NewVD->isConstexpr() && !T->isDependentType() &&
7175       RequireLiteralType(NewVD->getLocation(), T,
7176                          diag::err_constexpr_var_non_literal)) {
7177     NewVD->setInvalidDecl();
7178     return;
7179   }
7180 }
7181 
7182 /// \brief Perform semantic checking on a newly-created variable
7183 /// declaration.
7184 ///
7185 /// This routine performs all of the type-checking required for a
7186 /// variable declaration once it has been built. It is used both to
7187 /// check variables after they have been parsed and their declarators
7188 /// have been translated into a declaration, and to check variables
7189 /// that have been instantiated from a template.
7190 ///
7191 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7192 ///
7193 /// Returns true if the variable declaration is a redeclaration.
7194 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7195   CheckVariableDeclarationType(NewVD);
7196 
7197   // If the decl is already known invalid, don't check it.
7198   if (NewVD->isInvalidDecl())
7199     return false;
7200 
7201   // If we did not find anything by this name, look for a non-visible
7202   // extern "C" declaration with the same name.
7203   if (Previous.empty() &&
7204       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7205     Previous.setShadowed();
7206 
7207   if (!Previous.empty()) {
7208     MergeVarDecl(NewVD, Previous);
7209     return true;
7210   }
7211   return false;
7212 }
7213 
7214 namespace {
7215 struct FindOverriddenMethod {
7216   Sema *S;
7217   CXXMethodDecl *Method;
7218 
7219   /// Member lookup function that determines whether a given C++
7220   /// method overrides a method in a base class, to be used with
7221   /// CXXRecordDecl::lookupInBases().
7222   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7223     RecordDecl *BaseRecord =
7224         Specifier->getType()->getAs<RecordType>()->getDecl();
7225 
7226     DeclarationName Name = Method->getDeclName();
7227 
7228     // FIXME: Do we care about other names here too?
7229     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7230       // We really want to find the base class destructor here.
7231       QualType T = S->Context.getTypeDeclType(BaseRecord);
7232       CanQualType CT = S->Context.getCanonicalType(T);
7233 
7234       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7235     }
7236 
7237     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7238          Path.Decls = Path.Decls.slice(1)) {
7239       NamedDecl *D = Path.Decls.front();
7240       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7241         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7242           return true;
7243       }
7244     }
7245 
7246     return false;
7247   }
7248 };
7249 
7250 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7251 } // end anonymous namespace
7252 
7253 /// \brief Report an error regarding overriding, along with any relevant
7254 /// overriden methods.
7255 ///
7256 /// \param DiagID the primary error to report.
7257 /// \param MD the overriding method.
7258 /// \param OEK which overrides to include as notes.
7259 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7260                             OverrideErrorKind OEK = OEK_All) {
7261   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7262   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7263                                       E = MD->end_overridden_methods();
7264        I != E; ++I) {
7265     // This check (& the OEK parameter) could be replaced by a predicate, but
7266     // without lambdas that would be overkill. This is still nicer than writing
7267     // out the diag loop 3 times.
7268     if ((OEK == OEK_All) ||
7269         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7270         (OEK == OEK_Deleted && (*I)->isDeleted()))
7271       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7272   }
7273 }
7274 
7275 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7276 /// and if so, check that it's a valid override and remember it.
7277 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7278   // Look for methods in base classes that this method might override.
7279   CXXBasePaths Paths;
7280   FindOverriddenMethod FOM;
7281   FOM.Method = MD;
7282   FOM.S = this;
7283   bool hasDeletedOverridenMethods = false;
7284   bool hasNonDeletedOverridenMethods = false;
7285   bool AddedAny = false;
7286   if (DC->lookupInBases(FOM, Paths)) {
7287     for (auto *I : Paths.found_decls()) {
7288       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7289         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7290         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7291             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7292             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7293             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7294           hasDeletedOverridenMethods |= OldMD->isDeleted();
7295           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7296           AddedAny = true;
7297         }
7298       }
7299     }
7300   }
7301 
7302   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7303     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7304   }
7305   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7306     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7307   }
7308 
7309   return AddedAny;
7310 }
7311 
7312 namespace {
7313   // Struct for holding all of the extra arguments needed by
7314   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7315   struct ActOnFDArgs {
7316     Scope *S;
7317     Declarator &D;
7318     MultiTemplateParamsArg TemplateParamLists;
7319     bool AddToScope;
7320   };
7321 } // end anonymous namespace
7322 
7323 namespace {
7324 
7325 // Callback to only accept typo corrections that have a non-zero edit distance.
7326 // Also only accept corrections that have the same parent decl.
7327 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7328  public:
7329   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7330                             CXXRecordDecl *Parent)
7331       : Context(Context), OriginalFD(TypoFD),
7332         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7333 
7334   bool ValidateCandidate(const TypoCorrection &candidate) override {
7335     if (candidate.getEditDistance() == 0)
7336       return false;
7337 
7338     SmallVector<unsigned, 1> MismatchedParams;
7339     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7340                                           CDeclEnd = candidate.end();
7341          CDecl != CDeclEnd; ++CDecl) {
7342       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7343 
7344       if (FD && !FD->hasBody() &&
7345           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7346         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7347           CXXRecordDecl *Parent = MD->getParent();
7348           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7349             return true;
7350         } else if (!ExpectedParent) {
7351           return true;
7352         }
7353       }
7354     }
7355 
7356     return false;
7357   }
7358 
7359  private:
7360   ASTContext &Context;
7361   FunctionDecl *OriginalFD;
7362   CXXRecordDecl *ExpectedParent;
7363 };
7364 
7365 } // end anonymous namespace
7366 
7367 /// \brief Generate diagnostics for an invalid function redeclaration.
7368 ///
7369 /// This routine handles generating the diagnostic messages for an invalid
7370 /// function redeclaration, including finding possible similar declarations
7371 /// or performing typo correction if there are no previous declarations with
7372 /// the same name.
7373 ///
7374 /// Returns a NamedDecl iff typo correction was performed and substituting in
7375 /// the new declaration name does not cause new errors.
7376 static NamedDecl *DiagnoseInvalidRedeclaration(
7377     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7378     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7379   DeclarationName Name = NewFD->getDeclName();
7380   DeclContext *NewDC = NewFD->getDeclContext();
7381   SmallVector<unsigned, 1> MismatchedParams;
7382   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7383   TypoCorrection Correction;
7384   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7385   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7386                                    : diag::err_member_decl_does_not_match;
7387   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7388                     IsLocalFriend ? Sema::LookupLocalFriendName
7389                                   : Sema::LookupOrdinaryName,
7390                     Sema::ForRedeclaration);
7391 
7392   NewFD->setInvalidDecl();
7393   if (IsLocalFriend)
7394     SemaRef.LookupName(Prev, S);
7395   else
7396     SemaRef.LookupQualifiedName(Prev, NewDC);
7397   assert(!Prev.isAmbiguous() &&
7398          "Cannot have an ambiguity in previous-declaration lookup");
7399   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7400   if (!Prev.empty()) {
7401     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7402          Func != FuncEnd; ++Func) {
7403       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7404       if (FD &&
7405           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7406         // Add 1 to the index so that 0 can mean the mismatch didn't
7407         // involve a parameter
7408         unsigned ParamNum =
7409             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7410         NearMatches.push_back(std::make_pair(FD, ParamNum));
7411       }
7412     }
7413   // If the qualified name lookup yielded nothing, try typo correction
7414   } else if ((Correction = SemaRef.CorrectTypo(
7415                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7416                   &ExtraArgs.D.getCXXScopeSpec(),
7417                   llvm::make_unique<DifferentNameValidatorCCC>(
7418                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7419                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7420     // Set up everything for the call to ActOnFunctionDeclarator
7421     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7422                               ExtraArgs.D.getIdentifierLoc());
7423     Previous.clear();
7424     Previous.setLookupName(Correction.getCorrection());
7425     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7426                                     CDeclEnd = Correction.end();
7427          CDecl != CDeclEnd; ++CDecl) {
7428       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7429       if (FD && !FD->hasBody() &&
7430           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7431         Previous.addDecl(FD);
7432       }
7433     }
7434     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7435 
7436     NamedDecl *Result;
7437     // Retry building the function declaration with the new previous
7438     // declarations, and with errors suppressed.
7439     {
7440       // Trap errors.
7441       Sema::SFINAETrap Trap(SemaRef);
7442 
7443       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7444       // pieces need to verify the typo-corrected C++ declaration and hopefully
7445       // eliminate the need for the parameter pack ExtraArgs.
7446       Result = SemaRef.ActOnFunctionDeclarator(
7447           ExtraArgs.S, ExtraArgs.D,
7448           Correction.getCorrectionDecl()->getDeclContext(),
7449           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7450           ExtraArgs.AddToScope);
7451 
7452       if (Trap.hasErrorOccurred())
7453         Result = nullptr;
7454     }
7455 
7456     if (Result) {
7457       // Determine which correction we picked.
7458       Decl *Canonical = Result->getCanonicalDecl();
7459       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7460            I != E; ++I)
7461         if ((*I)->getCanonicalDecl() == Canonical)
7462           Correction.setCorrectionDecl(*I);
7463 
7464       SemaRef.diagnoseTypo(
7465           Correction,
7466           SemaRef.PDiag(IsLocalFriend
7467                           ? diag::err_no_matching_local_friend_suggest
7468                           : diag::err_member_decl_does_not_match_suggest)
7469             << Name << NewDC << IsDefinition);
7470       return Result;
7471     }
7472 
7473     // Pretend the typo correction never occurred
7474     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7475                               ExtraArgs.D.getIdentifierLoc());
7476     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7477     Previous.clear();
7478     Previous.setLookupName(Name);
7479   }
7480 
7481   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7482       << Name << NewDC << IsDefinition << NewFD->getLocation();
7483 
7484   bool NewFDisConst = false;
7485   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7486     NewFDisConst = NewMD->isConst();
7487 
7488   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7489        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7490        NearMatch != NearMatchEnd; ++NearMatch) {
7491     FunctionDecl *FD = NearMatch->first;
7492     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7493     bool FDisConst = MD && MD->isConst();
7494     bool IsMember = MD || !IsLocalFriend;
7495 
7496     // FIXME: These notes are poorly worded for the local friend case.
7497     if (unsigned Idx = NearMatch->second) {
7498       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7499       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7500       if (Loc.isInvalid()) Loc = FD->getLocation();
7501       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7502                                  : diag::note_local_decl_close_param_match)
7503         << Idx << FDParam->getType()
7504         << NewFD->getParamDecl(Idx - 1)->getType();
7505     } else if (FDisConst != NewFDisConst) {
7506       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7507           << NewFDisConst << FD->getSourceRange().getEnd();
7508     } else
7509       SemaRef.Diag(FD->getLocation(),
7510                    IsMember ? diag::note_member_def_close_match
7511                             : diag::note_local_decl_close_match);
7512   }
7513   return nullptr;
7514 }
7515 
7516 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7517   switch (D.getDeclSpec().getStorageClassSpec()) {
7518   default: llvm_unreachable("Unknown storage class!");
7519   case DeclSpec::SCS_auto:
7520   case DeclSpec::SCS_register:
7521   case DeclSpec::SCS_mutable:
7522     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7523                  diag::err_typecheck_sclass_func);
7524     D.getMutableDeclSpec().ClearStorageClassSpecs();
7525     D.setInvalidType();
7526     break;
7527   case DeclSpec::SCS_unspecified: break;
7528   case DeclSpec::SCS_extern:
7529     if (D.getDeclSpec().isExternInLinkageSpec())
7530       return SC_None;
7531     return SC_Extern;
7532   case DeclSpec::SCS_static: {
7533     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7534       // C99 6.7.1p5:
7535       //   The declaration of an identifier for a function that has
7536       //   block scope shall have no explicit storage-class specifier
7537       //   other than extern
7538       // See also (C++ [dcl.stc]p4).
7539       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7540                    diag::err_static_block_func);
7541       break;
7542     } else
7543       return SC_Static;
7544   }
7545   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7546   }
7547 
7548   // No explicit storage class has already been returned
7549   return SC_None;
7550 }
7551 
7552 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7553                                            DeclContext *DC, QualType &R,
7554                                            TypeSourceInfo *TInfo,
7555                                            StorageClass SC,
7556                                            bool &IsVirtualOkay) {
7557   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7558   DeclarationName Name = NameInfo.getName();
7559 
7560   FunctionDecl *NewFD = nullptr;
7561   bool isInline = D.getDeclSpec().isInlineSpecified();
7562 
7563   if (!SemaRef.getLangOpts().CPlusPlus) {
7564     // Determine whether the function was written with a
7565     // prototype. This true when:
7566     //   - there is a prototype in the declarator, or
7567     //   - the type R of the function is some kind of typedef or other non-
7568     //     attributed reference to a type name (which eventually refers to a
7569     //     function type).
7570     bool HasPrototype =
7571       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7572       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7573 
7574     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7575                                  D.getLocStart(), NameInfo, R,
7576                                  TInfo, SC, isInline,
7577                                  HasPrototype, false);
7578     if (D.isInvalidType())
7579       NewFD->setInvalidDecl();
7580 
7581     return NewFD;
7582   }
7583 
7584   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7585   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7586 
7587   // Check that the return type is not an abstract class type.
7588   // For record types, this is done by the AbstractClassUsageDiagnoser once
7589   // the class has been completely parsed.
7590   if (!DC->isRecord() &&
7591       SemaRef.RequireNonAbstractType(
7592           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7593           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7594     D.setInvalidType();
7595 
7596   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7597     // This is a C++ constructor declaration.
7598     assert(DC->isRecord() &&
7599            "Constructors can only be declared in a member context");
7600 
7601     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7602     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7603                                       D.getLocStart(), NameInfo,
7604                                       R, TInfo, isExplicit, isInline,
7605                                       /*isImplicitlyDeclared=*/false,
7606                                       isConstexpr);
7607 
7608   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7609     // This is a C++ destructor declaration.
7610     if (DC->isRecord()) {
7611       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7612       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7613       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7614                                         SemaRef.Context, Record,
7615                                         D.getLocStart(),
7616                                         NameInfo, R, TInfo, isInline,
7617                                         /*isImplicitlyDeclared=*/false);
7618 
7619       // If the class is complete, then we now create the implicit exception
7620       // specification. If the class is incomplete or dependent, we can't do
7621       // it yet.
7622       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7623           Record->getDefinition() && !Record->isBeingDefined() &&
7624           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7625         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7626       }
7627 
7628       IsVirtualOkay = true;
7629       return NewDD;
7630 
7631     } else {
7632       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7633       D.setInvalidType();
7634 
7635       // Create a FunctionDecl to satisfy the function definition parsing
7636       // code path.
7637       return FunctionDecl::Create(SemaRef.Context, DC,
7638                                   D.getLocStart(),
7639                                   D.getIdentifierLoc(), Name, R, TInfo,
7640                                   SC, isInline,
7641                                   /*hasPrototype=*/true, isConstexpr);
7642     }
7643 
7644   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7645     if (!DC->isRecord()) {
7646       SemaRef.Diag(D.getIdentifierLoc(),
7647            diag::err_conv_function_not_member);
7648       return nullptr;
7649     }
7650 
7651     SemaRef.CheckConversionDeclarator(D, R, SC);
7652     IsVirtualOkay = true;
7653     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7654                                      D.getLocStart(), NameInfo,
7655                                      R, TInfo, isInline, isExplicit,
7656                                      isConstexpr, SourceLocation());
7657 
7658   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7659     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7660 
7661     // We don't need to store much extra information for a deduction guide, so
7662     // just model it as a plain FunctionDecl.
7663     auto *FD = FunctionDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7664                                     NameInfo, R, TInfo, SC, isInline,
7665                                     true /*HasPrototype*/, isConstexpr);
7666     if (isExplicit)
7667       FD->setExplicitSpecified();
7668     return FD;
7669   } else if (DC->isRecord()) {
7670     // If the name of the function is the same as the name of the record,
7671     // then this must be an invalid constructor that has a return type.
7672     // (The parser checks for a return type and makes the declarator a
7673     // constructor if it has no return type).
7674     if (Name.getAsIdentifierInfo() &&
7675         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7676       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7677         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7678         << SourceRange(D.getIdentifierLoc());
7679       return nullptr;
7680     }
7681 
7682     // This is a C++ method declaration.
7683     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7684                                                cast<CXXRecordDecl>(DC),
7685                                                D.getLocStart(), NameInfo, R,
7686                                                TInfo, SC, isInline,
7687                                                isConstexpr, SourceLocation());
7688     IsVirtualOkay = !Ret->isStatic();
7689     return Ret;
7690   } else {
7691     bool isFriend =
7692         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7693     if (!isFriend && SemaRef.CurContext->isRecord())
7694       return nullptr;
7695 
7696     // Determine whether the function was written with a
7697     // prototype. This true when:
7698     //   - we're in C++ (where every function has a prototype),
7699     return FunctionDecl::Create(SemaRef.Context, DC,
7700                                 D.getLocStart(),
7701                                 NameInfo, R, TInfo, SC, isInline,
7702                                 true/*HasPrototype*/, isConstexpr);
7703   }
7704 }
7705 
7706 enum OpenCLParamType {
7707   ValidKernelParam,
7708   PtrPtrKernelParam,
7709   PtrKernelParam,
7710   InvalidAddrSpacePtrKernelParam,
7711   InvalidKernelParam,
7712   RecordKernelParam
7713 };
7714 
7715 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7716   if (PT->isPointerType()) {
7717     QualType PointeeType = PT->getPointeeType();
7718     if (PointeeType->isPointerType())
7719       return PtrPtrKernelParam;
7720     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7721         PointeeType.getAddressSpace() == 0)
7722       return InvalidAddrSpacePtrKernelParam;
7723     return PtrKernelParam;
7724   }
7725 
7726   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7727   // be used as builtin types.
7728 
7729   if (PT->isImageType())
7730     return PtrKernelParam;
7731 
7732   if (PT->isBooleanType())
7733     return InvalidKernelParam;
7734 
7735   if (PT->isEventT())
7736     return InvalidKernelParam;
7737 
7738   // OpenCL extension spec v1.2 s9.5:
7739   // This extension adds support for half scalar and vector types as built-in
7740   // types that can be used for arithmetic operations, conversions etc.
7741   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7742     return InvalidKernelParam;
7743 
7744   if (PT->isRecordType())
7745     return RecordKernelParam;
7746 
7747   return ValidKernelParam;
7748 }
7749 
7750 static void checkIsValidOpenCLKernelParameter(
7751   Sema &S,
7752   Declarator &D,
7753   ParmVarDecl *Param,
7754   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7755   QualType PT = Param->getType();
7756 
7757   // Cache the valid types we encounter to avoid rechecking structs that are
7758   // used again
7759   if (ValidTypes.count(PT.getTypePtr()))
7760     return;
7761 
7762   switch (getOpenCLKernelParameterType(S, PT)) {
7763   case PtrPtrKernelParam:
7764     // OpenCL v1.2 s6.9.a:
7765     // A kernel function argument cannot be declared as a
7766     // pointer to a pointer type.
7767     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7768     D.setInvalidType();
7769     return;
7770 
7771   case InvalidAddrSpacePtrKernelParam:
7772     // OpenCL v1.0 s6.5:
7773     // __kernel function arguments declared to be a pointer of a type can point
7774     // to one of the following address spaces only : __global, __local or
7775     // __constant.
7776     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7777     D.setInvalidType();
7778     return;
7779 
7780     // OpenCL v1.2 s6.9.k:
7781     // Arguments to kernel functions in a program cannot be declared with the
7782     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7783     // uintptr_t or a struct and/or union that contain fields declared to be
7784     // one of these built-in scalar types.
7785 
7786   case InvalidKernelParam:
7787     // OpenCL v1.2 s6.8 n:
7788     // A kernel function argument cannot be declared
7789     // of event_t type.
7790     // Do not diagnose half type since it is diagnosed as invalid argument
7791     // type for any function elsewhere.
7792     if (!PT->isHalfType())
7793       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7794     D.setInvalidType();
7795     return;
7796 
7797   case PtrKernelParam:
7798   case ValidKernelParam:
7799     ValidTypes.insert(PT.getTypePtr());
7800     return;
7801 
7802   case RecordKernelParam:
7803     break;
7804   }
7805 
7806   // Track nested structs we will inspect
7807   SmallVector<const Decl *, 4> VisitStack;
7808 
7809   // Track where we are in the nested structs. Items will migrate from
7810   // VisitStack to HistoryStack as we do the DFS for bad field.
7811   SmallVector<const FieldDecl *, 4> HistoryStack;
7812   HistoryStack.push_back(nullptr);
7813 
7814   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7815   VisitStack.push_back(PD);
7816 
7817   assert(VisitStack.back() && "First decl null?");
7818 
7819   do {
7820     const Decl *Next = VisitStack.pop_back_val();
7821     if (!Next) {
7822       assert(!HistoryStack.empty());
7823       // Found a marker, we have gone up a level
7824       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7825         ValidTypes.insert(Hist->getType().getTypePtr());
7826 
7827       continue;
7828     }
7829 
7830     // Adds everything except the original parameter declaration (which is not a
7831     // field itself) to the history stack.
7832     const RecordDecl *RD;
7833     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7834       HistoryStack.push_back(Field);
7835       RD = Field->getType()->castAs<RecordType>()->getDecl();
7836     } else {
7837       RD = cast<RecordDecl>(Next);
7838     }
7839 
7840     // Add a null marker so we know when we've gone back up a level
7841     VisitStack.push_back(nullptr);
7842 
7843     for (const auto *FD : RD->fields()) {
7844       QualType QT = FD->getType();
7845 
7846       if (ValidTypes.count(QT.getTypePtr()))
7847         continue;
7848 
7849       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7850       if (ParamType == ValidKernelParam)
7851         continue;
7852 
7853       if (ParamType == RecordKernelParam) {
7854         VisitStack.push_back(FD);
7855         continue;
7856       }
7857 
7858       // OpenCL v1.2 s6.9.p:
7859       // Arguments to kernel functions that are declared to be a struct or union
7860       // do not allow OpenCL objects to be passed as elements of the struct or
7861       // union.
7862       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7863           ParamType == InvalidAddrSpacePtrKernelParam) {
7864         S.Diag(Param->getLocation(),
7865                diag::err_record_with_pointers_kernel_param)
7866           << PT->isUnionType()
7867           << PT;
7868       } else {
7869         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7870       }
7871 
7872       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7873         << PD->getDeclName();
7874 
7875       // We have an error, now let's go back up through history and show where
7876       // the offending field came from
7877       for (ArrayRef<const FieldDecl *>::const_iterator
7878                I = HistoryStack.begin() + 1,
7879                E = HistoryStack.end();
7880            I != E; ++I) {
7881         const FieldDecl *OuterField = *I;
7882         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7883           << OuterField->getType();
7884       }
7885 
7886       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7887         << QT->isPointerType()
7888         << QT;
7889       D.setInvalidType();
7890       return;
7891     }
7892   } while (!VisitStack.empty());
7893 }
7894 
7895 /// Find the DeclContext in which a tag is implicitly declared if we see an
7896 /// elaborated type specifier in the specified context, and lookup finds
7897 /// nothing.
7898 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7899   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7900     DC = DC->getParent();
7901   return DC;
7902 }
7903 
7904 /// Find the Scope in which a tag is implicitly declared if we see an
7905 /// elaborated type specifier in the specified context, and lookup finds
7906 /// nothing.
7907 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7908   while (S->isClassScope() ||
7909          (LangOpts.CPlusPlus &&
7910           S->isFunctionPrototypeScope()) ||
7911          ((S->getFlags() & Scope::DeclScope) == 0) ||
7912          (S->getEntity() && S->getEntity()->isTransparentContext()))
7913     S = S->getParent();
7914   return S;
7915 }
7916 
7917 NamedDecl*
7918 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7919                               TypeSourceInfo *TInfo, LookupResult &Previous,
7920                               MultiTemplateParamsArg TemplateParamLists,
7921                               bool &AddToScope) {
7922   QualType R = TInfo->getType();
7923 
7924   assert(R.getTypePtr()->isFunctionType());
7925 
7926   // TODO: consider using NameInfo for diagnostic.
7927   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7928   DeclarationName Name = NameInfo.getName();
7929   StorageClass SC = getFunctionStorageClass(*this, D);
7930 
7931   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7932     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7933          diag::err_invalid_thread)
7934       << DeclSpec::getSpecifierName(TSCS);
7935 
7936   if (D.isFirstDeclarationOfMember())
7937     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7938                            D.getIdentifierLoc());
7939 
7940   bool isFriend = false;
7941   FunctionTemplateDecl *FunctionTemplate = nullptr;
7942   bool isMemberSpecialization = false;
7943   bool isFunctionTemplateSpecialization = false;
7944 
7945   bool isDependentClassScopeExplicitSpecialization = false;
7946   bool HasExplicitTemplateArgs = false;
7947   TemplateArgumentListInfo TemplateArgs;
7948 
7949   bool isVirtualOkay = false;
7950 
7951   DeclContext *OriginalDC = DC;
7952   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7953 
7954   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7955                                               isVirtualOkay);
7956   if (!NewFD) return nullptr;
7957 
7958   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7959     NewFD->setTopLevelDeclInObjCContainer();
7960 
7961   // Set the lexical context. If this is a function-scope declaration, or has a
7962   // C++ scope specifier, or is the object of a friend declaration, the lexical
7963   // context will be different from the semantic context.
7964   NewFD->setLexicalDeclContext(CurContext);
7965 
7966   if (IsLocalExternDecl)
7967     NewFD->setLocalExternDecl();
7968 
7969   if (getLangOpts().CPlusPlus) {
7970     bool isInline = D.getDeclSpec().isInlineSpecified();
7971     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7972     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7973     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7974     bool isConcept = D.getDeclSpec().isConceptSpecified();
7975     isFriend = D.getDeclSpec().isFriendSpecified();
7976     if (isFriend && !isInline && D.isFunctionDefinition()) {
7977       // C++ [class.friend]p5
7978       //   A function can be defined in a friend declaration of a
7979       //   class . . . . Such a function is implicitly inline.
7980       NewFD->setImplicitlyInline();
7981     }
7982 
7983     // If this is a method defined in an __interface, and is not a constructor
7984     // or an overloaded operator, then set the pure flag (isVirtual will already
7985     // return true).
7986     if (const CXXRecordDecl *Parent =
7987           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7988       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7989         NewFD->setPure(true);
7990 
7991       // C++ [class.union]p2
7992       //   A union can have member functions, but not virtual functions.
7993       if (isVirtual && Parent->isUnion())
7994         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7995     }
7996 
7997     SetNestedNameSpecifier(NewFD, D);
7998     isMemberSpecialization = false;
7999     isFunctionTemplateSpecialization = false;
8000     if (D.isInvalidType())
8001       NewFD->setInvalidDecl();
8002 
8003     // Match up the template parameter lists with the scope specifier, then
8004     // determine whether we have a template or a template specialization.
8005     bool Invalid = false;
8006     if (TemplateParameterList *TemplateParams =
8007             MatchTemplateParametersToScopeSpecifier(
8008                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8009                 D.getCXXScopeSpec(),
8010                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8011                     ? D.getName().TemplateId
8012                     : nullptr,
8013                 TemplateParamLists, isFriend, isMemberSpecialization,
8014                 Invalid)) {
8015       if (TemplateParams->size() > 0) {
8016         // This is a function template
8017 
8018         // Check that we can declare a template here.
8019         if (CheckTemplateDeclScope(S, TemplateParams))
8020           NewFD->setInvalidDecl();
8021 
8022         // A destructor cannot be a template.
8023         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8024           Diag(NewFD->getLocation(), diag::err_destructor_template);
8025           NewFD->setInvalidDecl();
8026         }
8027 
8028         // If we're adding a template to a dependent context, we may need to
8029         // rebuilding some of the types used within the template parameter list,
8030         // now that we know what the current instantiation is.
8031         if (DC->isDependentContext()) {
8032           ContextRAII SavedContext(*this, DC);
8033           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8034             Invalid = true;
8035         }
8036 
8037         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8038                                                         NewFD->getLocation(),
8039                                                         Name, TemplateParams,
8040                                                         NewFD);
8041         FunctionTemplate->setLexicalDeclContext(CurContext);
8042         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8043 
8044         // For source fidelity, store the other template param lists.
8045         if (TemplateParamLists.size() > 1) {
8046           NewFD->setTemplateParameterListsInfo(Context,
8047                                                TemplateParamLists.drop_back(1));
8048         }
8049       } else {
8050         // This is a function template specialization.
8051         isFunctionTemplateSpecialization = true;
8052         // For source fidelity, store all the template param lists.
8053         if (TemplateParamLists.size() > 0)
8054           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8055 
8056         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8057         if (isFriend) {
8058           // We want to remove the "template<>", found here.
8059           SourceRange RemoveRange = TemplateParams->getSourceRange();
8060 
8061           // If we remove the template<> and the name is not a
8062           // template-id, we're actually silently creating a problem:
8063           // the friend declaration will refer to an untemplated decl,
8064           // and clearly the user wants a template specialization.  So
8065           // we need to insert '<>' after the name.
8066           SourceLocation InsertLoc;
8067           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8068             InsertLoc = D.getName().getSourceRange().getEnd();
8069             InsertLoc = getLocForEndOfToken(InsertLoc);
8070           }
8071 
8072           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8073             << Name << RemoveRange
8074             << FixItHint::CreateRemoval(RemoveRange)
8075             << FixItHint::CreateInsertion(InsertLoc, "<>");
8076         }
8077       }
8078     }
8079     else {
8080       // All template param lists were matched against the scope specifier:
8081       // this is NOT (an explicit specialization of) a template.
8082       if (TemplateParamLists.size() > 0)
8083         // For source fidelity, store all the template param lists.
8084         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8085     }
8086 
8087     if (Invalid) {
8088       NewFD->setInvalidDecl();
8089       if (FunctionTemplate)
8090         FunctionTemplate->setInvalidDecl();
8091     }
8092 
8093     // C++ [dcl.fct.spec]p5:
8094     //   The virtual specifier shall only be used in declarations of
8095     //   nonstatic class member functions that appear within a
8096     //   member-specification of a class declaration; see 10.3.
8097     //
8098     if (isVirtual && !NewFD->isInvalidDecl()) {
8099       if (!isVirtualOkay) {
8100         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8101              diag::err_virtual_non_function);
8102       } else if (!CurContext->isRecord()) {
8103         // 'virtual' was specified outside of the class.
8104         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8105              diag::err_virtual_out_of_class)
8106           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8107       } else if (NewFD->getDescribedFunctionTemplate()) {
8108         // C++ [temp.mem]p3:
8109         //  A member function template shall not be virtual.
8110         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8111              diag::err_virtual_member_function_template)
8112           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8113       } else {
8114         // Okay: Add virtual to the method.
8115         NewFD->setVirtualAsWritten(true);
8116       }
8117 
8118       if (getLangOpts().CPlusPlus14 &&
8119           NewFD->getReturnType()->isUndeducedType())
8120         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8121     }
8122 
8123     if (getLangOpts().CPlusPlus14 &&
8124         (NewFD->isDependentContext() ||
8125          (isFriend && CurContext->isDependentContext())) &&
8126         NewFD->getReturnType()->isUndeducedType()) {
8127       // If the function template is referenced directly (for instance, as a
8128       // member of the current instantiation), pretend it has a dependent type.
8129       // This is not really justified by the standard, but is the only sane
8130       // thing to do.
8131       // FIXME: For a friend function, we have not marked the function as being
8132       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8133       const FunctionProtoType *FPT =
8134           NewFD->getType()->castAs<FunctionProtoType>();
8135       QualType Result =
8136           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8137       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8138                                              FPT->getExtProtoInfo()));
8139     }
8140 
8141     // C++ [dcl.fct.spec]p3:
8142     //  The inline specifier shall not appear on a block scope function
8143     //  declaration.
8144     if (isInline && !NewFD->isInvalidDecl()) {
8145       if (CurContext->isFunctionOrMethod()) {
8146         // 'inline' is not allowed on block scope function declaration.
8147         Diag(D.getDeclSpec().getInlineSpecLoc(),
8148              diag::err_inline_declaration_block_scope) << Name
8149           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8150       }
8151     }
8152 
8153     // C++ [dcl.fct.spec]p6:
8154     //  The explicit specifier shall be used only in the declaration of a
8155     //  constructor or conversion function within its class definition;
8156     //  see 12.3.1 and 12.3.2.
8157     if (isExplicit && !NewFD->isInvalidDecl() && !NewFD->isDeductionGuide()) {
8158       if (!CurContext->isRecord()) {
8159         // 'explicit' was specified outside of the class.
8160         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8161              diag::err_explicit_out_of_class)
8162           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8163       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8164                  !isa<CXXConversionDecl>(NewFD)) {
8165         // 'explicit' was specified on a function that wasn't a constructor
8166         // or conversion function.
8167         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8168              diag::err_explicit_non_ctor_or_conv_function)
8169           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8170       }
8171     }
8172 
8173     if (isConstexpr) {
8174       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8175       // are implicitly inline.
8176       NewFD->setImplicitlyInline();
8177 
8178       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8179       // be either constructors or to return a literal type. Therefore,
8180       // destructors cannot be declared constexpr.
8181       if (isa<CXXDestructorDecl>(NewFD))
8182         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8183     }
8184 
8185     if (isConcept) {
8186       // This is a function concept.
8187       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8188         FTD->setConcept();
8189 
8190       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8191       // applied only to the definition of a function template [...]
8192       if (!D.isFunctionDefinition()) {
8193         Diag(D.getDeclSpec().getConceptSpecLoc(),
8194              diag::err_function_concept_not_defined);
8195         NewFD->setInvalidDecl();
8196       }
8197 
8198       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8199       // have no exception-specification and is treated as if it were specified
8200       // with noexcept(true) (15.4). [...]
8201       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8202         if (FPT->hasExceptionSpec()) {
8203           SourceRange Range;
8204           if (D.isFunctionDeclarator())
8205             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8206           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8207               << FixItHint::CreateRemoval(Range);
8208           NewFD->setInvalidDecl();
8209         } else {
8210           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8211         }
8212 
8213         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8214         // following restrictions:
8215         // - The declared return type shall have the type bool.
8216         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8217           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8218           NewFD->setInvalidDecl();
8219         }
8220 
8221         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8222         // following restrictions:
8223         // - The declaration's parameter list shall be equivalent to an empty
8224         //   parameter list.
8225         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8226           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8227       }
8228 
8229       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8230       // implicity defined to be a constexpr declaration (implicitly inline)
8231       NewFD->setImplicitlyInline();
8232 
8233       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8234       // be declared with the thread_local, inline, friend, or constexpr
8235       // specifiers, [...]
8236       if (isInline) {
8237         Diag(D.getDeclSpec().getInlineSpecLoc(),
8238              diag::err_concept_decl_invalid_specifiers)
8239             << 1 << 1;
8240         NewFD->setInvalidDecl(true);
8241       }
8242 
8243       if (isFriend) {
8244         Diag(D.getDeclSpec().getFriendSpecLoc(),
8245              diag::err_concept_decl_invalid_specifiers)
8246             << 1 << 2;
8247         NewFD->setInvalidDecl(true);
8248       }
8249 
8250       if (isConstexpr) {
8251         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8252              diag::err_concept_decl_invalid_specifiers)
8253             << 1 << 3;
8254         NewFD->setInvalidDecl(true);
8255       }
8256 
8257       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8258       // applied only to the definition of a function template or variable
8259       // template, declared in namespace scope.
8260       if (isFunctionTemplateSpecialization) {
8261         Diag(D.getDeclSpec().getConceptSpecLoc(),
8262              diag::err_concept_specified_specialization) << 1;
8263         NewFD->setInvalidDecl(true);
8264         return NewFD;
8265       }
8266     }
8267 
8268     // If __module_private__ was specified, mark the function accordingly.
8269     if (D.getDeclSpec().isModulePrivateSpecified()) {
8270       if (isFunctionTemplateSpecialization) {
8271         SourceLocation ModulePrivateLoc
8272           = D.getDeclSpec().getModulePrivateSpecLoc();
8273         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8274           << 0
8275           << FixItHint::CreateRemoval(ModulePrivateLoc);
8276       } else {
8277         NewFD->setModulePrivate();
8278         if (FunctionTemplate)
8279           FunctionTemplate->setModulePrivate();
8280       }
8281     }
8282 
8283     if (isFriend) {
8284       if (FunctionTemplate) {
8285         FunctionTemplate->setObjectOfFriendDecl();
8286         FunctionTemplate->setAccess(AS_public);
8287       }
8288       NewFD->setObjectOfFriendDecl();
8289       NewFD->setAccess(AS_public);
8290     }
8291 
8292     // If a function is defined as defaulted or deleted, mark it as such now.
8293     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8294     // definition kind to FDK_Definition.
8295     switch (D.getFunctionDefinitionKind()) {
8296       case FDK_Declaration:
8297       case FDK_Definition:
8298         break;
8299 
8300       case FDK_Defaulted:
8301         NewFD->setDefaulted();
8302         break;
8303 
8304       case FDK_Deleted:
8305         NewFD->setDeletedAsWritten();
8306         break;
8307     }
8308 
8309     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8310         D.isFunctionDefinition()) {
8311       // C++ [class.mfct]p2:
8312       //   A member function may be defined (8.4) in its class definition, in
8313       //   which case it is an inline member function (7.1.2)
8314       NewFD->setImplicitlyInline();
8315     }
8316 
8317     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8318         !CurContext->isRecord()) {
8319       // C++ [class.static]p1:
8320       //   A data or function member of a class may be declared static
8321       //   in a class definition, in which case it is a static member of
8322       //   the class.
8323 
8324       // Complain about the 'static' specifier if it's on an out-of-line
8325       // member function definition.
8326       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8327            diag::err_static_out_of_line)
8328         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8329     }
8330 
8331     // C++11 [except.spec]p15:
8332     //   A deallocation function with no exception-specification is treated
8333     //   as if it were specified with noexcept(true).
8334     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8335     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8336          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8337         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8338       NewFD->setType(Context.getFunctionType(
8339           FPT->getReturnType(), FPT->getParamTypes(),
8340           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8341   }
8342 
8343   // Filter out previous declarations that don't match the scope.
8344   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8345                        D.getCXXScopeSpec().isNotEmpty() ||
8346                        isMemberSpecialization ||
8347                        isFunctionTemplateSpecialization);
8348 
8349   // Handle GNU asm-label extension (encoded as an attribute).
8350   if (Expr *E = (Expr*) D.getAsmLabel()) {
8351     // The parser guarantees this is a string.
8352     StringLiteral *SE = cast<StringLiteral>(E);
8353     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8354                                                 SE->getString(), 0));
8355   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8356     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8357       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8358     if (I != ExtnameUndeclaredIdentifiers.end()) {
8359       if (isDeclExternC(NewFD)) {
8360         NewFD->addAttr(I->second);
8361         ExtnameUndeclaredIdentifiers.erase(I);
8362       } else
8363         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8364             << /*Variable*/0 << NewFD;
8365     }
8366   }
8367 
8368   // Copy the parameter declarations from the declarator D to the function
8369   // declaration NewFD, if they are available.  First scavenge them into Params.
8370   SmallVector<ParmVarDecl*, 16> Params;
8371   unsigned FTIIdx;
8372   if (D.isFunctionDeclarator(FTIIdx)) {
8373     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8374 
8375     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8376     // function that takes no arguments, not a function that takes a
8377     // single void argument.
8378     // We let through "const void" here because Sema::GetTypeForDeclarator
8379     // already checks for that case.
8380     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8381       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8382         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8383         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8384         Param->setDeclContext(NewFD);
8385         Params.push_back(Param);
8386 
8387         if (Param->isInvalidDecl())
8388           NewFD->setInvalidDecl();
8389       }
8390     }
8391 
8392     if (!getLangOpts().CPlusPlus) {
8393       // In C, find all the tag declarations from the prototype and move them
8394       // into the function DeclContext. Remove them from the surrounding tag
8395       // injection context of the function, which is typically but not always
8396       // the TU.
8397       DeclContext *PrototypeTagContext =
8398           getTagInjectionContext(NewFD->getLexicalDeclContext());
8399       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8400         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8401 
8402         // We don't want to reparent enumerators. Look at their parent enum
8403         // instead.
8404         if (!TD) {
8405           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8406             TD = cast<EnumDecl>(ECD->getDeclContext());
8407         }
8408         if (!TD)
8409           continue;
8410         DeclContext *TagDC = TD->getLexicalDeclContext();
8411         if (!TagDC->containsDecl(TD))
8412           continue;
8413         TagDC->removeDecl(TD);
8414         TD->setDeclContext(NewFD);
8415         NewFD->addDecl(TD);
8416 
8417         // Preserve the lexical DeclContext if it is not the surrounding tag
8418         // injection context of the FD. In this example, the semantic context of
8419         // E will be f and the lexical context will be S, while both the
8420         // semantic and lexical contexts of S will be f:
8421         //   void f(struct S { enum E { a } f; } s);
8422         if (TagDC != PrototypeTagContext)
8423           TD->setLexicalDeclContext(TagDC);
8424       }
8425     }
8426   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8427     // When we're declaring a function with a typedef, typeof, etc as in the
8428     // following example, we'll need to synthesize (unnamed)
8429     // parameters for use in the declaration.
8430     //
8431     // @code
8432     // typedef void fn(int);
8433     // fn f;
8434     // @endcode
8435 
8436     // Synthesize a parameter for each argument type.
8437     for (const auto &AI : FT->param_types()) {
8438       ParmVarDecl *Param =
8439           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8440       Param->setScopeInfo(0, Params.size());
8441       Params.push_back(Param);
8442     }
8443   } else {
8444     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8445            "Should not need args for typedef of non-prototype fn");
8446   }
8447 
8448   // Finally, we know we have the right number of parameters, install them.
8449   NewFD->setParams(Params);
8450 
8451   if (D.getDeclSpec().isNoreturnSpecified())
8452     NewFD->addAttr(
8453         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8454                                        Context, 0));
8455 
8456   // Functions returning a variably modified type violate C99 6.7.5.2p2
8457   // because all functions have linkage.
8458   if (!NewFD->isInvalidDecl() &&
8459       NewFD->getReturnType()->isVariablyModifiedType()) {
8460     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8461     NewFD->setInvalidDecl();
8462   }
8463 
8464   // Apply an implicit SectionAttr if #pragma code_seg is active.
8465   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8466       !NewFD->hasAttr<SectionAttr>()) {
8467     NewFD->addAttr(
8468         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8469                                     CodeSegStack.CurrentValue->getString(),
8470                                     CodeSegStack.CurrentPragmaLocation));
8471     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8472                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8473                          ASTContext::PSF_Read,
8474                      NewFD))
8475       NewFD->dropAttr<SectionAttr>();
8476   }
8477 
8478   // Handle attributes.
8479   ProcessDeclAttributes(S, NewFD, D);
8480 
8481   if (getLangOpts().OpenCL) {
8482     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8483     // type declaration will generate a compilation error.
8484     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8485     if (AddressSpace == LangAS::opencl_local ||
8486         AddressSpace == LangAS::opencl_global ||
8487         AddressSpace == LangAS::opencl_constant) {
8488       Diag(NewFD->getLocation(),
8489            diag::err_opencl_return_value_with_address_space);
8490       NewFD->setInvalidDecl();
8491     }
8492   }
8493 
8494   if (!getLangOpts().CPlusPlus) {
8495     // Perform semantic checking on the function declaration.
8496     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8497       CheckMain(NewFD, D.getDeclSpec());
8498 
8499     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8500       CheckMSVCRTEntryPoint(NewFD);
8501 
8502     if (!NewFD->isInvalidDecl())
8503       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8504                                                   isMemberSpecialization));
8505     else if (!Previous.empty())
8506       // Recover gracefully from an invalid redeclaration.
8507       D.setRedeclaration(true);
8508     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8509             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8510            "previous declaration set still overloaded");
8511 
8512     // Diagnose no-prototype function declarations with calling conventions that
8513     // don't support variadic calls. Only do this in C and do it after merging
8514     // possibly prototyped redeclarations.
8515     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8516     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8517       CallingConv CC = FT->getExtInfo().getCC();
8518       if (!supportsVariadicCall(CC)) {
8519         // Windows system headers sometimes accidentally use stdcall without
8520         // (void) parameters, so we relax this to a warning.
8521         int DiagID =
8522             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8523         Diag(NewFD->getLocation(), DiagID)
8524             << FunctionType::getNameForCallConv(CC);
8525       }
8526     }
8527   } else {
8528     // C++11 [replacement.functions]p3:
8529     //  The program's definitions shall not be specified as inline.
8530     //
8531     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8532     //
8533     // Suppress the diagnostic if the function is __attribute__((used)), since
8534     // that forces an external definition to be emitted.
8535     if (D.getDeclSpec().isInlineSpecified() &&
8536         NewFD->isReplaceableGlobalAllocationFunction() &&
8537         !NewFD->hasAttr<UsedAttr>())
8538       Diag(D.getDeclSpec().getInlineSpecLoc(),
8539            diag::ext_operator_new_delete_declared_inline)
8540         << NewFD->getDeclName();
8541 
8542     // If the declarator is a template-id, translate the parser's template
8543     // argument list into our AST format.
8544     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8545       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8546       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8547       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8548       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8549                                          TemplateId->NumArgs);
8550       translateTemplateArguments(TemplateArgsPtr,
8551                                  TemplateArgs);
8552 
8553       HasExplicitTemplateArgs = true;
8554 
8555       if (NewFD->isInvalidDecl()) {
8556         HasExplicitTemplateArgs = false;
8557       } else if (FunctionTemplate) {
8558         // Function template with explicit template arguments.
8559         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8560           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8561 
8562         HasExplicitTemplateArgs = false;
8563       } else {
8564         assert((isFunctionTemplateSpecialization ||
8565                 D.getDeclSpec().isFriendSpecified()) &&
8566                "should have a 'template<>' for this decl");
8567         // "friend void foo<>(int);" is an implicit specialization decl.
8568         isFunctionTemplateSpecialization = true;
8569       }
8570     } else if (isFriend && isFunctionTemplateSpecialization) {
8571       // This combination is only possible in a recovery case;  the user
8572       // wrote something like:
8573       //   template <> friend void foo(int);
8574       // which we're recovering from as if the user had written:
8575       //   friend void foo<>(int);
8576       // Go ahead and fake up a template id.
8577       HasExplicitTemplateArgs = true;
8578       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8579       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8580     }
8581 
8582     // We do not add HD attributes to specializations here because
8583     // they may have different constexpr-ness compared to their
8584     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8585     // may end up with different effective targets. Instead, a
8586     // specialization inherits its target attributes from its template
8587     // in the CheckFunctionTemplateSpecialization() call below.
8588     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8589       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8590 
8591     // If it's a friend (and only if it's a friend), it's possible
8592     // that either the specialized function type or the specialized
8593     // template is dependent, and therefore matching will fail.  In
8594     // this case, don't check the specialization yet.
8595     bool InstantiationDependent = false;
8596     if (isFunctionTemplateSpecialization && isFriend &&
8597         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8598          TemplateSpecializationType::anyDependentTemplateArguments(
8599             TemplateArgs,
8600             InstantiationDependent))) {
8601       assert(HasExplicitTemplateArgs &&
8602              "friend function specialization without template args");
8603       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8604                                                        Previous))
8605         NewFD->setInvalidDecl();
8606     } else if (isFunctionTemplateSpecialization) {
8607       if (CurContext->isDependentContext() && CurContext->isRecord()
8608           && !isFriend) {
8609         isDependentClassScopeExplicitSpecialization = true;
8610         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8611           diag::ext_function_specialization_in_class :
8612           diag::err_function_specialization_in_class)
8613           << NewFD->getDeclName();
8614       } else if (CheckFunctionTemplateSpecialization(NewFD,
8615                                   (HasExplicitTemplateArgs ? &TemplateArgs
8616                                                            : nullptr),
8617                                                      Previous))
8618         NewFD->setInvalidDecl();
8619 
8620       // C++ [dcl.stc]p1:
8621       //   A storage-class-specifier shall not be specified in an explicit
8622       //   specialization (14.7.3)
8623       FunctionTemplateSpecializationInfo *Info =
8624           NewFD->getTemplateSpecializationInfo();
8625       if (Info && SC != SC_None) {
8626         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8627           Diag(NewFD->getLocation(),
8628                diag::err_explicit_specialization_inconsistent_storage_class)
8629             << SC
8630             << FixItHint::CreateRemoval(
8631                                       D.getDeclSpec().getStorageClassSpecLoc());
8632 
8633         else
8634           Diag(NewFD->getLocation(),
8635                diag::ext_explicit_specialization_storage_class)
8636             << FixItHint::CreateRemoval(
8637                                       D.getDeclSpec().getStorageClassSpecLoc());
8638       }
8639     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8640       if (CheckMemberSpecialization(NewFD, Previous))
8641           NewFD->setInvalidDecl();
8642     }
8643 
8644     // Perform semantic checking on the function declaration.
8645     if (!isDependentClassScopeExplicitSpecialization) {
8646       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8647         CheckMain(NewFD, D.getDeclSpec());
8648 
8649       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8650         CheckMSVCRTEntryPoint(NewFD);
8651 
8652       if (!NewFD->isInvalidDecl())
8653         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8654                                                     isMemberSpecialization));
8655       else if (!Previous.empty())
8656         // Recover gracefully from an invalid redeclaration.
8657         D.setRedeclaration(true);
8658     }
8659 
8660     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8661             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8662            "previous declaration set still overloaded");
8663 
8664     NamedDecl *PrincipalDecl = (FunctionTemplate
8665                                 ? cast<NamedDecl>(FunctionTemplate)
8666                                 : NewFD);
8667 
8668     if (isFriend && NewFD->getPreviousDecl()) {
8669       AccessSpecifier Access = AS_public;
8670       if (!NewFD->isInvalidDecl())
8671         Access = NewFD->getPreviousDecl()->getAccess();
8672 
8673       NewFD->setAccess(Access);
8674       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8675     }
8676 
8677     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8678         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8679       PrincipalDecl->setNonMemberOperator();
8680 
8681     // If we have a function template, check the template parameter
8682     // list. This will check and merge default template arguments.
8683     if (FunctionTemplate) {
8684       FunctionTemplateDecl *PrevTemplate =
8685                                      FunctionTemplate->getPreviousDecl();
8686       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8687                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8688                                     : nullptr,
8689                             D.getDeclSpec().isFriendSpecified()
8690                               ? (D.isFunctionDefinition()
8691                                    ? TPC_FriendFunctionTemplateDefinition
8692                                    : TPC_FriendFunctionTemplate)
8693                               : (D.getCXXScopeSpec().isSet() &&
8694                                  DC && DC->isRecord() &&
8695                                  DC->isDependentContext())
8696                                   ? TPC_ClassTemplateMember
8697                                   : TPC_FunctionTemplate);
8698     }
8699 
8700     if (NewFD->isInvalidDecl()) {
8701       // Ignore all the rest of this.
8702     } else if (!D.isRedeclaration()) {
8703       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8704                                        AddToScope };
8705       // Fake up an access specifier if it's supposed to be a class member.
8706       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8707         NewFD->setAccess(AS_public);
8708 
8709       // Qualified decls generally require a previous declaration.
8710       if (D.getCXXScopeSpec().isSet()) {
8711         // ...with the major exception of templated-scope or
8712         // dependent-scope friend declarations.
8713 
8714         // TODO: we currently also suppress this check in dependent
8715         // contexts because (1) the parameter depth will be off when
8716         // matching friend templates and (2) we might actually be
8717         // selecting a friend based on a dependent factor.  But there
8718         // are situations where these conditions don't apply and we
8719         // can actually do this check immediately.
8720         if (isFriend &&
8721             (TemplateParamLists.size() ||
8722              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8723              CurContext->isDependentContext())) {
8724           // ignore these
8725         } else {
8726           // The user tried to provide an out-of-line definition for a
8727           // function that is a member of a class or namespace, but there
8728           // was no such member function declared (C++ [class.mfct]p2,
8729           // C++ [namespace.memdef]p2). For example:
8730           //
8731           // class X {
8732           //   void f() const;
8733           // };
8734           //
8735           // void X::f() { } // ill-formed
8736           //
8737           // Complain about this problem, and attempt to suggest close
8738           // matches (e.g., those that differ only in cv-qualifiers and
8739           // whether the parameter types are references).
8740 
8741           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8742                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8743             AddToScope = ExtraArgs.AddToScope;
8744             return Result;
8745           }
8746         }
8747 
8748         // Unqualified local friend declarations are required to resolve
8749         // to something.
8750       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8751         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8752                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8753           AddToScope = ExtraArgs.AddToScope;
8754           return Result;
8755         }
8756       }
8757     } else if (!D.isFunctionDefinition() &&
8758                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8759                !isFriend && !isFunctionTemplateSpecialization &&
8760                !isMemberSpecialization) {
8761       // An out-of-line member function declaration must also be a
8762       // definition (C++ [class.mfct]p2).
8763       // Note that this is not the case for explicit specializations of
8764       // function templates or member functions of class templates, per
8765       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8766       // extension for compatibility with old SWIG code which likes to
8767       // generate them.
8768       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8769         << D.getCXXScopeSpec().getRange();
8770     }
8771   }
8772 
8773   ProcessPragmaWeak(S, NewFD);
8774   checkAttributesAfterMerging(*this, *NewFD);
8775 
8776   AddKnownFunctionAttributes(NewFD);
8777 
8778   if (NewFD->hasAttr<OverloadableAttr>() &&
8779       !NewFD->getType()->getAs<FunctionProtoType>()) {
8780     Diag(NewFD->getLocation(),
8781          diag::err_attribute_overloadable_no_prototype)
8782       << NewFD;
8783 
8784     // Turn this into a variadic function with no parameters.
8785     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8786     FunctionProtoType::ExtProtoInfo EPI(
8787         Context.getDefaultCallingConvention(true, false));
8788     EPI.Variadic = true;
8789     EPI.ExtInfo = FT->getExtInfo();
8790 
8791     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8792     NewFD->setType(R);
8793   }
8794 
8795   // If there's a #pragma GCC visibility in scope, and this isn't a class
8796   // member, set the visibility of this function.
8797   if (!DC->isRecord() && NewFD->isExternallyVisible())
8798     AddPushedVisibilityAttribute(NewFD);
8799 
8800   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8801   // marking the function.
8802   AddCFAuditedAttribute(NewFD);
8803 
8804   // If this is a function definition, check if we have to apply optnone due to
8805   // a pragma.
8806   if(D.isFunctionDefinition())
8807     AddRangeBasedOptnone(NewFD);
8808 
8809   // If this is the first declaration of an extern C variable, update
8810   // the map of such variables.
8811   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8812       isIncompleteDeclExternC(*this, NewFD))
8813     RegisterLocallyScopedExternCDecl(NewFD, S);
8814 
8815   // Set this FunctionDecl's range up to the right paren.
8816   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8817 
8818   if (D.isRedeclaration() && !Previous.empty()) {
8819     checkDLLAttributeRedeclaration(
8820         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8821         isMemberSpecialization || isFunctionTemplateSpecialization,
8822         D.isFunctionDefinition());
8823   }
8824 
8825   if (getLangOpts().CUDA) {
8826     IdentifierInfo *II = NewFD->getIdentifier();
8827     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8828         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8829       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8830         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8831 
8832       Context.setcudaConfigureCallDecl(NewFD);
8833     }
8834 
8835     // Variadic functions, other than a *declaration* of printf, are not allowed
8836     // in device-side CUDA code, unless someone passed
8837     // -fcuda-allow-variadic-functions.
8838     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8839         (NewFD->hasAttr<CUDADeviceAttr>() ||
8840          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8841         !(II && II->isStr("printf") && NewFD->isExternC() &&
8842           !D.isFunctionDefinition())) {
8843       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8844     }
8845   }
8846 
8847   if (getLangOpts().CPlusPlus) {
8848     if (FunctionTemplate) {
8849       if (NewFD->isInvalidDecl())
8850         FunctionTemplate->setInvalidDecl();
8851       return FunctionTemplate;
8852     }
8853   }
8854 
8855   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8856     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8857     if ((getLangOpts().OpenCLVersion >= 120)
8858         && (SC == SC_Static)) {
8859       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8860       D.setInvalidType();
8861     }
8862 
8863     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8864     if (!NewFD->getReturnType()->isVoidType()) {
8865       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8866       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8867           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8868                                 : FixItHint());
8869       D.setInvalidType();
8870     }
8871 
8872     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8873     for (auto Param : NewFD->parameters())
8874       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8875   }
8876   for (const ParmVarDecl *Param : NewFD->parameters()) {
8877     QualType PT = Param->getType();
8878 
8879     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8880     // types.
8881     if (getLangOpts().OpenCLVersion >= 200) {
8882       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8883         QualType ElemTy = PipeTy->getElementType();
8884           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8885             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8886             D.setInvalidType();
8887           }
8888       }
8889     }
8890   }
8891 
8892   MarkUnusedFileScopedDecl(NewFD);
8893 
8894   // Here we have an function template explicit specialization at class scope.
8895   // The actually specialization will be postponed to template instatiation
8896   // time via the ClassScopeFunctionSpecializationDecl node.
8897   if (isDependentClassScopeExplicitSpecialization) {
8898     ClassScopeFunctionSpecializationDecl *NewSpec =
8899                          ClassScopeFunctionSpecializationDecl::Create(
8900                                 Context, CurContext, SourceLocation(),
8901                                 cast<CXXMethodDecl>(NewFD),
8902                                 HasExplicitTemplateArgs, TemplateArgs);
8903     CurContext->addDecl(NewSpec);
8904     AddToScope = false;
8905   }
8906 
8907   return NewFD;
8908 }
8909 
8910 /// \brief Checks if the new declaration declared in dependent context must be
8911 /// put in the same redeclaration chain as the specified declaration.
8912 ///
8913 /// \param D Declaration that is checked.
8914 /// \param PrevDecl Previous declaration found with proper lookup method for the
8915 ///                 same declaration name.
8916 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8917 ///          belongs to.
8918 ///
8919 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8920   // Any declarations should be put into redeclaration chains except for
8921   // friend declaration in a dependent context that names a function in
8922   // namespace scope.
8923   //
8924   // This allows to compile code like:
8925   //
8926   //       void func();
8927   //       template<typename T> class C1 { friend void func() { } };
8928   //       template<typename T> class C2 { friend void func() { } };
8929   //
8930   // This code snippet is a valid code unless both templates are instantiated.
8931   return !(D->getLexicalDeclContext()->isDependentContext() &&
8932            D->getDeclContext()->isFileContext() &&
8933            D->getFriendObjectKind() != Decl::FOK_None);
8934 }
8935 
8936 /// \brief Perform semantic checking of a new function declaration.
8937 ///
8938 /// Performs semantic analysis of the new function declaration
8939 /// NewFD. This routine performs all semantic checking that does not
8940 /// require the actual declarator involved in the declaration, and is
8941 /// used both for the declaration of functions as they are parsed
8942 /// (called via ActOnDeclarator) and for the declaration of functions
8943 /// that have been instantiated via C++ template instantiation (called
8944 /// via InstantiateDecl).
8945 ///
8946 /// \param IsMemberSpecialization whether this new function declaration is
8947 /// a member specialization (that replaces any definition provided by the
8948 /// previous declaration).
8949 ///
8950 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8951 ///
8952 /// \returns true if the function declaration is a redeclaration.
8953 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8954                                     LookupResult &Previous,
8955                                     bool IsMemberSpecialization) {
8956   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8957          "Variably modified return types are not handled here");
8958 
8959   // Determine whether the type of this function should be merged with
8960   // a previous visible declaration. This never happens for functions in C++,
8961   // and always happens in C if the previous declaration was visible.
8962   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8963                                !Previous.isShadowed();
8964 
8965   bool Redeclaration = false;
8966   NamedDecl *OldDecl = nullptr;
8967 
8968   // Merge or overload the declaration with an existing declaration of
8969   // the same name, if appropriate.
8970   if (!Previous.empty()) {
8971     // Determine whether NewFD is an overload of PrevDecl or
8972     // a declaration that requires merging. If it's an overload,
8973     // there's no more work to do here; we'll just add the new
8974     // function to the scope.
8975     if (!AllowOverloadingOfFunction(Previous, Context)) {
8976       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8977       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8978         Redeclaration = true;
8979         OldDecl = Candidate;
8980       }
8981     } else {
8982       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8983                             /*NewIsUsingDecl*/ false)) {
8984       case Ovl_Match:
8985         Redeclaration = true;
8986         break;
8987 
8988       case Ovl_NonFunction:
8989         Redeclaration = true;
8990         break;
8991 
8992       case Ovl_Overload:
8993         Redeclaration = false;
8994         break;
8995       }
8996 
8997       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8998         // If a function name is overloadable in C, then every function
8999         // with that name must be marked "overloadable".
9000         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9001           << Redeclaration << NewFD;
9002         NamedDecl *OverloadedDecl = nullptr;
9003         if (Redeclaration)
9004           OverloadedDecl = OldDecl;
9005         else if (!Previous.empty())
9006           OverloadedDecl = Previous.getRepresentativeDecl();
9007         if (OverloadedDecl)
9008           Diag(OverloadedDecl->getLocation(),
9009                diag::note_attribute_overloadable_prev_overload);
9010         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9011       }
9012     }
9013   }
9014 
9015   // Check for a previous extern "C" declaration with this name.
9016   if (!Redeclaration &&
9017       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9018     if (!Previous.empty()) {
9019       // This is an extern "C" declaration with the same name as a previous
9020       // declaration, and thus redeclares that entity...
9021       Redeclaration = true;
9022       OldDecl = Previous.getFoundDecl();
9023       MergeTypeWithPrevious = false;
9024 
9025       // ... except in the presence of __attribute__((overloadable)).
9026       if (OldDecl->hasAttr<OverloadableAttr>()) {
9027         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9028           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9029             << Redeclaration << NewFD;
9030           Diag(Previous.getFoundDecl()->getLocation(),
9031                diag::note_attribute_overloadable_prev_overload);
9032           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9033         }
9034         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9035           Redeclaration = false;
9036           OldDecl = nullptr;
9037         }
9038       }
9039     }
9040   }
9041 
9042   // C++11 [dcl.constexpr]p8:
9043   //   A constexpr specifier for a non-static member function that is not
9044   //   a constructor declares that member function to be const.
9045   //
9046   // This needs to be delayed until we know whether this is an out-of-line
9047   // definition of a static member function.
9048   //
9049   // This rule is not present in C++1y, so we produce a backwards
9050   // compatibility warning whenever it happens in C++11.
9051   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9052   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9053       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9054       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9055     CXXMethodDecl *OldMD = nullptr;
9056     if (OldDecl)
9057       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9058     if (!OldMD || !OldMD->isStatic()) {
9059       const FunctionProtoType *FPT =
9060         MD->getType()->castAs<FunctionProtoType>();
9061       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9062       EPI.TypeQuals |= Qualifiers::Const;
9063       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9064                                           FPT->getParamTypes(), EPI));
9065 
9066       // Warn that we did this, if we're not performing template instantiation.
9067       // In that case, we'll have warned already when the template was defined.
9068       if (ActiveTemplateInstantiations.empty()) {
9069         SourceLocation AddConstLoc;
9070         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9071                 .IgnoreParens().getAs<FunctionTypeLoc>())
9072           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9073 
9074         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9075           << FixItHint::CreateInsertion(AddConstLoc, " const");
9076       }
9077     }
9078   }
9079 
9080   if (Redeclaration) {
9081     // NewFD and OldDecl represent declarations that need to be
9082     // merged.
9083     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9084       NewFD->setInvalidDecl();
9085       return Redeclaration;
9086     }
9087 
9088     Previous.clear();
9089     Previous.addDecl(OldDecl);
9090 
9091     if (FunctionTemplateDecl *OldTemplateDecl
9092                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9093       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9094       FunctionTemplateDecl *NewTemplateDecl
9095         = NewFD->getDescribedFunctionTemplate();
9096       assert(NewTemplateDecl && "Template/non-template mismatch");
9097       if (CXXMethodDecl *Method
9098             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9099         Method->setAccess(OldTemplateDecl->getAccess());
9100         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9101       }
9102 
9103       // If this is an explicit specialization of a member that is a function
9104       // template, mark it as a member specialization.
9105       if (IsMemberSpecialization &&
9106           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9107         NewTemplateDecl->setMemberSpecialization();
9108         assert(OldTemplateDecl->isMemberSpecialization());
9109         // Explicit specializations of a member template do not inherit deleted
9110         // status from the parent member template that they are specializing.
9111         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9112           FunctionDecl *const OldTemplatedDecl =
9113               OldTemplateDecl->getTemplatedDecl();
9114           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9115           OldTemplatedDecl->setDeletedAsWritten(false);
9116         }
9117       }
9118 
9119     } else {
9120       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9121         // This needs to happen first so that 'inline' propagates.
9122         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9123         if (isa<CXXMethodDecl>(NewFD))
9124           NewFD->setAccess(OldDecl->getAccess());
9125       }
9126     }
9127   }
9128 
9129   // Semantic checking for this function declaration (in isolation).
9130 
9131   if (getLangOpts().CPlusPlus) {
9132     // C++-specific checks.
9133     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9134       CheckConstructor(Constructor);
9135     } else if (CXXDestructorDecl *Destructor =
9136                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9137       CXXRecordDecl *Record = Destructor->getParent();
9138       QualType ClassType = Context.getTypeDeclType(Record);
9139 
9140       // FIXME: Shouldn't we be able to perform this check even when the class
9141       // type is dependent? Both gcc and edg can handle that.
9142       if (!ClassType->isDependentType()) {
9143         DeclarationName Name
9144           = Context.DeclarationNames.getCXXDestructorName(
9145                                         Context.getCanonicalType(ClassType));
9146         if (NewFD->getDeclName() != Name) {
9147           Diag(NewFD->getLocation(), diag::err_destructor_name);
9148           NewFD->setInvalidDecl();
9149           return Redeclaration;
9150         }
9151       }
9152     } else if (CXXConversionDecl *Conversion
9153                = dyn_cast<CXXConversionDecl>(NewFD)) {
9154       ActOnConversionDeclarator(Conversion);
9155     } else if (NewFD->isDeductionGuide() &&
9156                NewFD->getTemplateSpecializationKind() ==
9157                    TSK_ExplicitSpecialization) {
9158       // A deduction guide is not on the list of entities that can be
9159       // explicitly specialized.
9160       Diag(NewFD->getLocStart(), diag::err_deduction_guide_specialized)
9161         << /*explicit specialization*/ 1;
9162     }
9163 
9164     // Find any virtual functions that this function overrides.
9165     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9166       if (!Method->isFunctionTemplateSpecialization() &&
9167           !Method->getDescribedFunctionTemplate() &&
9168           Method->isCanonicalDecl()) {
9169         if (AddOverriddenMethods(Method->getParent(), Method)) {
9170           // If the function was marked as "static", we have a problem.
9171           if (NewFD->getStorageClass() == SC_Static) {
9172             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9173           }
9174         }
9175       }
9176 
9177       if (Method->isStatic())
9178         checkThisInStaticMemberFunctionType(Method);
9179     }
9180 
9181     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9182     if (NewFD->isOverloadedOperator() &&
9183         CheckOverloadedOperatorDeclaration(NewFD)) {
9184       NewFD->setInvalidDecl();
9185       return Redeclaration;
9186     }
9187 
9188     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9189     if (NewFD->getLiteralIdentifier() &&
9190         CheckLiteralOperatorDeclaration(NewFD)) {
9191       NewFD->setInvalidDecl();
9192       return Redeclaration;
9193     }
9194 
9195     // In C++, check default arguments now that we have merged decls. Unless
9196     // the lexical context is the class, because in this case this is done
9197     // during delayed parsing anyway.
9198     if (!CurContext->isRecord())
9199       CheckCXXDefaultArguments(NewFD);
9200 
9201     // If this function declares a builtin function, check the type of this
9202     // declaration against the expected type for the builtin.
9203     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9204       ASTContext::GetBuiltinTypeError Error;
9205       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9206       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9207       // If the type of the builtin differs only in its exception
9208       // specification, that's OK.
9209       // FIXME: If the types do differ in this way, it would be better to
9210       // retain the 'noexcept' form of the type.
9211       if (!T.isNull() &&
9212           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9213                                                             NewFD->getType()))
9214         // The type of this function differs from the type of the builtin,
9215         // so forget about the builtin entirely.
9216         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9217     }
9218 
9219     // If this function is declared as being extern "C", then check to see if
9220     // the function returns a UDT (class, struct, or union type) that is not C
9221     // compatible, and if it does, warn the user.
9222     // But, issue any diagnostic on the first declaration only.
9223     if (Previous.empty() && NewFD->isExternC()) {
9224       QualType R = NewFD->getReturnType();
9225       if (R->isIncompleteType() && !R->isVoidType())
9226         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9227             << NewFD << R;
9228       else if (!R.isPODType(Context) && !R->isVoidType() &&
9229                !R->isObjCObjectPointerType())
9230         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9231     }
9232 
9233     // C++1z [dcl.fct]p6:
9234     //   [...] whether the function has a non-throwing exception-specification
9235     //   [is] part of the function type
9236     //
9237     // This results in an ABI break between C++14 and C++17 for functions whose
9238     // declared type includes an exception-specification in a parameter or
9239     // return type. (Exception specifications on the function itself are OK in
9240     // most cases, and exception specifications are not permitted in most other
9241     // contexts where they could make it into a mangling.)
9242     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9243       auto HasNoexcept = [&](QualType T) -> bool {
9244         // Strip off declarator chunks that could be between us and a function
9245         // type. We don't need to look far, exception specifications are very
9246         // restricted prior to C++17.
9247         if (auto *RT = T->getAs<ReferenceType>())
9248           T = RT->getPointeeType();
9249         else if (T->isAnyPointerType())
9250           T = T->getPointeeType();
9251         else if (auto *MPT = T->getAs<MemberPointerType>())
9252           T = MPT->getPointeeType();
9253         if (auto *FPT = T->getAs<FunctionProtoType>())
9254           if (FPT->isNothrow(Context))
9255             return true;
9256         return false;
9257       };
9258 
9259       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9260       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9261       for (QualType T : FPT->param_types())
9262         AnyNoexcept |= HasNoexcept(T);
9263       if (AnyNoexcept)
9264         Diag(NewFD->getLocation(),
9265              diag::warn_cxx1z_compat_exception_spec_in_signature)
9266             << NewFD;
9267     }
9268 
9269     if (!Redeclaration && LangOpts.CUDA)
9270       checkCUDATargetOverload(NewFD, Previous);
9271   }
9272   return Redeclaration;
9273 }
9274 
9275 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9276   // C++11 [basic.start.main]p3:
9277   //   A program that [...] declares main to be inline, static or
9278   //   constexpr is ill-formed.
9279   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9280   //   appear in a declaration of main.
9281   // static main is not an error under C99, but we should warn about it.
9282   // We accept _Noreturn main as an extension.
9283   if (FD->getStorageClass() == SC_Static)
9284     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9285          ? diag::err_static_main : diag::warn_static_main)
9286       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9287   if (FD->isInlineSpecified())
9288     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9289       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9290   if (DS.isNoreturnSpecified()) {
9291     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9292     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9293     Diag(NoreturnLoc, diag::ext_noreturn_main);
9294     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9295       << FixItHint::CreateRemoval(NoreturnRange);
9296   }
9297   if (FD->isConstexpr()) {
9298     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9299       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9300     FD->setConstexpr(false);
9301   }
9302 
9303   if (getLangOpts().OpenCL) {
9304     Diag(FD->getLocation(), diag::err_opencl_no_main)
9305         << FD->hasAttr<OpenCLKernelAttr>();
9306     FD->setInvalidDecl();
9307     return;
9308   }
9309 
9310   QualType T = FD->getType();
9311   assert(T->isFunctionType() && "function decl is not of function type");
9312   const FunctionType* FT = T->castAs<FunctionType>();
9313 
9314   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9315     // In C with GNU extensions we allow main() to have non-integer return
9316     // type, but we should warn about the extension, and we disable the
9317     // implicit-return-zero rule.
9318 
9319     // GCC in C mode accepts qualified 'int'.
9320     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9321       FD->setHasImplicitReturnZero(true);
9322     else {
9323       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9324       SourceRange RTRange = FD->getReturnTypeSourceRange();
9325       if (RTRange.isValid())
9326         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9327             << FixItHint::CreateReplacement(RTRange, "int");
9328     }
9329   } else {
9330     // In C and C++, main magically returns 0 if you fall off the end;
9331     // set the flag which tells us that.
9332     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9333 
9334     // All the standards say that main() should return 'int'.
9335     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9336       FD->setHasImplicitReturnZero(true);
9337     else {
9338       // Otherwise, this is just a flat-out error.
9339       SourceRange RTRange = FD->getReturnTypeSourceRange();
9340       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9341           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9342                                 : FixItHint());
9343       FD->setInvalidDecl(true);
9344     }
9345   }
9346 
9347   // Treat protoless main() as nullary.
9348   if (isa<FunctionNoProtoType>(FT)) return;
9349 
9350   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9351   unsigned nparams = FTP->getNumParams();
9352   assert(FD->getNumParams() == nparams);
9353 
9354   bool HasExtraParameters = (nparams > 3);
9355 
9356   if (FTP->isVariadic()) {
9357     Diag(FD->getLocation(), diag::ext_variadic_main);
9358     // FIXME: if we had information about the location of the ellipsis, we
9359     // could add a FixIt hint to remove it as a parameter.
9360   }
9361 
9362   // Darwin passes an undocumented fourth argument of type char**.  If
9363   // other platforms start sprouting these, the logic below will start
9364   // getting shifty.
9365   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9366     HasExtraParameters = false;
9367 
9368   if (HasExtraParameters) {
9369     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9370     FD->setInvalidDecl(true);
9371     nparams = 3;
9372   }
9373 
9374   // FIXME: a lot of the following diagnostics would be improved
9375   // if we had some location information about types.
9376 
9377   QualType CharPP =
9378     Context.getPointerType(Context.getPointerType(Context.CharTy));
9379   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9380 
9381   for (unsigned i = 0; i < nparams; ++i) {
9382     QualType AT = FTP->getParamType(i);
9383 
9384     bool mismatch = true;
9385 
9386     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9387       mismatch = false;
9388     else if (Expected[i] == CharPP) {
9389       // As an extension, the following forms are okay:
9390       //   char const **
9391       //   char const * const *
9392       //   char * const *
9393 
9394       QualifierCollector qs;
9395       const PointerType* PT;
9396       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9397           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9398           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9399                               Context.CharTy)) {
9400         qs.removeConst();
9401         mismatch = !qs.empty();
9402       }
9403     }
9404 
9405     if (mismatch) {
9406       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9407       // TODO: suggest replacing given type with expected type
9408       FD->setInvalidDecl(true);
9409     }
9410   }
9411 
9412   if (nparams == 1 && !FD->isInvalidDecl()) {
9413     Diag(FD->getLocation(), diag::warn_main_one_arg);
9414   }
9415 
9416   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9417     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9418     FD->setInvalidDecl();
9419   }
9420 }
9421 
9422 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9423   QualType T = FD->getType();
9424   assert(T->isFunctionType() && "function decl is not of function type");
9425   const FunctionType *FT = T->castAs<FunctionType>();
9426 
9427   // Set an implicit return of 'zero' if the function can return some integral,
9428   // enumeration, pointer or nullptr type.
9429   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9430       FT->getReturnType()->isAnyPointerType() ||
9431       FT->getReturnType()->isNullPtrType())
9432     // DllMain is exempt because a return value of zero means it failed.
9433     if (FD->getName() != "DllMain")
9434       FD->setHasImplicitReturnZero(true);
9435 
9436   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9437     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9438     FD->setInvalidDecl();
9439   }
9440 }
9441 
9442 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9443   // FIXME: Need strict checking.  In C89, we need to check for
9444   // any assignment, increment, decrement, function-calls, or
9445   // commas outside of a sizeof.  In C99, it's the same list,
9446   // except that the aforementioned are allowed in unevaluated
9447   // expressions.  Everything else falls under the
9448   // "may accept other forms of constant expressions" exception.
9449   // (We never end up here for C++, so the constant expression
9450   // rules there don't matter.)
9451   const Expr *Culprit;
9452   if (Init->isConstantInitializer(Context, false, &Culprit))
9453     return false;
9454   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9455     << Culprit->getSourceRange();
9456   return true;
9457 }
9458 
9459 namespace {
9460   // Visits an initialization expression to see if OrigDecl is evaluated in
9461   // its own initialization and throws a warning if it does.
9462   class SelfReferenceChecker
9463       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9464     Sema &S;
9465     Decl *OrigDecl;
9466     bool isRecordType;
9467     bool isPODType;
9468     bool isReferenceType;
9469 
9470     bool isInitList;
9471     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9472 
9473   public:
9474     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9475 
9476     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9477                                                     S(S), OrigDecl(OrigDecl) {
9478       isPODType = false;
9479       isRecordType = false;
9480       isReferenceType = false;
9481       isInitList = false;
9482       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9483         isPODType = VD->getType().isPODType(S.Context);
9484         isRecordType = VD->getType()->isRecordType();
9485         isReferenceType = VD->getType()->isReferenceType();
9486       }
9487     }
9488 
9489     // For most expressions, just call the visitor.  For initializer lists,
9490     // track the index of the field being initialized since fields are
9491     // initialized in order allowing use of previously initialized fields.
9492     void CheckExpr(Expr *E) {
9493       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9494       if (!InitList) {
9495         Visit(E);
9496         return;
9497       }
9498 
9499       // Track and increment the index here.
9500       isInitList = true;
9501       InitFieldIndex.push_back(0);
9502       for (auto Child : InitList->children()) {
9503         CheckExpr(cast<Expr>(Child));
9504         ++InitFieldIndex.back();
9505       }
9506       InitFieldIndex.pop_back();
9507     }
9508 
9509     // Returns true if MemberExpr is checked and no futher checking is needed.
9510     // Returns false if additional checking is required.
9511     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9512       llvm::SmallVector<FieldDecl*, 4> Fields;
9513       Expr *Base = E;
9514       bool ReferenceField = false;
9515 
9516       // Get the field memebers used.
9517       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9518         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9519         if (!FD)
9520           return false;
9521         Fields.push_back(FD);
9522         if (FD->getType()->isReferenceType())
9523           ReferenceField = true;
9524         Base = ME->getBase()->IgnoreParenImpCasts();
9525       }
9526 
9527       // Keep checking only if the base Decl is the same.
9528       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9529       if (!DRE || DRE->getDecl() != OrigDecl)
9530         return false;
9531 
9532       // A reference field can be bound to an unininitialized field.
9533       if (CheckReference && !ReferenceField)
9534         return true;
9535 
9536       // Convert FieldDecls to their index number.
9537       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9538       for (const FieldDecl *I : llvm::reverse(Fields))
9539         UsedFieldIndex.push_back(I->getFieldIndex());
9540 
9541       // See if a warning is needed by checking the first difference in index
9542       // numbers.  If field being used has index less than the field being
9543       // initialized, then the use is safe.
9544       for (auto UsedIter = UsedFieldIndex.begin(),
9545                 UsedEnd = UsedFieldIndex.end(),
9546                 OrigIter = InitFieldIndex.begin(),
9547                 OrigEnd = InitFieldIndex.end();
9548            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9549         if (*UsedIter < *OrigIter)
9550           return true;
9551         if (*UsedIter > *OrigIter)
9552           break;
9553       }
9554 
9555       // TODO: Add a different warning which will print the field names.
9556       HandleDeclRefExpr(DRE);
9557       return true;
9558     }
9559 
9560     // For most expressions, the cast is directly above the DeclRefExpr.
9561     // For conditional operators, the cast can be outside the conditional
9562     // operator if both expressions are DeclRefExpr's.
9563     void HandleValue(Expr *E) {
9564       E = E->IgnoreParens();
9565       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9566         HandleDeclRefExpr(DRE);
9567         return;
9568       }
9569 
9570       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9571         Visit(CO->getCond());
9572         HandleValue(CO->getTrueExpr());
9573         HandleValue(CO->getFalseExpr());
9574         return;
9575       }
9576 
9577       if (BinaryConditionalOperator *BCO =
9578               dyn_cast<BinaryConditionalOperator>(E)) {
9579         Visit(BCO->getCond());
9580         HandleValue(BCO->getFalseExpr());
9581         return;
9582       }
9583 
9584       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9585         HandleValue(OVE->getSourceExpr());
9586         return;
9587       }
9588 
9589       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9590         if (BO->getOpcode() == BO_Comma) {
9591           Visit(BO->getLHS());
9592           HandleValue(BO->getRHS());
9593           return;
9594         }
9595       }
9596 
9597       if (isa<MemberExpr>(E)) {
9598         if (isInitList) {
9599           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9600                                       false /*CheckReference*/))
9601             return;
9602         }
9603 
9604         Expr *Base = E->IgnoreParenImpCasts();
9605         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9606           // Check for static member variables and don't warn on them.
9607           if (!isa<FieldDecl>(ME->getMemberDecl()))
9608             return;
9609           Base = ME->getBase()->IgnoreParenImpCasts();
9610         }
9611         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9612           HandleDeclRefExpr(DRE);
9613         return;
9614       }
9615 
9616       Visit(E);
9617     }
9618 
9619     // Reference types not handled in HandleValue are handled here since all
9620     // uses of references are bad, not just r-value uses.
9621     void VisitDeclRefExpr(DeclRefExpr *E) {
9622       if (isReferenceType)
9623         HandleDeclRefExpr(E);
9624     }
9625 
9626     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9627       if (E->getCastKind() == CK_LValueToRValue) {
9628         HandleValue(E->getSubExpr());
9629         return;
9630       }
9631 
9632       Inherited::VisitImplicitCastExpr(E);
9633     }
9634 
9635     void VisitMemberExpr(MemberExpr *E) {
9636       if (isInitList) {
9637         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9638           return;
9639       }
9640 
9641       // Don't warn on arrays since they can be treated as pointers.
9642       if (E->getType()->canDecayToPointerType()) return;
9643 
9644       // Warn when a non-static method call is followed by non-static member
9645       // field accesses, which is followed by a DeclRefExpr.
9646       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9647       bool Warn = (MD && !MD->isStatic());
9648       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9649       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9650         if (!isa<FieldDecl>(ME->getMemberDecl()))
9651           Warn = false;
9652         Base = ME->getBase()->IgnoreParenImpCasts();
9653       }
9654 
9655       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9656         if (Warn)
9657           HandleDeclRefExpr(DRE);
9658         return;
9659       }
9660 
9661       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9662       // Visit that expression.
9663       Visit(Base);
9664     }
9665 
9666     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9667       Expr *Callee = E->getCallee();
9668 
9669       if (isa<UnresolvedLookupExpr>(Callee))
9670         return Inherited::VisitCXXOperatorCallExpr(E);
9671 
9672       Visit(Callee);
9673       for (auto Arg: E->arguments())
9674         HandleValue(Arg->IgnoreParenImpCasts());
9675     }
9676 
9677     void VisitUnaryOperator(UnaryOperator *E) {
9678       // For POD record types, addresses of its own members are well-defined.
9679       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9680           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9681         if (!isPODType)
9682           HandleValue(E->getSubExpr());
9683         return;
9684       }
9685 
9686       if (E->isIncrementDecrementOp()) {
9687         HandleValue(E->getSubExpr());
9688         return;
9689       }
9690 
9691       Inherited::VisitUnaryOperator(E);
9692     }
9693 
9694     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9695 
9696     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9697       if (E->getConstructor()->isCopyConstructor()) {
9698         Expr *ArgExpr = E->getArg(0);
9699         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9700           if (ILE->getNumInits() == 1)
9701             ArgExpr = ILE->getInit(0);
9702         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9703           if (ICE->getCastKind() == CK_NoOp)
9704             ArgExpr = ICE->getSubExpr();
9705         HandleValue(ArgExpr);
9706         return;
9707       }
9708       Inherited::VisitCXXConstructExpr(E);
9709     }
9710 
9711     void VisitCallExpr(CallExpr *E) {
9712       // Treat std::move as a use.
9713       if (E->getNumArgs() == 1) {
9714         if (FunctionDecl *FD = E->getDirectCallee()) {
9715           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9716               FD->getIdentifier()->isStr("move")) {
9717             HandleValue(E->getArg(0));
9718             return;
9719           }
9720         }
9721       }
9722 
9723       Inherited::VisitCallExpr(E);
9724     }
9725 
9726     void VisitBinaryOperator(BinaryOperator *E) {
9727       if (E->isCompoundAssignmentOp()) {
9728         HandleValue(E->getLHS());
9729         Visit(E->getRHS());
9730         return;
9731       }
9732 
9733       Inherited::VisitBinaryOperator(E);
9734     }
9735 
9736     // A custom visitor for BinaryConditionalOperator is needed because the
9737     // regular visitor would check the condition and true expression separately
9738     // but both point to the same place giving duplicate diagnostics.
9739     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9740       Visit(E->getCond());
9741       Visit(E->getFalseExpr());
9742     }
9743 
9744     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9745       Decl* ReferenceDecl = DRE->getDecl();
9746       if (OrigDecl != ReferenceDecl) return;
9747       unsigned diag;
9748       if (isReferenceType) {
9749         diag = diag::warn_uninit_self_reference_in_reference_init;
9750       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9751         diag = diag::warn_static_self_reference_in_init;
9752       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9753                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9754                  DRE->getDecl()->getType()->isRecordType()) {
9755         diag = diag::warn_uninit_self_reference_in_init;
9756       } else {
9757         // Local variables will be handled by the CFG analysis.
9758         return;
9759       }
9760 
9761       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9762                             S.PDiag(diag)
9763                               << DRE->getNameInfo().getName()
9764                               << OrigDecl->getLocation()
9765                               << DRE->getSourceRange());
9766     }
9767   };
9768 
9769   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9770   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9771                                  bool DirectInit) {
9772     // Parameters arguments are occassionially constructed with itself,
9773     // for instance, in recursive functions.  Skip them.
9774     if (isa<ParmVarDecl>(OrigDecl))
9775       return;
9776 
9777     E = E->IgnoreParens();
9778 
9779     // Skip checking T a = a where T is not a record or reference type.
9780     // Doing so is a way to silence uninitialized warnings.
9781     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9782       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9783         if (ICE->getCastKind() == CK_LValueToRValue)
9784           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9785             if (DRE->getDecl() == OrigDecl)
9786               return;
9787 
9788     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9789   }
9790 } // end anonymous namespace
9791 
9792 namespace {
9793   // Simple wrapper to add the name of a variable or (if no variable is
9794   // available) a DeclarationName into a diagnostic.
9795   struct VarDeclOrName {
9796     VarDecl *VDecl;
9797     DeclarationName Name;
9798 
9799     friend const Sema::SemaDiagnosticBuilder &
9800     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9801       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9802     }
9803   };
9804 } // end anonymous namespace
9805 
9806 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9807                                             DeclarationName Name, QualType Type,
9808                                             TypeSourceInfo *TSI,
9809                                             SourceRange Range, bool DirectInit,
9810                                             Expr *Init) {
9811   bool IsInitCapture = !VDecl;
9812   assert((!VDecl || !VDecl->isInitCapture()) &&
9813          "init captures are expected to be deduced prior to initialization");
9814 
9815   VarDeclOrName VN{VDecl, Name};
9816 
9817   DeducedType *Deduced = Type->getContainedDeducedType();
9818   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9819 
9820   // C++11 [dcl.spec.auto]p3
9821   if (!Init) {
9822     assert(VDecl && "no init for init capture deduction?");
9823     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9824       << VDecl->getDeclName() << Type;
9825     return QualType();
9826   }
9827 
9828   ArrayRef<Expr*> DeduceInits = Init;
9829   if (DirectInit) {
9830     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9831       DeduceInits = PL->exprs();
9832   }
9833 
9834   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9835     assert(VDecl && "non-auto type for init capture deduction?");
9836     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9837     InitializationKind Kind = InitializationKind::CreateForInit(
9838         VDecl->getLocation(), DirectInit, Init);
9839     // FIXME: Initialization should not be taking a mutable list of inits.
9840     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9841     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9842                                                        InitsCopy);
9843   }
9844 
9845   if (DirectInit) {
9846     if (auto *IL = dyn_cast<InitListExpr>(Init))
9847       DeduceInits = IL->inits();
9848   }
9849 
9850   // Deduction only works if we have exactly one source expression.
9851   if (DeduceInits.empty()) {
9852     // It isn't possible to write this directly, but it is possible to
9853     // end up in this situation with "auto x(some_pack...);"
9854     Diag(Init->getLocStart(), IsInitCapture
9855                                   ? diag::err_init_capture_no_expression
9856                                   : diag::err_auto_var_init_no_expression)
9857         << VN << Type << Range;
9858     return QualType();
9859   }
9860 
9861   if (DeduceInits.size() > 1) {
9862     Diag(DeduceInits[1]->getLocStart(),
9863          IsInitCapture ? diag::err_init_capture_multiple_expressions
9864                        : diag::err_auto_var_init_multiple_expressions)
9865         << VN << Type << Range;
9866     return QualType();
9867   }
9868 
9869   Expr *DeduceInit = DeduceInits[0];
9870   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9871     Diag(Init->getLocStart(), IsInitCapture
9872                                   ? diag::err_init_capture_paren_braces
9873                                   : diag::err_auto_var_init_paren_braces)
9874         << isa<InitListExpr>(Init) << VN << Type << Range;
9875     return QualType();
9876   }
9877 
9878   // Expressions default to 'id' when we're in a debugger.
9879   bool DefaultedAnyToId = false;
9880   if (getLangOpts().DebuggerCastResultToId &&
9881       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9882     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9883     if (Result.isInvalid()) {
9884       return QualType();
9885     }
9886     Init = Result.get();
9887     DefaultedAnyToId = true;
9888   }
9889 
9890   // C++ [dcl.decomp]p1:
9891   //   If the assignment-expression [...] has array type A and no ref-qualifier
9892   //   is present, e has type cv A
9893   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9894       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9895       DeduceInit->getType()->isConstantArrayType())
9896     return Context.getQualifiedType(DeduceInit->getType(),
9897                                     Type.getQualifiers());
9898 
9899   QualType DeducedType;
9900   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9901     if (!IsInitCapture)
9902       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9903     else if (isa<InitListExpr>(Init))
9904       Diag(Range.getBegin(),
9905            diag::err_init_capture_deduction_failure_from_init_list)
9906           << VN
9907           << (DeduceInit->getType().isNull() ? TSI->getType()
9908                                              : DeduceInit->getType())
9909           << DeduceInit->getSourceRange();
9910     else
9911       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9912           << VN << TSI->getType()
9913           << (DeduceInit->getType().isNull() ? TSI->getType()
9914                                              : DeduceInit->getType())
9915           << DeduceInit->getSourceRange();
9916   }
9917 
9918   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9919   // 'id' instead of a specific object type prevents most of our usual
9920   // checks.
9921   // We only want to warn outside of template instantiations, though:
9922   // inside a template, the 'id' could have come from a parameter.
9923   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9924       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9925     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9926     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9927   }
9928 
9929   return DeducedType;
9930 }
9931 
9932 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9933                                          Expr *Init) {
9934   QualType DeducedType = deduceVarTypeFromInitializer(
9935       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9936       VDecl->getSourceRange(), DirectInit, Init);
9937   if (DeducedType.isNull()) {
9938     VDecl->setInvalidDecl();
9939     return true;
9940   }
9941 
9942   VDecl->setType(DeducedType);
9943   assert(VDecl->isLinkageValid());
9944 
9945   // In ARC, infer lifetime.
9946   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9947     VDecl->setInvalidDecl();
9948 
9949   // If this is a redeclaration, check that the type we just deduced matches
9950   // the previously declared type.
9951   if (VarDecl *Old = VDecl->getPreviousDecl()) {
9952     // We never need to merge the type, because we cannot form an incomplete
9953     // array of auto, nor deduce such a type.
9954     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9955   }
9956 
9957   // Check the deduced type is valid for a variable declaration.
9958   CheckVariableDeclarationType(VDecl);
9959   return VDecl->isInvalidDecl();
9960 }
9961 
9962 /// AddInitializerToDecl - Adds the initializer Init to the
9963 /// declaration dcl. If DirectInit is true, this is C++ direct
9964 /// initialization rather than copy initialization.
9965 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
9966   // If there is no declaration, there was an error parsing it.  Just ignore
9967   // the initializer.
9968   if (!RealDecl || RealDecl->isInvalidDecl()) {
9969     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9970     return;
9971   }
9972 
9973   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9974     // Pure-specifiers are handled in ActOnPureSpecifier.
9975     Diag(Method->getLocation(), diag::err_member_function_initialization)
9976       << Method->getDeclName() << Init->getSourceRange();
9977     Method->setInvalidDecl();
9978     return;
9979   }
9980 
9981   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9982   if (!VDecl) {
9983     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9984     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9985     RealDecl->setInvalidDecl();
9986     return;
9987   }
9988 
9989   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9990   if (VDecl->getType()->isUndeducedType()) {
9991     // Attempt typo correction early so that the type of the init expression can
9992     // be deduced based on the chosen correction if the original init contains a
9993     // TypoExpr.
9994     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9995     if (!Res.isUsable()) {
9996       RealDecl->setInvalidDecl();
9997       return;
9998     }
9999     Init = Res.get();
10000 
10001     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10002       return;
10003   }
10004 
10005   // dllimport cannot be used on variable definitions.
10006   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10007     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10008     VDecl->setInvalidDecl();
10009     return;
10010   }
10011 
10012   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10013     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10014     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10015     VDecl->setInvalidDecl();
10016     return;
10017   }
10018 
10019   if (!VDecl->getType()->isDependentType()) {
10020     // A definition must end up with a complete type, which means it must be
10021     // complete with the restriction that an array type might be completed by
10022     // the initializer; note that later code assumes this restriction.
10023     QualType BaseDeclType = VDecl->getType();
10024     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10025       BaseDeclType = Array->getElementType();
10026     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10027                             diag::err_typecheck_decl_incomplete_type)) {
10028       RealDecl->setInvalidDecl();
10029       return;
10030     }
10031 
10032     // The variable can not have an abstract class type.
10033     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10034                                diag::err_abstract_type_in_decl,
10035                                AbstractVariableType))
10036       VDecl->setInvalidDecl();
10037   }
10038 
10039   // If adding the initializer will turn this declaration into a definition,
10040   // and we already have a definition for this variable, diagnose or otherwise
10041   // handle the situation.
10042   VarDecl *Def;
10043   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10044       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10045       !VDecl->isThisDeclarationADemotedDefinition() &&
10046       checkVarDeclRedefinition(Def, VDecl))
10047     return;
10048 
10049   if (getLangOpts().CPlusPlus) {
10050     // C++ [class.static.data]p4
10051     //   If a static data member is of const integral or const
10052     //   enumeration type, its declaration in the class definition can
10053     //   specify a constant-initializer which shall be an integral
10054     //   constant expression (5.19). In that case, the member can appear
10055     //   in integral constant expressions. The member shall still be
10056     //   defined in a namespace scope if it is used in the program and the
10057     //   namespace scope definition shall not contain an initializer.
10058     //
10059     // We already performed a redefinition check above, but for static
10060     // data members we also need to check whether there was an in-class
10061     // declaration with an initializer.
10062     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10063       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10064           << VDecl->getDeclName();
10065       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10066            diag::note_previous_initializer)
10067           << 0;
10068       return;
10069     }
10070 
10071     if (VDecl->hasLocalStorage())
10072       getCurFunction()->setHasBranchProtectedScope();
10073 
10074     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10075       VDecl->setInvalidDecl();
10076       return;
10077     }
10078   }
10079 
10080   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10081   // a kernel function cannot be initialized."
10082   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10083     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10084     VDecl->setInvalidDecl();
10085     return;
10086   }
10087 
10088   // Get the decls type and save a reference for later, since
10089   // CheckInitializerTypes may change it.
10090   QualType DclT = VDecl->getType(), SavT = DclT;
10091 
10092   // Expressions default to 'id' when we're in a debugger
10093   // and we are assigning it to a variable of Objective-C pointer type.
10094   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10095       Init->getType() == Context.UnknownAnyTy) {
10096     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10097     if (Result.isInvalid()) {
10098       VDecl->setInvalidDecl();
10099       return;
10100     }
10101     Init = Result.get();
10102   }
10103 
10104   // Perform the initialization.
10105   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10106   if (!VDecl->isInvalidDecl()) {
10107     // Handle errors like: int a({0})
10108     if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
10109         !canInitializeWithParenthesizedList(VDecl->getType()))
10110       if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
10111         Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
10112             << VDecl->getType() << CXXDirectInit->getSourceRange()
10113             << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
10114             << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
10115         Init = IList;
10116         CXXDirectInit = nullptr;
10117       }
10118 
10119     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10120     InitializationKind Kind = InitializationKind::CreateForInit(
10121         VDecl->getLocation(), DirectInit, Init);
10122 
10123     MultiExprArg Args = Init;
10124     if (CXXDirectInit)
10125       Args = MultiExprArg(CXXDirectInit->getExprs(),
10126                           CXXDirectInit->getNumExprs());
10127 
10128     // Try to correct any TypoExprs in the initialization arguments.
10129     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10130       ExprResult Res = CorrectDelayedTyposInExpr(
10131           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10132             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10133             return Init.Failed() ? ExprError() : E;
10134           });
10135       if (Res.isInvalid()) {
10136         VDecl->setInvalidDecl();
10137       } else if (Res.get() != Args[Idx]) {
10138         Args[Idx] = Res.get();
10139       }
10140     }
10141     if (VDecl->isInvalidDecl())
10142       return;
10143 
10144     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10145                                    /*TopLevelOfInitList=*/false,
10146                                    /*TreatUnavailableAsInvalid=*/false);
10147     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10148     if (Result.isInvalid()) {
10149       VDecl->setInvalidDecl();
10150       return;
10151     }
10152 
10153     Init = Result.getAs<Expr>();
10154   }
10155 
10156   // Check for self-references within variable initializers.
10157   // Variables declared within a function/method body (except for references)
10158   // are handled by a dataflow analysis.
10159   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10160       VDecl->getType()->isReferenceType()) {
10161     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10162   }
10163 
10164   // If the type changed, it means we had an incomplete type that was
10165   // completed by the initializer. For example:
10166   //   int ary[] = { 1, 3, 5 };
10167   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10168   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10169     VDecl->setType(DclT);
10170 
10171   if (!VDecl->isInvalidDecl()) {
10172     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10173 
10174     if (VDecl->hasAttr<BlocksAttr>())
10175       checkRetainCycles(VDecl, Init);
10176 
10177     // It is safe to assign a weak reference into a strong variable.
10178     // Although this code can still have problems:
10179     //   id x = self.weakProp;
10180     //   id y = self.weakProp;
10181     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10182     // paths through the function. This should be revisited if
10183     // -Wrepeated-use-of-weak is made flow-sensitive.
10184     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
10185         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10186                          Init->getLocStart()))
10187       getCurFunction()->markSafeWeakUse(Init);
10188   }
10189 
10190   // The initialization is usually a full-expression.
10191   //
10192   // FIXME: If this is a braced initialization of an aggregate, it is not
10193   // an expression, and each individual field initializer is a separate
10194   // full-expression. For instance, in:
10195   //
10196   //   struct Temp { ~Temp(); };
10197   //   struct S { S(Temp); };
10198   //   struct T { S a, b; } t = { Temp(), Temp() }
10199   //
10200   // we should destroy the first Temp before constructing the second.
10201   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10202                                           false,
10203                                           VDecl->isConstexpr());
10204   if (Result.isInvalid()) {
10205     VDecl->setInvalidDecl();
10206     return;
10207   }
10208   Init = Result.get();
10209 
10210   // Attach the initializer to the decl.
10211   VDecl->setInit(Init);
10212 
10213   if (VDecl->isLocalVarDecl()) {
10214     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10215     // static storage duration shall be constant expressions or string literals.
10216     // C++ does not have this restriction.
10217     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10218       const Expr *Culprit;
10219       if (VDecl->getStorageClass() == SC_Static)
10220         CheckForConstantInitializer(Init, DclT);
10221       // C89 is stricter than C99 for non-static aggregate types.
10222       // C89 6.5.7p3: All the expressions [...] in an initializer list
10223       // for an object that has aggregate or union type shall be
10224       // constant expressions.
10225       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10226                isa<InitListExpr>(Init) &&
10227                !Init->isConstantInitializer(Context, false, &Culprit))
10228         Diag(Culprit->getExprLoc(),
10229              diag::ext_aggregate_init_not_constant)
10230           << Culprit->getSourceRange();
10231     }
10232   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10233              VDecl->getLexicalDeclContext()->isRecord()) {
10234     // This is an in-class initialization for a static data member, e.g.,
10235     //
10236     // struct S {
10237     //   static const int value = 17;
10238     // };
10239 
10240     // C++ [class.mem]p4:
10241     //   A member-declarator can contain a constant-initializer only
10242     //   if it declares a static member (9.4) of const integral or
10243     //   const enumeration type, see 9.4.2.
10244     //
10245     // C++11 [class.static.data]p3:
10246     //   If a non-volatile non-inline const static data member is of integral
10247     //   or enumeration type, its declaration in the class definition can
10248     //   specify a brace-or-equal-initializer in which every initalizer-clause
10249     //   that is an assignment-expression is a constant expression. A static
10250     //   data member of literal type can be declared in the class definition
10251     //   with the constexpr specifier; if so, its declaration shall specify a
10252     //   brace-or-equal-initializer in which every initializer-clause that is
10253     //   an assignment-expression is a constant expression.
10254 
10255     // Do nothing on dependent types.
10256     if (DclT->isDependentType()) {
10257 
10258     // Allow any 'static constexpr' members, whether or not they are of literal
10259     // type. We separately check that every constexpr variable is of literal
10260     // type.
10261     } else if (VDecl->isConstexpr()) {
10262 
10263     // Require constness.
10264     } else if (!DclT.isConstQualified()) {
10265       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10266         << Init->getSourceRange();
10267       VDecl->setInvalidDecl();
10268 
10269     // We allow integer constant expressions in all cases.
10270     } else if (DclT->isIntegralOrEnumerationType()) {
10271       // Check whether the expression is a constant expression.
10272       SourceLocation Loc;
10273       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10274         // In C++11, a non-constexpr const static data member with an
10275         // in-class initializer cannot be volatile.
10276         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10277       else if (Init->isValueDependent())
10278         ; // Nothing to check.
10279       else if (Init->isIntegerConstantExpr(Context, &Loc))
10280         ; // Ok, it's an ICE!
10281       else if (Init->isEvaluatable(Context)) {
10282         // If we can constant fold the initializer through heroics, accept it,
10283         // but report this as a use of an extension for -pedantic.
10284         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10285           << Init->getSourceRange();
10286       } else {
10287         // Otherwise, this is some crazy unknown case.  Report the issue at the
10288         // location provided by the isIntegerConstantExpr failed check.
10289         Diag(Loc, diag::err_in_class_initializer_non_constant)
10290           << Init->getSourceRange();
10291         VDecl->setInvalidDecl();
10292       }
10293 
10294     // We allow foldable floating-point constants as an extension.
10295     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10296       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10297       // it anyway and provide a fixit to add the 'constexpr'.
10298       if (getLangOpts().CPlusPlus11) {
10299         Diag(VDecl->getLocation(),
10300              diag::ext_in_class_initializer_float_type_cxx11)
10301             << DclT << Init->getSourceRange();
10302         Diag(VDecl->getLocStart(),
10303              diag::note_in_class_initializer_float_type_cxx11)
10304             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10305       } else {
10306         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10307           << DclT << Init->getSourceRange();
10308 
10309         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10310           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10311             << Init->getSourceRange();
10312           VDecl->setInvalidDecl();
10313         }
10314       }
10315 
10316     // Suggest adding 'constexpr' in C++11 for literal types.
10317     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10318       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10319         << DclT << Init->getSourceRange()
10320         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10321       VDecl->setConstexpr(true);
10322 
10323     } else {
10324       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10325         << DclT << Init->getSourceRange();
10326       VDecl->setInvalidDecl();
10327     }
10328   } else if (VDecl->isFileVarDecl()) {
10329     // In C, extern is typically used to avoid tentative definitions when
10330     // declaring variables in headers, but adding an intializer makes it a
10331     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10332     // In C++, extern is often used to give implictly static const variables
10333     // external linkage, so don't warn in that case. If selectany is present,
10334     // this might be header code intended for C and C++ inclusion, so apply the
10335     // C++ rules.
10336     if (VDecl->getStorageClass() == SC_Extern &&
10337         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10338          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10339         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10340         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10341       Diag(VDecl->getLocation(), diag::warn_extern_init);
10342 
10343     // C99 6.7.8p4. All file scoped initializers need to be constant.
10344     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10345       CheckForConstantInitializer(Init, DclT);
10346   }
10347 
10348   // We will represent direct-initialization similarly to copy-initialization:
10349   //    int x(1);  -as-> int x = 1;
10350   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10351   //
10352   // Clients that want to distinguish between the two forms, can check for
10353   // direct initializer using VarDecl::getInitStyle().
10354   // A major benefit is that clients that don't particularly care about which
10355   // exactly form was it (like the CodeGen) can handle both cases without
10356   // special case code.
10357 
10358   // C++ 8.5p11:
10359   // The form of initialization (using parentheses or '=') is generally
10360   // insignificant, but does matter when the entity being initialized has a
10361   // class type.
10362   if (CXXDirectInit) {
10363     assert(DirectInit && "Call-style initializer must be direct init.");
10364     VDecl->setInitStyle(VarDecl::CallInit);
10365   } else if (DirectInit) {
10366     // This must be list-initialization. No other way is direct-initialization.
10367     VDecl->setInitStyle(VarDecl::ListInit);
10368   }
10369 
10370   CheckCompleteVariableDeclaration(VDecl);
10371 }
10372 
10373 /// ActOnInitializerError - Given that there was an error parsing an
10374 /// initializer for the given declaration, try to return to some form
10375 /// of sanity.
10376 void Sema::ActOnInitializerError(Decl *D) {
10377   // Our main concern here is re-establishing invariants like "a
10378   // variable's type is either dependent or complete".
10379   if (!D || D->isInvalidDecl()) return;
10380 
10381   VarDecl *VD = dyn_cast<VarDecl>(D);
10382   if (!VD) return;
10383 
10384   // Bindings are not usable if we can't make sense of the initializer.
10385   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10386     for (auto *BD : DD->bindings())
10387       BD->setInvalidDecl();
10388 
10389   // Auto types are meaningless if we can't make sense of the initializer.
10390   if (ParsingInitForAutoVars.count(D)) {
10391     D->setInvalidDecl();
10392     return;
10393   }
10394 
10395   QualType Ty = VD->getType();
10396   if (Ty->isDependentType()) return;
10397 
10398   // Require a complete type.
10399   if (RequireCompleteType(VD->getLocation(),
10400                           Context.getBaseElementType(Ty),
10401                           diag::err_typecheck_decl_incomplete_type)) {
10402     VD->setInvalidDecl();
10403     return;
10404   }
10405 
10406   // Require a non-abstract type.
10407   if (RequireNonAbstractType(VD->getLocation(), Ty,
10408                              diag::err_abstract_type_in_decl,
10409                              AbstractVariableType)) {
10410     VD->setInvalidDecl();
10411     return;
10412   }
10413 
10414   // Don't bother complaining about constructors or destructors,
10415   // though.
10416 }
10417 
10418 /// Checks if an object of the given type can be initialized with parenthesized
10419 /// init-list.
10420 ///
10421 /// \param TargetType Type of object being initialized.
10422 ///
10423 /// The function is used to detect wrong initializations, such as 'int({0})'.
10424 ///
10425 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
10426   return TargetType->isDependentType() || TargetType->isRecordType() ||
10427          TargetType->getContainedAutoType();
10428 }
10429 
10430 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10431   // If there is no declaration, there was an error parsing it. Just ignore it.
10432   if (!RealDecl)
10433     return;
10434 
10435   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10436     QualType Type = Var->getType();
10437 
10438     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10439     if (isa<DecompositionDecl>(RealDecl)) {
10440       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10441       Var->setInvalidDecl();
10442       return;
10443     }
10444 
10445     if (Type->isUndeducedType() &&
10446         DeduceVariableDeclarationType(Var, false, nullptr))
10447       return;
10448 
10449     // C++11 [class.static.data]p3: A static data member can be declared with
10450     // the constexpr specifier; if so, its declaration shall specify
10451     // a brace-or-equal-initializer.
10452     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10453     // the definition of a variable [...] or the declaration of a static data
10454     // member.
10455     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10456         !Var->isThisDeclarationADemotedDefinition()) {
10457       if (Var->isStaticDataMember()) {
10458         // C++1z removes the relevant rule; the in-class declaration is always
10459         // a definition there.
10460         if (!getLangOpts().CPlusPlus1z) {
10461           Diag(Var->getLocation(),
10462                diag::err_constexpr_static_mem_var_requires_init)
10463             << Var->getDeclName();
10464           Var->setInvalidDecl();
10465           return;
10466         }
10467       } else {
10468         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10469         Var->setInvalidDecl();
10470         return;
10471       }
10472     }
10473 
10474     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10475     // definition having the concept specifier is called a variable concept. A
10476     // concept definition refers to [...] a variable concept and its initializer.
10477     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10478       if (VTD->isConcept()) {
10479         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10480         Var->setInvalidDecl();
10481         return;
10482       }
10483     }
10484 
10485     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10486     // be initialized.
10487     if (!Var->isInvalidDecl() &&
10488         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10489         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10490       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10491       Var->setInvalidDecl();
10492       return;
10493     }
10494 
10495     switch (Var->isThisDeclarationADefinition()) {
10496     case VarDecl::Definition:
10497       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10498         break;
10499 
10500       // We have an out-of-line definition of a static data member
10501       // that has an in-class initializer, so we type-check this like
10502       // a declaration.
10503       //
10504       // Fall through
10505 
10506     case VarDecl::DeclarationOnly:
10507       // It's only a declaration.
10508 
10509       // Block scope. C99 6.7p7: If an identifier for an object is
10510       // declared with no linkage (C99 6.2.2p6), the type for the
10511       // object shall be complete.
10512       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10513           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10514           RequireCompleteType(Var->getLocation(), Type,
10515                               diag::err_typecheck_decl_incomplete_type))
10516         Var->setInvalidDecl();
10517 
10518       // Make sure that the type is not abstract.
10519       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10520           RequireNonAbstractType(Var->getLocation(), Type,
10521                                  diag::err_abstract_type_in_decl,
10522                                  AbstractVariableType))
10523         Var->setInvalidDecl();
10524       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10525           Var->getStorageClass() == SC_PrivateExtern) {
10526         Diag(Var->getLocation(), diag::warn_private_extern);
10527         Diag(Var->getLocation(), diag::note_private_extern);
10528       }
10529 
10530       return;
10531 
10532     case VarDecl::TentativeDefinition:
10533       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10534       // object that has file scope without an initializer, and without a
10535       // storage-class specifier or with the storage-class specifier "static",
10536       // constitutes a tentative definition. Note: A tentative definition with
10537       // external linkage is valid (C99 6.2.2p5).
10538       if (!Var->isInvalidDecl()) {
10539         if (const IncompleteArrayType *ArrayT
10540                                     = Context.getAsIncompleteArrayType(Type)) {
10541           if (RequireCompleteType(Var->getLocation(),
10542                                   ArrayT->getElementType(),
10543                                   diag::err_illegal_decl_array_incomplete_type))
10544             Var->setInvalidDecl();
10545         } else if (Var->getStorageClass() == SC_Static) {
10546           // C99 6.9.2p3: If the declaration of an identifier for an object is
10547           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10548           // declared type shall not be an incomplete type.
10549           // NOTE: code such as the following
10550           //     static struct s;
10551           //     struct s { int a; };
10552           // is accepted by gcc. Hence here we issue a warning instead of
10553           // an error and we do not invalidate the static declaration.
10554           // NOTE: to avoid multiple warnings, only check the first declaration.
10555           if (Var->isFirstDecl())
10556             RequireCompleteType(Var->getLocation(), Type,
10557                                 diag::ext_typecheck_decl_incomplete_type);
10558         }
10559       }
10560 
10561       // Record the tentative definition; we're done.
10562       if (!Var->isInvalidDecl())
10563         TentativeDefinitions.push_back(Var);
10564       return;
10565     }
10566 
10567     // Provide a specific diagnostic for uninitialized variable
10568     // definitions with incomplete array type.
10569     if (Type->isIncompleteArrayType()) {
10570       Diag(Var->getLocation(),
10571            diag::err_typecheck_incomplete_array_needs_initializer);
10572       Var->setInvalidDecl();
10573       return;
10574     }
10575 
10576     // Provide a specific diagnostic for uninitialized variable
10577     // definitions with reference type.
10578     if (Type->isReferenceType()) {
10579       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10580         << Var->getDeclName()
10581         << SourceRange(Var->getLocation(), Var->getLocation());
10582       Var->setInvalidDecl();
10583       return;
10584     }
10585 
10586     // Do not attempt to type-check the default initializer for a
10587     // variable with dependent type.
10588     if (Type->isDependentType())
10589       return;
10590 
10591     if (Var->isInvalidDecl())
10592       return;
10593 
10594     if (!Var->hasAttr<AliasAttr>()) {
10595       if (RequireCompleteType(Var->getLocation(),
10596                               Context.getBaseElementType(Type),
10597                               diag::err_typecheck_decl_incomplete_type)) {
10598         Var->setInvalidDecl();
10599         return;
10600       }
10601     } else {
10602       return;
10603     }
10604 
10605     // The variable can not have an abstract class type.
10606     if (RequireNonAbstractType(Var->getLocation(), Type,
10607                                diag::err_abstract_type_in_decl,
10608                                AbstractVariableType)) {
10609       Var->setInvalidDecl();
10610       return;
10611     }
10612 
10613     // Check for jumps past the implicit initializer.  C++0x
10614     // clarifies that this applies to a "variable with automatic
10615     // storage duration", not a "local variable".
10616     // C++11 [stmt.dcl]p3
10617     //   A program that jumps from a point where a variable with automatic
10618     //   storage duration is not in scope to a point where it is in scope is
10619     //   ill-formed unless the variable has scalar type, class type with a
10620     //   trivial default constructor and a trivial destructor, a cv-qualified
10621     //   version of one of these types, or an array of one of the preceding
10622     //   types and is declared without an initializer.
10623     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10624       if (const RecordType *Record
10625             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10626         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10627         // Mark the function for further checking even if the looser rules of
10628         // C++11 do not require such checks, so that we can diagnose
10629         // incompatibilities with C++98.
10630         if (!CXXRecord->isPOD())
10631           getCurFunction()->setHasBranchProtectedScope();
10632       }
10633     }
10634 
10635     // C++03 [dcl.init]p9:
10636     //   If no initializer is specified for an object, and the
10637     //   object is of (possibly cv-qualified) non-POD class type (or
10638     //   array thereof), the object shall be default-initialized; if
10639     //   the object is of const-qualified type, the underlying class
10640     //   type shall have a user-declared default
10641     //   constructor. Otherwise, if no initializer is specified for
10642     //   a non- static object, the object and its subobjects, if
10643     //   any, have an indeterminate initial value); if the object
10644     //   or any of its subobjects are of const-qualified type, the
10645     //   program is ill-formed.
10646     // C++0x [dcl.init]p11:
10647     //   If no initializer is specified for an object, the object is
10648     //   default-initialized; [...].
10649     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10650     InitializationKind Kind
10651       = InitializationKind::CreateDefault(Var->getLocation());
10652 
10653     InitializationSequence InitSeq(*this, Entity, Kind, None);
10654     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10655     if (Init.isInvalid())
10656       Var->setInvalidDecl();
10657     else if (Init.get()) {
10658       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10659       // This is important for template substitution.
10660       Var->setInitStyle(VarDecl::CallInit);
10661     }
10662 
10663     CheckCompleteVariableDeclaration(Var);
10664   }
10665 }
10666 
10667 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10668   // If there is no declaration, there was an error parsing it. Ignore it.
10669   if (!D)
10670     return;
10671 
10672   VarDecl *VD = dyn_cast<VarDecl>(D);
10673   if (!VD) {
10674     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10675     D->setInvalidDecl();
10676     return;
10677   }
10678 
10679   VD->setCXXForRangeDecl(true);
10680 
10681   // for-range-declaration cannot be given a storage class specifier.
10682   int Error = -1;
10683   switch (VD->getStorageClass()) {
10684   case SC_None:
10685     break;
10686   case SC_Extern:
10687     Error = 0;
10688     break;
10689   case SC_Static:
10690     Error = 1;
10691     break;
10692   case SC_PrivateExtern:
10693     Error = 2;
10694     break;
10695   case SC_Auto:
10696     Error = 3;
10697     break;
10698   case SC_Register:
10699     Error = 4;
10700     break;
10701   }
10702   if (Error != -1) {
10703     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10704       << VD->getDeclName() << Error;
10705     D->setInvalidDecl();
10706   }
10707 }
10708 
10709 StmtResult
10710 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10711                                  IdentifierInfo *Ident,
10712                                  ParsedAttributes &Attrs,
10713                                  SourceLocation AttrEnd) {
10714   // C++1y [stmt.iter]p1:
10715   //   A range-based for statement of the form
10716   //      for ( for-range-identifier : for-range-initializer ) statement
10717   //   is equivalent to
10718   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10719   DeclSpec DS(Attrs.getPool().getFactory());
10720 
10721   const char *PrevSpec;
10722   unsigned DiagID;
10723   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10724                      getPrintingPolicy());
10725 
10726   Declarator D(DS, Declarator::ForContext);
10727   D.SetIdentifier(Ident, IdentLoc);
10728   D.takeAttributes(Attrs, AttrEnd);
10729 
10730   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10731   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10732                 EmptyAttrs, IdentLoc);
10733   Decl *Var = ActOnDeclarator(S, D);
10734   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10735   FinalizeDeclaration(Var);
10736   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10737                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10738 }
10739 
10740 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10741   if (var->isInvalidDecl()) return;
10742 
10743   if (getLangOpts().OpenCL) {
10744     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10745     // initialiser
10746     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10747         !var->hasInit()) {
10748       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10749           << 1 /*Init*/;
10750       var->setInvalidDecl();
10751       return;
10752     }
10753   }
10754 
10755   // In Objective-C, don't allow jumps past the implicit initialization of a
10756   // local retaining variable.
10757   if (getLangOpts().ObjC1 &&
10758       var->hasLocalStorage()) {
10759     switch (var->getType().getObjCLifetime()) {
10760     case Qualifiers::OCL_None:
10761     case Qualifiers::OCL_ExplicitNone:
10762     case Qualifiers::OCL_Autoreleasing:
10763       break;
10764 
10765     case Qualifiers::OCL_Weak:
10766     case Qualifiers::OCL_Strong:
10767       getCurFunction()->setHasBranchProtectedScope();
10768       break;
10769     }
10770   }
10771 
10772   // Warn about externally-visible variables being defined without a
10773   // prior declaration.  We only want to do this for global
10774   // declarations, but we also specifically need to avoid doing it for
10775   // class members because the linkage of an anonymous class can
10776   // change if it's later given a typedef name.
10777   if (var->isThisDeclarationADefinition() &&
10778       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10779       var->isExternallyVisible() && var->hasLinkage() &&
10780       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10781                                   var->getLocation())) {
10782     // Find a previous declaration that's not a definition.
10783     VarDecl *prev = var->getPreviousDecl();
10784     while (prev && prev->isThisDeclarationADefinition())
10785       prev = prev->getPreviousDecl();
10786 
10787     if (!prev)
10788       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10789   }
10790 
10791   // Cache the result of checking for constant initialization.
10792   Optional<bool> CacheHasConstInit;
10793   const Expr *CacheCulprit;
10794   auto checkConstInit = [&]() mutable {
10795     if (!CacheHasConstInit)
10796       CacheHasConstInit = var->getInit()->isConstantInitializer(
10797             Context, var->getType()->isReferenceType(), &CacheCulprit);
10798     return *CacheHasConstInit;
10799   };
10800 
10801   if (var->getTLSKind() == VarDecl::TLS_Static) {
10802     if (var->getType().isDestructedType()) {
10803       // GNU C++98 edits for __thread, [basic.start.term]p3:
10804       //   The type of an object with thread storage duration shall not
10805       //   have a non-trivial destructor.
10806       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10807       if (getLangOpts().CPlusPlus11)
10808         Diag(var->getLocation(), diag::note_use_thread_local);
10809     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10810       if (!checkConstInit()) {
10811         // GNU C++98 edits for __thread, [basic.start.init]p4:
10812         //   An object of thread storage duration shall not require dynamic
10813         //   initialization.
10814         // FIXME: Need strict checking here.
10815         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10816           << CacheCulprit->getSourceRange();
10817         if (getLangOpts().CPlusPlus11)
10818           Diag(var->getLocation(), diag::note_use_thread_local);
10819       }
10820     }
10821   }
10822 
10823   // Apply section attributes and pragmas to global variables.
10824   bool GlobalStorage = var->hasGlobalStorage();
10825   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10826       ActiveTemplateInstantiations.empty()) {
10827     PragmaStack<StringLiteral *> *Stack = nullptr;
10828     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10829     if (var->getType().isConstQualified())
10830       Stack = &ConstSegStack;
10831     else if (!var->getInit()) {
10832       Stack = &BSSSegStack;
10833       SectionFlags |= ASTContext::PSF_Write;
10834     } else {
10835       Stack = &DataSegStack;
10836       SectionFlags |= ASTContext::PSF_Write;
10837     }
10838     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10839       var->addAttr(SectionAttr::CreateImplicit(
10840           Context, SectionAttr::Declspec_allocate,
10841           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10842     }
10843     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10844       if (UnifySection(SA->getName(), SectionFlags, var))
10845         var->dropAttr<SectionAttr>();
10846 
10847     // Apply the init_seg attribute if this has an initializer.  If the
10848     // initializer turns out to not be dynamic, we'll end up ignoring this
10849     // attribute.
10850     if (CurInitSeg && var->getInit())
10851       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10852                                                CurInitSegLoc));
10853   }
10854 
10855   // All the following checks are C++ only.
10856   if (!getLangOpts().CPlusPlus) {
10857       // If this variable must be emitted, add it as an initializer for the
10858       // current module.
10859      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10860        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10861      return;
10862   }
10863 
10864   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10865     CheckCompleteDecompositionDeclaration(DD);
10866 
10867   QualType type = var->getType();
10868   if (type->isDependentType()) return;
10869 
10870   // __block variables might require us to capture a copy-initializer.
10871   if (var->hasAttr<BlocksAttr>()) {
10872     // It's currently invalid to ever have a __block variable with an
10873     // array type; should we diagnose that here?
10874 
10875     // Regardless, we don't want to ignore array nesting when
10876     // constructing this copy.
10877     if (type->isStructureOrClassType()) {
10878       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10879       SourceLocation poi = var->getLocation();
10880       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10881       ExprResult result
10882         = PerformMoveOrCopyInitialization(
10883             InitializedEntity::InitializeBlock(poi, type, false),
10884             var, var->getType(), varRef, /*AllowNRVO=*/true);
10885       if (!result.isInvalid()) {
10886         result = MaybeCreateExprWithCleanups(result);
10887         Expr *init = result.getAs<Expr>();
10888         Context.setBlockVarCopyInits(var, init);
10889       }
10890     }
10891   }
10892 
10893   Expr *Init = var->getInit();
10894   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10895   QualType baseType = Context.getBaseElementType(type);
10896 
10897   if (!var->getDeclContext()->isDependentContext() &&
10898       Init && !Init->isValueDependent()) {
10899 
10900     if (var->isConstexpr()) {
10901       SmallVector<PartialDiagnosticAt, 8> Notes;
10902       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10903         SourceLocation DiagLoc = var->getLocation();
10904         // If the note doesn't add any useful information other than a source
10905         // location, fold it into the primary diagnostic.
10906         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10907               diag::note_invalid_subexpr_in_const_expr) {
10908           DiagLoc = Notes[0].first;
10909           Notes.clear();
10910         }
10911         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10912           << var << Init->getSourceRange();
10913         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10914           Diag(Notes[I].first, Notes[I].second);
10915       }
10916     } else if (var->isUsableInConstantExpressions(Context)) {
10917       // Check whether the initializer of a const variable of integral or
10918       // enumeration type is an ICE now, since we can't tell whether it was
10919       // initialized by a constant expression if we check later.
10920       var->checkInitIsICE();
10921     }
10922 
10923     // Don't emit further diagnostics about constexpr globals since they
10924     // were just diagnosed.
10925     if (!var->isConstexpr() && GlobalStorage &&
10926             var->hasAttr<RequireConstantInitAttr>()) {
10927       // FIXME: Need strict checking in C++03 here.
10928       bool DiagErr = getLangOpts().CPlusPlus11
10929           ? !var->checkInitIsICE() : !checkConstInit();
10930       if (DiagErr) {
10931         auto attr = var->getAttr<RequireConstantInitAttr>();
10932         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10933           << Init->getSourceRange();
10934         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10935           << attr->getRange();
10936       }
10937     }
10938     else if (!var->isConstexpr() && IsGlobal &&
10939              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10940                                     var->getLocation())) {
10941       // Warn about globals which don't have a constant initializer.  Don't
10942       // warn about globals with a non-trivial destructor because we already
10943       // warned about them.
10944       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10945       if (!(RD && !RD->hasTrivialDestructor())) {
10946         if (!checkConstInit())
10947           Diag(var->getLocation(), diag::warn_global_constructor)
10948             << Init->getSourceRange();
10949       }
10950     }
10951   }
10952 
10953   // Require the destructor.
10954   if (const RecordType *recordType = baseType->getAs<RecordType>())
10955     FinalizeVarWithDestructor(var, recordType);
10956 
10957   // If this variable must be emitted, add it as an initializer for the current
10958   // module.
10959   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10960     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10961 }
10962 
10963 /// \brief Determines if a variable's alignment is dependent.
10964 static bool hasDependentAlignment(VarDecl *VD) {
10965   if (VD->getType()->isDependentType())
10966     return true;
10967   for (auto *I : VD->specific_attrs<AlignedAttr>())
10968     if (I->isAlignmentDependent())
10969       return true;
10970   return false;
10971 }
10972 
10973 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10974 /// any semantic actions necessary after any initializer has been attached.
10975 void
10976 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10977   // Note that we are no longer parsing the initializer for this declaration.
10978   ParsingInitForAutoVars.erase(ThisDecl);
10979 
10980   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10981   if (!VD)
10982     return;
10983 
10984   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10985     for (auto *BD : DD->bindings()) {
10986       FinalizeDeclaration(BD);
10987     }
10988   }
10989 
10990   checkAttributesAfterMerging(*this, *VD);
10991 
10992   // Perform TLS alignment check here after attributes attached to the variable
10993   // which may affect the alignment have been processed. Only perform the check
10994   // if the target has a maximum TLS alignment (zero means no constraints).
10995   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10996     // Protect the check so that it's not performed on dependent types and
10997     // dependent alignments (we can't determine the alignment in that case).
10998     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
10999         !VD->isInvalidDecl()) {
11000       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11001       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11002         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11003           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11004           << (unsigned)MaxAlignChars.getQuantity();
11005       }
11006     }
11007   }
11008 
11009   if (VD->isStaticLocal()) {
11010     if (FunctionDecl *FD =
11011             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11012       // Static locals inherit dll attributes from their function.
11013       if (Attr *A = getDLLAttr(FD)) {
11014         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11015         NewAttr->setInherited(true);
11016         VD->addAttr(NewAttr);
11017       }
11018       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11019       // function, only __shared__ variables may be declared with
11020       // static storage class.
11021       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11022           CUDADiagIfDeviceCode(VD->getLocation(),
11023                                diag::err_device_static_local_var)
11024               << CurrentCUDATarget())
11025         VD->setInvalidDecl();
11026     }
11027   }
11028 
11029   // Perform check for initializers of device-side global variables.
11030   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11031   // 7.5). We must also apply the same checks to all __shared__
11032   // variables whether they are local or not. CUDA also allows
11033   // constant initializers for __constant__ and __device__ variables.
11034   if (getLangOpts().CUDA) {
11035     const Expr *Init = VD->getInit();
11036     if (Init && VD->hasGlobalStorage()) {
11037       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11038           VD->hasAttr<CUDASharedAttr>()) {
11039         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11040         bool AllowedInit = false;
11041         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11042           AllowedInit =
11043               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11044         // We'll allow constant initializers even if it's a non-empty
11045         // constructor according to CUDA rules. This deviates from NVCC,
11046         // but allows us to handle things like constexpr constructors.
11047         if (!AllowedInit &&
11048             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11049           AllowedInit = VD->getInit()->isConstantInitializer(
11050               Context, VD->getType()->isReferenceType());
11051 
11052         // Also make sure that destructor, if there is one, is empty.
11053         if (AllowedInit)
11054           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11055             AllowedInit =
11056                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11057 
11058         if (!AllowedInit) {
11059           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11060                                       ? diag::err_shared_var_init
11061                                       : diag::err_dynamic_var_init)
11062               << Init->getSourceRange();
11063           VD->setInvalidDecl();
11064         }
11065       } else {
11066         // This is a host-side global variable.  Check that the initializer is
11067         // callable from the host side.
11068         const FunctionDecl *InitFn = nullptr;
11069         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11070           InitFn = CE->getConstructor();
11071         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11072           InitFn = CE->getDirectCallee();
11073         }
11074         if (InitFn) {
11075           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11076           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11077             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11078                 << InitFnTarget << InitFn;
11079             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11080             VD->setInvalidDecl();
11081           }
11082         }
11083       }
11084     }
11085   }
11086 
11087   // Grab the dllimport or dllexport attribute off of the VarDecl.
11088   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11089 
11090   // Imported static data members cannot be defined out-of-line.
11091   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11092     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11093         VD->isThisDeclarationADefinition()) {
11094       // We allow definitions of dllimport class template static data members
11095       // with a warning.
11096       CXXRecordDecl *Context =
11097         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11098       bool IsClassTemplateMember =
11099           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11100           Context->getDescribedClassTemplate();
11101 
11102       Diag(VD->getLocation(),
11103            IsClassTemplateMember
11104                ? diag::warn_attribute_dllimport_static_field_definition
11105                : diag::err_attribute_dllimport_static_field_definition);
11106       Diag(IA->getLocation(), diag::note_attribute);
11107       if (!IsClassTemplateMember)
11108         VD->setInvalidDecl();
11109     }
11110   }
11111 
11112   // dllimport/dllexport variables cannot be thread local, their TLS index
11113   // isn't exported with the variable.
11114   if (DLLAttr && VD->getTLSKind()) {
11115     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11116     if (F && getDLLAttr(F)) {
11117       assert(VD->isStaticLocal());
11118       // But if this is a static local in a dlimport/dllexport function, the
11119       // function will never be inlined, which means the var would never be
11120       // imported, so having it marked import/export is safe.
11121     } else {
11122       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11123                                                                     << DLLAttr;
11124       VD->setInvalidDecl();
11125     }
11126   }
11127 
11128   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11129     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11130       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11131       VD->dropAttr<UsedAttr>();
11132     }
11133   }
11134 
11135   const DeclContext *DC = VD->getDeclContext();
11136   // If there's a #pragma GCC visibility in scope, and this isn't a class
11137   // member, set the visibility of this variable.
11138   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11139     AddPushedVisibilityAttribute(VD);
11140 
11141   // FIXME: Warn on unused templates.
11142   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11143       !isa<VarTemplatePartialSpecializationDecl>(VD))
11144     MarkUnusedFileScopedDecl(VD);
11145 
11146   // Now we have parsed the initializer and can update the table of magic
11147   // tag values.
11148   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11149       !VD->getType()->isIntegralOrEnumerationType())
11150     return;
11151 
11152   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11153     const Expr *MagicValueExpr = VD->getInit();
11154     if (!MagicValueExpr) {
11155       continue;
11156     }
11157     llvm::APSInt MagicValueInt;
11158     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11159       Diag(I->getRange().getBegin(),
11160            diag::err_type_tag_for_datatype_not_ice)
11161         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11162       continue;
11163     }
11164     if (MagicValueInt.getActiveBits() > 64) {
11165       Diag(I->getRange().getBegin(),
11166            diag::err_type_tag_for_datatype_too_large)
11167         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11168       continue;
11169     }
11170     uint64_t MagicValue = MagicValueInt.getZExtValue();
11171     RegisterTypeTagForDatatype(I->getArgumentKind(),
11172                                MagicValue,
11173                                I->getMatchingCType(),
11174                                I->getLayoutCompatible(),
11175                                I->getMustBeNull());
11176   }
11177 }
11178 
11179 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11180   auto *VD = dyn_cast<VarDecl>(DD);
11181   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11182 }
11183 
11184 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11185                                                    ArrayRef<Decl *> Group) {
11186   SmallVector<Decl*, 8> Decls;
11187 
11188   if (DS.isTypeSpecOwned())
11189     Decls.push_back(DS.getRepAsDecl());
11190 
11191   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11192   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11193   bool DiagnosedMultipleDecomps = false;
11194   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11195   bool DiagnosedNonDeducedAuto = false;
11196 
11197   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11198     if (Decl *D = Group[i]) {
11199       // For declarators, there are some additional syntactic-ish checks we need
11200       // to perform.
11201       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11202         if (!FirstDeclaratorInGroup)
11203           FirstDeclaratorInGroup = DD;
11204         if (!FirstDecompDeclaratorInGroup)
11205           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11206         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11207             !hasDeducedAuto(DD))
11208           FirstNonDeducedAutoInGroup = DD;
11209 
11210         if (FirstDeclaratorInGroup != DD) {
11211           // A decomposition declaration cannot be combined with any other
11212           // declaration in the same group.
11213           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11214             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11215                  diag::err_decomp_decl_not_alone)
11216                 << FirstDeclaratorInGroup->getSourceRange()
11217                 << DD->getSourceRange();
11218             DiagnosedMultipleDecomps = true;
11219           }
11220 
11221           // A declarator that uses 'auto' in any way other than to declare a
11222           // variable with a deduced type cannot be combined with any other
11223           // declarator in the same group.
11224           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11225             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11226                  diag::err_auto_non_deduced_not_alone)
11227                 << FirstNonDeducedAutoInGroup->getType()
11228                        ->hasAutoForTrailingReturnType()
11229                 << FirstDeclaratorInGroup->getSourceRange()
11230                 << DD->getSourceRange();
11231             DiagnosedNonDeducedAuto = true;
11232           }
11233         }
11234       }
11235 
11236       Decls.push_back(D);
11237     }
11238   }
11239 
11240   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11241     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11242       handleTagNumbering(Tag, S);
11243       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11244           getLangOpts().CPlusPlus)
11245         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11246     }
11247   }
11248 
11249   return BuildDeclaratorGroup(Decls);
11250 }
11251 
11252 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11253 /// group, performing any necessary semantic checking.
11254 Sema::DeclGroupPtrTy
11255 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11256   // C++14 [dcl.spec.auto]p7: (DR1347)
11257   //   If the type that replaces the placeholder type is not the same in each
11258   //   deduction, the program is ill-formed.
11259   if (Group.size() > 1) {
11260     QualType Deduced;
11261     VarDecl *DeducedDecl = nullptr;
11262     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11263       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11264       if (!D || D->isInvalidDecl())
11265         break;
11266       DeducedType *DT = D->getType()->getContainedDeducedType();
11267       if (!DT || DT->getDeducedType().isNull())
11268         continue;
11269       if (Deduced.isNull()) {
11270         Deduced = DT->getDeducedType();
11271         DeducedDecl = D;
11272       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11273         auto *AT = dyn_cast<AutoType>(DT);
11274         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11275              diag::err_auto_different_deductions)
11276           << (AT ? (unsigned)AT->getKeyword() : 3)
11277           << Deduced << DeducedDecl->getDeclName()
11278           << DT->getDeducedType() << D->getDeclName()
11279           << DeducedDecl->getInit()->getSourceRange()
11280           << D->getInit()->getSourceRange();
11281         D->setInvalidDecl();
11282         break;
11283       }
11284     }
11285   }
11286 
11287   ActOnDocumentableDecls(Group);
11288 
11289   return DeclGroupPtrTy::make(
11290       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11291 }
11292 
11293 void Sema::ActOnDocumentableDecl(Decl *D) {
11294   ActOnDocumentableDecls(D);
11295 }
11296 
11297 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11298   // Don't parse the comment if Doxygen diagnostics are ignored.
11299   if (Group.empty() || !Group[0])
11300     return;
11301 
11302   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11303                       Group[0]->getLocation()) &&
11304       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11305                       Group[0]->getLocation()))
11306     return;
11307 
11308   if (Group.size() >= 2) {
11309     // This is a decl group.  Normally it will contain only declarations
11310     // produced from declarator list.  But in case we have any definitions or
11311     // additional declaration references:
11312     //   'typedef struct S {} S;'
11313     //   'typedef struct S *S;'
11314     //   'struct S *pS;'
11315     // FinalizeDeclaratorGroup adds these as separate declarations.
11316     Decl *MaybeTagDecl = Group[0];
11317     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11318       Group = Group.slice(1);
11319     }
11320   }
11321 
11322   // See if there are any new comments that are not attached to a decl.
11323   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11324   if (!Comments.empty() &&
11325       !Comments.back()->isAttached()) {
11326     // There is at least one comment that not attached to a decl.
11327     // Maybe it should be attached to one of these decls?
11328     //
11329     // Note that this way we pick up not only comments that precede the
11330     // declaration, but also comments that *follow* the declaration -- thanks to
11331     // the lookahead in the lexer: we've consumed the semicolon and looked
11332     // ahead through comments.
11333     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11334       Context.getCommentForDecl(Group[i], &PP);
11335   }
11336 }
11337 
11338 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11339 /// to introduce parameters into function prototype scope.
11340 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11341   const DeclSpec &DS = D.getDeclSpec();
11342 
11343   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11344 
11345   // C++03 [dcl.stc]p2 also permits 'auto'.
11346   StorageClass SC = SC_None;
11347   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11348     SC = SC_Register;
11349   } else if (getLangOpts().CPlusPlus &&
11350              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11351     SC = SC_Auto;
11352   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11353     Diag(DS.getStorageClassSpecLoc(),
11354          diag::err_invalid_storage_class_in_func_decl);
11355     D.getMutableDeclSpec().ClearStorageClassSpecs();
11356   }
11357 
11358   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11359     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11360       << DeclSpec::getSpecifierName(TSCS);
11361   if (DS.isInlineSpecified())
11362     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11363         << getLangOpts().CPlusPlus1z;
11364   if (DS.isConstexprSpecified())
11365     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11366       << 0;
11367   if (DS.isConceptSpecified())
11368     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11369 
11370   DiagnoseFunctionSpecifiers(DS);
11371 
11372   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11373   QualType parmDeclType = TInfo->getType();
11374 
11375   if (getLangOpts().CPlusPlus) {
11376     // Check that there are no default arguments inside the type of this
11377     // parameter.
11378     CheckExtraCXXDefaultArguments(D);
11379 
11380     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11381     if (D.getCXXScopeSpec().isSet()) {
11382       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11383         << D.getCXXScopeSpec().getRange();
11384       D.getCXXScopeSpec().clear();
11385     }
11386   }
11387 
11388   // Ensure we have a valid name
11389   IdentifierInfo *II = nullptr;
11390   if (D.hasName()) {
11391     II = D.getIdentifier();
11392     if (!II) {
11393       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11394         << GetNameForDeclarator(D).getName();
11395       D.setInvalidType(true);
11396     }
11397   }
11398 
11399   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11400   if (II) {
11401     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11402                    ForRedeclaration);
11403     LookupName(R, S);
11404     if (R.isSingleResult()) {
11405       NamedDecl *PrevDecl = R.getFoundDecl();
11406       if (PrevDecl->isTemplateParameter()) {
11407         // Maybe we will complain about the shadowed template parameter.
11408         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11409         // Just pretend that we didn't see the previous declaration.
11410         PrevDecl = nullptr;
11411       } else if (S->isDeclScope(PrevDecl)) {
11412         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11413         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11414 
11415         // Recover by removing the name
11416         II = nullptr;
11417         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11418         D.setInvalidType(true);
11419       }
11420     }
11421   }
11422 
11423   // Temporarily put parameter variables in the translation unit, not
11424   // the enclosing context.  This prevents them from accidentally
11425   // looking like class members in C++.
11426   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11427                                     D.getLocStart(),
11428                                     D.getIdentifierLoc(), II,
11429                                     parmDeclType, TInfo,
11430                                     SC);
11431 
11432   if (D.isInvalidType())
11433     New->setInvalidDecl();
11434 
11435   assert(S->isFunctionPrototypeScope());
11436   assert(S->getFunctionPrototypeDepth() >= 1);
11437   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11438                     S->getNextFunctionPrototypeIndex());
11439 
11440   // Add the parameter declaration into this scope.
11441   S->AddDecl(New);
11442   if (II)
11443     IdResolver.AddDecl(New);
11444 
11445   ProcessDeclAttributes(S, New, D);
11446 
11447   if (D.getDeclSpec().isModulePrivateSpecified())
11448     Diag(New->getLocation(), diag::err_module_private_local)
11449       << 1 << New->getDeclName()
11450       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11451       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11452 
11453   if (New->hasAttr<BlocksAttr>()) {
11454     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11455   }
11456   return New;
11457 }
11458 
11459 /// \brief Synthesizes a variable for a parameter arising from a
11460 /// typedef.
11461 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11462                                               SourceLocation Loc,
11463                                               QualType T) {
11464   /* FIXME: setting StartLoc == Loc.
11465      Would it be worth to modify callers so as to provide proper source
11466      location for the unnamed parameters, embedding the parameter's type? */
11467   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11468                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11469                                            SC_None, nullptr);
11470   Param->setImplicit();
11471   return Param;
11472 }
11473 
11474 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11475   // Don't diagnose unused-parameter errors in template instantiations; we
11476   // will already have done so in the template itself.
11477   if (!ActiveTemplateInstantiations.empty())
11478     return;
11479 
11480   for (const ParmVarDecl *Parameter : Parameters) {
11481     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11482         !Parameter->hasAttr<UnusedAttr>()) {
11483       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11484         << Parameter->getDeclName();
11485     }
11486   }
11487 }
11488 
11489 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11490     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11491   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11492     return;
11493 
11494   // Warn if the return value is pass-by-value and larger than the specified
11495   // threshold.
11496   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11497     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11498     if (Size > LangOpts.NumLargeByValueCopy)
11499       Diag(D->getLocation(), diag::warn_return_value_size)
11500           << D->getDeclName() << Size;
11501   }
11502 
11503   // Warn if any parameter is pass-by-value and larger than the specified
11504   // threshold.
11505   for (const ParmVarDecl *Parameter : Parameters) {
11506     QualType T = Parameter->getType();
11507     if (T->isDependentType() || !T.isPODType(Context))
11508       continue;
11509     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11510     if (Size > LangOpts.NumLargeByValueCopy)
11511       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11512           << Parameter->getDeclName() << Size;
11513   }
11514 }
11515 
11516 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11517                                   SourceLocation NameLoc, IdentifierInfo *Name,
11518                                   QualType T, TypeSourceInfo *TSInfo,
11519                                   StorageClass SC) {
11520   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11521   if (getLangOpts().ObjCAutoRefCount &&
11522       T.getObjCLifetime() == Qualifiers::OCL_None &&
11523       T->isObjCLifetimeType()) {
11524 
11525     Qualifiers::ObjCLifetime lifetime;
11526 
11527     // Special cases for arrays:
11528     //   - if it's const, use __unsafe_unretained
11529     //   - otherwise, it's an error
11530     if (T->isArrayType()) {
11531       if (!T.isConstQualified()) {
11532         DelayedDiagnostics.add(
11533             sema::DelayedDiagnostic::makeForbiddenType(
11534             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11535       }
11536       lifetime = Qualifiers::OCL_ExplicitNone;
11537     } else {
11538       lifetime = T->getObjCARCImplicitLifetime();
11539     }
11540     T = Context.getLifetimeQualifiedType(T, lifetime);
11541   }
11542 
11543   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11544                                          Context.getAdjustedParameterType(T),
11545                                          TSInfo, SC, nullptr);
11546 
11547   // Parameters can not be abstract class types.
11548   // For record types, this is done by the AbstractClassUsageDiagnoser once
11549   // the class has been completely parsed.
11550   if (!CurContext->isRecord() &&
11551       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11552                              AbstractParamType))
11553     New->setInvalidDecl();
11554 
11555   // Parameter declarators cannot be interface types. All ObjC objects are
11556   // passed by reference.
11557   if (T->isObjCObjectType()) {
11558     SourceLocation TypeEndLoc =
11559         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11560     Diag(NameLoc,
11561          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11562       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11563     T = Context.getObjCObjectPointerType(T);
11564     New->setType(T);
11565   }
11566 
11567   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11568   // duration shall not be qualified by an address-space qualifier."
11569   // Since all parameters have automatic store duration, they can not have
11570   // an address space.
11571   if (T.getAddressSpace() != 0) {
11572     // OpenCL allows function arguments declared to be an array of a type
11573     // to be qualified with an address space.
11574     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11575       Diag(NameLoc, diag::err_arg_with_address_space);
11576       New->setInvalidDecl();
11577     }
11578   }
11579 
11580   return New;
11581 }
11582 
11583 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11584                                            SourceLocation LocAfterDecls) {
11585   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11586 
11587   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11588   // for a K&R function.
11589   if (!FTI.hasPrototype) {
11590     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11591       --i;
11592       if (FTI.Params[i].Param == nullptr) {
11593         SmallString<256> Code;
11594         llvm::raw_svector_ostream(Code)
11595             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11596         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11597             << FTI.Params[i].Ident
11598             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11599 
11600         // Implicitly declare the argument as type 'int' for lack of a better
11601         // type.
11602         AttributeFactory attrs;
11603         DeclSpec DS(attrs);
11604         const char* PrevSpec; // unused
11605         unsigned DiagID; // unused
11606         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11607                            DiagID, Context.getPrintingPolicy());
11608         // Use the identifier location for the type source range.
11609         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11610         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11611         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11612         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11613         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11614       }
11615     }
11616   }
11617 }
11618 
11619 Decl *
11620 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11621                               MultiTemplateParamsArg TemplateParameterLists,
11622                               SkipBodyInfo *SkipBody) {
11623   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11624   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11625   Scope *ParentScope = FnBodyScope->getParent();
11626 
11627   D.setFunctionDefinitionKind(FDK_Definition);
11628   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11629   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11630 }
11631 
11632 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11633   Consumer.HandleInlineFunctionDefinition(D);
11634 }
11635 
11636 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11637                              const FunctionDecl*& PossibleZeroParamPrototype) {
11638   // Don't warn about invalid declarations.
11639   if (FD->isInvalidDecl())
11640     return false;
11641 
11642   // Or declarations that aren't global.
11643   if (!FD->isGlobal())
11644     return false;
11645 
11646   // Don't warn about C++ member functions.
11647   if (isa<CXXMethodDecl>(FD))
11648     return false;
11649 
11650   // Don't warn about 'main'.
11651   if (FD->isMain())
11652     return false;
11653 
11654   // Don't warn about inline functions.
11655   if (FD->isInlined())
11656     return false;
11657 
11658   // Don't warn about function templates.
11659   if (FD->getDescribedFunctionTemplate())
11660     return false;
11661 
11662   // Don't warn about function template specializations.
11663   if (FD->isFunctionTemplateSpecialization())
11664     return false;
11665 
11666   // Don't warn for OpenCL kernels.
11667   if (FD->hasAttr<OpenCLKernelAttr>())
11668     return false;
11669 
11670   // Don't warn on explicitly deleted functions.
11671   if (FD->isDeleted())
11672     return false;
11673 
11674   bool MissingPrototype = true;
11675   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11676        Prev; Prev = Prev->getPreviousDecl()) {
11677     // Ignore any declarations that occur in function or method
11678     // scope, because they aren't visible from the header.
11679     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11680       continue;
11681 
11682     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11683     if (FD->getNumParams() == 0)
11684       PossibleZeroParamPrototype = Prev;
11685     break;
11686   }
11687 
11688   return MissingPrototype;
11689 }
11690 
11691 void
11692 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11693                                    const FunctionDecl *EffectiveDefinition,
11694                                    SkipBodyInfo *SkipBody) {
11695   // Don't complain if we're in GNU89 mode and the previous definition
11696   // was an extern inline function.
11697   const FunctionDecl *Definition = EffectiveDefinition;
11698   if (!Definition)
11699     if (!FD->isDefined(Definition))
11700       return;
11701 
11702   if (canRedefineFunction(Definition, getLangOpts()))
11703     return;
11704 
11705   // If we don't have a visible definition of the function, and it's inline or
11706   // a template, skip the new definition.
11707   if (SkipBody && !hasVisibleDefinition(Definition) &&
11708       (Definition->getFormalLinkage() == InternalLinkage ||
11709        Definition->isInlined() ||
11710        Definition->getDescribedFunctionTemplate() ||
11711        Definition->getNumTemplateParameterLists())) {
11712     SkipBody->ShouldSkip = true;
11713     if (auto *TD = Definition->getDescribedFunctionTemplate())
11714       makeMergedDefinitionVisible(TD, FD->getLocation());
11715     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11716                                 FD->getLocation());
11717     return;
11718   }
11719 
11720   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11721       Definition->getStorageClass() == SC_Extern)
11722     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11723         << FD->getDeclName() << getLangOpts().CPlusPlus;
11724   else
11725     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11726 
11727   Diag(Definition->getLocation(), diag::note_previous_definition);
11728   FD->setInvalidDecl();
11729 }
11730 
11731 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11732                                    Sema &S) {
11733   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11734 
11735   LambdaScopeInfo *LSI = S.PushLambdaScope();
11736   LSI->CallOperator = CallOperator;
11737   LSI->Lambda = LambdaClass;
11738   LSI->ReturnType = CallOperator->getReturnType();
11739   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11740 
11741   if (LCD == LCD_None)
11742     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11743   else if (LCD == LCD_ByCopy)
11744     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11745   else if (LCD == LCD_ByRef)
11746     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11747   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11748 
11749   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11750   LSI->Mutable = !CallOperator->isConst();
11751 
11752   // Add the captures to the LSI so they can be noted as already
11753   // captured within tryCaptureVar.
11754   auto I = LambdaClass->field_begin();
11755   for (const auto &C : LambdaClass->captures()) {
11756     if (C.capturesVariable()) {
11757       VarDecl *VD = C.getCapturedVar();
11758       if (VD->isInitCapture())
11759         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11760       QualType CaptureType = VD->getType();
11761       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11762       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11763           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11764           /*EllipsisLoc*/C.isPackExpansion()
11765                          ? C.getEllipsisLoc() : SourceLocation(),
11766           CaptureType, /*Expr*/ nullptr);
11767 
11768     } else if (C.capturesThis()) {
11769       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11770                               /*Expr*/ nullptr,
11771                               C.getCaptureKind() == LCK_StarThis);
11772     } else {
11773       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11774     }
11775     ++I;
11776   }
11777 }
11778 
11779 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11780                                     SkipBodyInfo *SkipBody) {
11781   // Clear the last template instantiation error context.
11782   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11783 
11784   if (!D)
11785     return D;
11786   FunctionDecl *FD = nullptr;
11787 
11788   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11789     FD = FunTmpl->getTemplatedDecl();
11790   else
11791     FD = cast<FunctionDecl>(D);
11792 
11793   // See if this is a redefinition.
11794   if (!FD->isLateTemplateParsed()) {
11795     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11796 
11797     // If we're skipping the body, we're done. Don't enter the scope.
11798     if (SkipBody && SkipBody->ShouldSkip)
11799       return D;
11800   }
11801 
11802   // Mark this function as "will have a body eventually".  This lets users to
11803   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11804   // this function.
11805   FD->setWillHaveBody();
11806 
11807   // If we are instantiating a generic lambda call operator, push
11808   // a LambdaScopeInfo onto the function stack.  But use the information
11809   // that's already been calculated (ActOnLambdaExpr) to prime the current
11810   // LambdaScopeInfo.
11811   // When the template operator is being specialized, the LambdaScopeInfo,
11812   // has to be properly restored so that tryCaptureVariable doesn't try
11813   // and capture any new variables. In addition when calculating potential
11814   // captures during transformation of nested lambdas, it is necessary to
11815   // have the LSI properly restored.
11816   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11817     assert(ActiveTemplateInstantiations.size() &&
11818       "There should be an active template instantiation on the stack "
11819       "when instantiating a generic lambda!");
11820     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11821   }
11822   else
11823     // Enter a new function scope
11824     PushFunctionScope();
11825 
11826   // Builtin functions cannot be defined.
11827   if (unsigned BuiltinID = FD->getBuiltinID()) {
11828     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11829         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11830       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11831       FD->setInvalidDecl();
11832     }
11833   }
11834 
11835   // The return type of a function definition must be complete
11836   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11837   QualType ResultType = FD->getReturnType();
11838   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11839       !FD->isInvalidDecl() &&
11840       RequireCompleteType(FD->getLocation(), ResultType,
11841                           diag::err_func_def_incomplete_result))
11842     FD->setInvalidDecl();
11843 
11844   if (FnBodyScope)
11845     PushDeclContext(FnBodyScope, FD);
11846 
11847   // Check the validity of our function parameters
11848   CheckParmsForFunctionDef(FD->parameters(),
11849                            /*CheckParameterNames=*/true);
11850 
11851   // Add non-parameter declarations already in the function to the current
11852   // scope.
11853   if (FnBodyScope) {
11854     for (Decl *NPD : FD->decls()) {
11855       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11856       if (!NonParmDecl)
11857         continue;
11858       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11859              "parameters should not be in newly created FD yet");
11860 
11861       // If the decl has a name, make it accessible in the current scope.
11862       if (NonParmDecl->getDeclName())
11863         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11864 
11865       // Similarly, dive into enums and fish their constants out, making them
11866       // accessible in this scope.
11867       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11868         for (auto *EI : ED->enumerators())
11869           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11870       }
11871     }
11872   }
11873 
11874   // Introduce our parameters into the function scope
11875   for (auto Param : FD->parameters()) {
11876     Param->setOwningFunction(FD);
11877 
11878     // If this has an identifier, add it to the scope stack.
11879     if (Param->getIdentifier() && FnBodyScope) {
11880       CheckShadow(FnBodyScope, Param);
11881 
11882       PushOnScopeChains(Param, FnBodyScope);
11883     }
11884   }
11885 
11886   // Ensure that the function's exception specification is instantiated.
11887   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11888     ResolveExceptionSpec(D->getLocation(), FPT);
11889 
11890   // dllimport cannot be applied to non-inline function definitions.
11891   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11892       !FD->isTemplateInstantiation()) {
11893     assert(!FD->hasAttr<DLLExportAttr>());
11894     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11895     FD->setInvalidDecl();
11896     return D;
11897   }
11898   // We want to attach documentation to original Decl (which might be
11899   // a function template).
11900   ActOnDocumentableDecl(D);
11901   if (getCurLexicalContext()->isObjCContainer() &&
11902       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11903       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11904     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11905 
11906   return D;
11907 }
11908 
11909 /// \brief Given the set of return statements within a function body,
11910 /// compute the variables that are subject to the named return value
11911 /// optimization.
11912 ///
11913 /// Each of the variables that is subject to the named return value
11914 /// optimization will be marked as NRVO variables in the AST, and any
11915 /// return statement that has a marked NRVO variable as its NRVO candidate can
11916 /// use the named return value optimization.
11917 ///
11918 /// This function applies a very simplistic algorithm for NRVO: if every return
11919 /// statement in the scope of a variable has the same NRVO candidate, that
11920 /// candidate is an NRVO variable.
11921 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11922   ReturnStmt **Returns = Scope->Returns.data();
11923 
11924   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11925     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11926       if (!NRVOCandidate->isNRVOVariable())
11927         Returns[I]->setNRVOCandidate(nullptr);
11928     }
11929   }
11930 }
11931 
11932 bool Sema::canDelayFunctionBody(const Declarator &D) {
11933   // We can't delay parsing the body of a constexpr function template (yet).
11934   if (D.getDeclSpec().isConstexprSpecified())
11935     return false;
11936 
11937   // We can't delay parsing the body of a function template with a deduced
11938   // return type (yet).
11939   if (D.getDeclSpec().hasAutoTypeSpec()) {
11940     // If the placeholder introduces a non-deduced trailing return type,
11941     // we can still delay parsing it.
11942     if (D.getNumTypeObjects()) {
11943       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11944       if (Outer.Kind == DeclaratorChunk::Function &&
11945           Outer.Fun.hasTrailingReturnType()) {
11946         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11947         return Ty.isNull() || !Ty->isUndeducedType();
11948       }
11949     }
11950     return false;
11951   }
11952 
11953   return true;
11954 }
11955 
11956 bool Sema::canSkipFunctionBody(Decl *D) {
11957   // We cannot skip the body of a function (or function template) which is
11958   // constexpr, since we may need to evaluate its body in order to parse the
11959   // rest of the file.
11960   // We cannot skip the body of a function with an undeduced return type,
11961   // because any callers of that function need to know the type.
11962   if (const FunctionDecl *FD = D->getAsFunction())
11963     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11964       return false;
11965   return Consumer.shouldSkipFunctionBody(D);
11966 }
11967 
11968 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11969   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11970     FD->setHasSkippedBody();
11971   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11972     MD->setHasSkippedBody();
11973   return Decl;
11974 }
11975 
11976 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11977   return ActOnFinishFunctionBody(D, BodyArg, false);
11978 }
11979 
11980 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11981                                     bool IsInstantiation) {
11982   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11983 
11984   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11985   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11986 
11987   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11988     CheckCompletedCoroutineBody(FD, Body);
11989 
11990   if (FD) {
11991     FD->setBody(Body);
11992 
11993     if (getLangOpts().CPlusPlus14) {
11994       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11995           FD->getReturnType()->isUndeducedType()) {
11996         // If the function has a deduced result type but contains no 'return'
11997         // statements, the result type as written must be exactly 'auto', and
11998         // the deduced result type is 'void'.
11999         if (!FD->getReturnType()->getAs<AutoType>()) {
12000           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12001               << FD->getReturnType();
12002           FD->setInvalidDecl();
12003         } else {
12004           // Substitute 'void' for the 'auto' in the type.
12005           TypeLoc ResultType = getReturnTypeLoc(FD);
12006           Context.adjustDeducedFunctionResultType(
12007               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12008         }
12009       }
12010     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12011       // In C++11, we don't use 'auto' deduction rules for lambda call
12012       // operators because we don't support return type deduction.
12013       auto *LSI = getCurLambda();
12014       if (LSI->HasImplicitReturnType) {
12015         deduceClosureReturnType(*LSI);
12016 
12017         // C++11 [expr.prim.lambda]p4:
12018         //   [...] if there are no return statements in the compound-statement
12019         //   [the deduced type is] the type void
12020         QualType RetType =
12021             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12022 
12023         // Update the return type to the deduced type.
12024         const FunctionProtoType *Proto =
12025             FD->getType()->getAs<FunctionProtoType>();
12026         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12027                                             Proto->getExtProtoInfo()));
12028       }
12029     }
12030 
12031     // The only way to be included in UndefinedButUsed is if there is an
12032     // ODR use before the definition. Avoid the expensive map lookup if this
12033     // is the first declaration.
12034     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12035       if (!FD->isExternallyVisible())
12036         UndefinedButUsed.erase(FD);
12037       else if (FD->isInlined() &&
12038                !LangOpts.GNUInline &&
12039                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12040         UndefinedButUsed.erase(FD);
12041     }
12042 
12043     // If the function implicitly returns zero (like 'main') or is naked,
12044     // don't complain about missing return statements.
12045     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12046       WP.disableCheckFallThrough();
12047 
12048     // MSVC permits the use of pure specifier (=0) on function definition,
12049     // defined at class scope, warn about this non-standard construct.
12050     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12051       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12052 
12053     if (!FD->isInvalidDecl()) {
12054       // Don't diagnose unused parameters of defaulted or deleted functions.
12055       if (!FD->isDeleted() && !FD->isDefaulted())
12056         DiagnoseUnusedParameters(FD->parameters());
12057       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12058                                              FD->getReturnType(), FD);
12059 
12060       // If this is a structor, we need a vtable.
12061       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12062         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12063       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12064         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12065 
12066       // Try to apply the named return value optimization. We have to check
12067       // if we can do this here because lambdas keep return statements around
12068       // to deduce an implicit return type.
12069       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12070           !FD->isDependentContext())
12071         computeNRVO(Body, getCurFunction());
12072     }
12073 
12074     // GNU warning -Wmissing-prototypes:
12075     //   Warn if a global function is defined without a previous
12076     //   prototype declaration. This warning is issued even if the
12077     //   definition itself provides a prototype. The aim is to detect
12078     //   global functions that fail to be declared in header files.
12079     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12080     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12081       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12082 
12083       if (PossibleZeroParamPrototype) {
12084         // We found a declaration that is not a prototype,
12085         // but that could be a zero-parameter prototype
12086         if (TypeSourceInfo *TI =
12087                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12088           TypeLoc TL = TI->getTypeLoc();
12089           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12090             Diag(PossibleZeroParamPrototype->getLocation(),
12091                  diag::note_declaration_not_a_prototype)
12092                 << PossibleZeroParamPrototype
12093                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12094         }
12095       }
12096 
12097       // GNU warning -Wstrict-prototypes
12098       //   Warn if K&R function is defined without a previous declaration.
12099       //   This warning is issued only if the definition itself does not provide
12100       //   a prototype. Only K&R definitions do not provide a prototype.
12101       //   An empty list in a function declarator that is part of a definition
12102       //   of that function specifies that the function has no parameters
12103       //   (C99 6.7.5.3p14)
12104       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12105           !LangOpts.CPlusPlus) {
12106         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12107         TypeLoc TL = TI->getTypeLoc();
12108         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12109         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12110       }
12111     }
12112 
12113     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12114       const CXXMethodDecl *KeyFunction;
12115       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12116           MD->isVirtual() &&
12117           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12118           MD == KeyFunction->getCanonicalDecl()) {
12119         // Update the key-function state if necessary for this ABI.
12120         if (FD->isInlined() &&
12121             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12122           Context.setNonKeyFunction(MD);
12123 
12124           // If the newly-chosen key function is already defined, then we
12125           // need to mark the vtable as used retroactively.
12126           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12127           const FunctionDecl *Definition;
12128           if (KeyFunction && KeyFunction->isDefined(Definition))
12129             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12130         } else {
12131           // We just defined they key function; mark the vtable as used.
12132           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12133         }
12134       }
12135     }
12136 
12137     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12138            "Function parsing confused");
12139   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12140     assert(MD == getCurMethodDecl() && "Method parsing confused");
12141     MD->setBody(Body);
12142     if (!MD->isInvalidDecl()) {
12143       DiagnoseUnusedParameters(MD->parameters());
12144       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12145                                              MD->getReturnType(), MD);
12146 
12147       if (Body)
12148         computeNRVO(Body, getCurFunction());
12149     }
12150     if (getCurFunction()->ObjCShouldCallSuper) {
12151       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12152         << MD->getSelector().getAsString();
12153       getCurFunction()->ObjCShouldCallSuper = false;
12154     }
12155     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12156       const ObjCMethodDecl *InitMethod = nullptr;
12157       bool isDesignated =
12158           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12159       assert(isDesignated && InitMethod);
12160       (void)isDesignated;
12161 
12162       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12163         auto IFace = MD->getClassInterface();
12164         if (!IFace)
12165           return false;
12166         auto SuperD = IFace->getSuperClass();
12167         if (!SuperD)
12168           return false;
12169         return SuperD->getIdentifier() ==
12170             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12171       };
12172       // Don't issue this warning for unavailable inits or direct subclasses
12173       // of NSObject.
12174       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12175         Diag(MD->getLocation(),
12176              diag::warn_objc_designated_init_missing_super_call);
12177         Diag(InitMethod->getLocation(),
12178              diag::note_objc_designated_init_marked_here);
12179       }
12180       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12181     }
12182     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12183       // Don't issue this warning for unavaialable inits.
12184       if (!MD->isUnavailable())
12185         Diag(MD->getLocation(),
12186              diag::warn_objc_secondary_init_missing_init_call);
12187       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12188     }
12189   } else {
12190     return nullptr;
12191   }
12192 
12193   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12194     DiagnoseUnguardedAvailabilityViolations(dcl);
12195 
12196   assert(!getCurFunction()->ObjCShouldCallSuper &&
12197          "This should only be set for ObjC methods, which should have been "
12198          "handled in the block above.");
12199 
12200   // Verify and clean out per-function state.
12201   if (Body && (!FD || !FD->isDefaulted())) {
12202     // C++ constructors that have function-try-blocks can't have return
12203     // statements in the handlers of that block. (C++ [except.handle]p14)
12204     // Verify this.
12205     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12206       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12207 
12208     // Verify that gotos and switch cases don't jump into scopes illegally.
12209     if (getCurFunction()->NeedsScopeChecking() &&
12210         !PP.isCodeCompletionEnabled())
12211       DiagnoseInvalidJumps(Body);
12212 
12213     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12214       if (!Destructor->getParent()->isDependentType())
12215         CheckDestructor(Destructor);
12216 
12217       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12218                                              Destructor->getParent());
12219     }
12220 
12221     // If any errors have occurred, clear out any temporaries that may have
12222     // been leftover. This ensures that these temporaries won't be picked up for
12223     // deletion in some later function.
12224     if (getDiagnostics().hasErrorOccurred() ||
12225         getDiagnostics().getSuppressAllDiagnostics()) {
12226       DiscardCleanupsInEvaluationContext();
12227     }
12228     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12229         !isa<FunctionTemplateDecl>(dcl)) {
12230       // Since the body is valid, issue any analysis-based warnings that are
12231       // enabled.
12232       ActivePolicy = &WP;
12233     }
12234 
12235     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12236         (!CheckConstexprFunctionDecl(FD) ||
12237          !CheckConstexprFunctionBody(FD, Body)))
12238       FD->setInvalidDecl();
12239 
12240     if (FD && FD->hasAttr<NakedAttr>()) {
12241       for (const Stmt *S : Body->children()) {
12242         // Allow local register variables without initializer as they don't
12243         // require prologue.
12244         bool RegisterVariables = false;
12245         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12246           for (const auto *Decl : DS->decls()) {
12247             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12248               RegisterVariables =
12249                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12250               if (!RegisterVariables)
12251                 break;
12252             }
12253           }
12254         }
12255         if (RegisterVariables)
12256           continue;
12257         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12258           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12259           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12260           FD->setInvalidDecl();
12261           break;
12262         }
12263       }
12264     }
12265 
12266     assert(ExprCleanupObjects.size() ==
12267                ExprEvalContexts.back().NumCleanupObjects &&
12268            "Leftover temporaries in function");
12269     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12270     assert(MaybeODRUseExprs.empty() &&
12271            "Leftover expressions for odr-use checking");
12272   }
12273 
12274   if (!IsInstantiation)
12275     PopDeclContext();
12276 
12277   PopFunctionScopeInfo(ActivePolicy, dcl);
12278   // If any errors have occurred, clear out any temporaries that may have
12279   // been leftover. This ensures that these temporaries won't be picked up for
12280   // deletion in some later function.
12281   if (getDiagnostics().hasErrorOccurred()) {
12282     DiscardCleanupsInEvaluationContext();
12283   }
12284 
12285   return dcl;
12286 }
12287 
12288 /// When we finish delayed parsing of an attribute, we must attach it to the
12289 /// relevant Decl.
12290 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12291                                        ParsedAttributes &Attrs) {
12292   // Always attach attributes to the underlying decl.
12293   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12294     D = TD->getTemplatedDecl();
12295   ProcessDeclAttributeList(S, D, Attrs.getList());
12296 
12297   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12298     if (Method->isStatic())
12299       checkThisInStaticMemberFunctionAttributes(Method);
12300 }
12301 
12302 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12303 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12304 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12305                                           IdentifierInfo &II, Scope *S) {
12306   // Before we produce a declaration for an implicitly defined
12307   // function, see whether there was a locally-scoped declaration of
12308   // this name as a function or variable. If so, use that
12309   // (non-visible) declaration, and complain about it.
12310   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12311     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12312     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12313     return ExternCPrev;
12314   }
12315 
12316   // Extension in C99.  Legal in C90, but warn about it.
12317   unsigned diag_id;
12318   if (II.getName().startswith("__builtin_"))
12319     diag_id = diag::warn_builtin_unknown;
12320   else if (getLangOpts().C99)
12321     diag_id = diag::ext_implicit_function_decl;
12322   else
12323     diag_id = diag::warn_implicit_function_decl;
12324   Diag(Loc, diag_id) << &II;
12325 
12326   // Because typo correction is expensive, only do it if the implicit
12327   // function declaration is going to be treated as an error.
12328   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12329     TypoCorrection Corrected;
12330     if (S &&
12331         (Corrected = CorrectTypo(
12332              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12333              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12334       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12335                    /*ErrorRecovery*/false);
12336   }
12337 
12338   // Set a Declarator for the implicit definition: int foo();
12339   const char *Dummy;
12340   AttributeFactory attrFactory;
12341   DeclSpec DS(attrFactory);
12342   unsigned DiagID;
12343   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12344                                   Context.getPrintingPolicy());
12345   (void)Error; // Silence warning.
12346   assert(!Error && "Error setting up implicit decl!");
12347   SourceLocation NoLoc;
12348   Declarator D(DS, Declarator::BlockContext);
12349   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12350                                              /*IsAmbiguous=*/false,
12351                                              /*LParenLoc=*/NoLoc,
12352                                              /*Params=*/nullptr,
12353                                              /*NumParams=*/0,
12354                                              /*EllipsisLoc=*/NoLoc,
12355                                              /*RParenLoc=*/NoLoc,
12356                                              /*TypeQuals=*/0,
12357                                              /*RefQualifierIsLvalueRef=*/true,
12358                                              /*RefQualifierLoc=*/NoLoc,
12359                                              /*ConstQualifierLoc=*/NoLoc,
12360                                              /*VolatileQualifierLoc=*/NoLoc,
12361                                              /*RestrictQualifierLoc=*/NoLoc,
12362                                              /*MutableLoc=*/NoLoc,
12363                                              EST_None,
12364                                              /*ESpecRange=*/SourceRange(),
12365                                              /*Exceptions=*/nullptr,
12366                                              /*ExceptionRanges=*/nullptr,
12367                                              /*NumExceptions=*/0,
12368                                              /*NoexceptExpr=*/nullptr,
12369                                              /*ExceptionSpecTokens=*/nullptr,
12370                                              /*DeclsInPrototype=*/None,
12371                                              Loc, Loc, D),
12372                 DS.getAttributes(),
12373                 SourceLocation());
12374   D.SetIdentifier(&II, Loc);
12375 
12376   // Insert this function into translation-unit scope.
12377 
12378   DeclContext *PrevDC = CurContext;
12379   CurContext = Context.getTranslationUnitDecl();
12380 
12381   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12382   FD->setImplicit();
12383 
12384   CurContext = PrevDC;
12385 
12386   AddKnownFunctionAttributes(FD);
12387 
12388   return FD;
12389 }
12390 
12391 /// \brief Adds any function attributes that we know a priori based on
12392 /// the declaration of this function.
12393 ///
12394 /// These attributes can apply both to implicitly-declared builtins
12395 /// (like __builtin___printf_chk) or to library-declared functions
12396 /// like NSLog or printf.
12397 ///
12398 /// We need to check for duplicate attributes both here and where user-written
12399 /// attributes are applied to declarations.
12400 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12401   if (FD->isInvalidDecl())
12402     return;
12403 
12404   // If this is a built-in function, map its builtin attributes to
12405   // actual attributes.
12406   if (unsigned BuiltinID = FD->getBuiltinID()) {
12407     // Handle printf-formatting attributes.
12408     unsigned FormatIdx;
12409     bool HasVAListArg;
12410     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12411       if (!FD->hasAttr<FormatAttr>()) {
12412         const char *fmt = "printf";
12413         unsigned int NumParams = FD->getNumParams();
12414         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12415             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12416           fmt = "NSString";
12417         FD->addAttr(FormatAttr::CreateImplicit(Context,
12418                                                &Context.Idents.get(fmt),
12419                                                FormatIdx+1,
12420                                                HasVAListArg ? 0 : FormatIdx+2,
12421                                                FD->getLocation()));
12422       }
12423     }
12424     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12425                                              HasVAListArg)) {
12426      if (!FD->hasAttr<FormatAttr>())
12427        FD->addAttr(FormatAttr::CreateImplicit(Context,
12428                                               &Context.Idents.get("scanf"),
12429                                               FormatIdx+1,
12430                                               HasVAListArg ? 0 : FormatIdx+2,
12431                                               FD->getLocation()));
12432     }
12433 
12434     // Mark const if we don't care about errno and that is the only
12435     // thing preventing the function from being const. This allows
12436     // IRgen to use LLVM intrinsics for such functions.
12437     if (!getLangOpts().MathErrno &&
12438         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12439       if (!FD->hasAttr<ConstAttr>())
12440         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12441     }
12442 
12443     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12444         !FD->hasAttr<ReturnsTwiceAttr>())
12445       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12446                                          FD->getLocation()));
12447     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12448       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12449     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12450       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12451     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12452       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12453     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12454         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12455       // Add the appropriate attribute, depending on the CUDA compilation mode
12456       // and which target the builtin belongs to. For example, during host
12457       // compilation, aux builtins are __device__, while the rest are __host__.
12458       if (getLangOpts().CUDAIsDevice !=
12459           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12460         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12461       else
12462         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12463     }
12464   }
12465 
12466   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12467   // throw, add an implicit nothrow attribute to any extern "C" function we come
12468   // across.
12469   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12470       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12471     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12472     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12473       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12474   }
12475 
12476   IdentifierInfo *Name = FD->getIdentifier();
12477   if (!Name)
12478     return;
12479   if ((!getLangOpts().CPlusPlus &&
12480        FD->getDeclContext()->isTranslationUnit()) ||
12481       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12482        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12483        LinkageSpecDecl::lang_c)) {
12484     // Okay: this could be a libc/libm/Objective-C function we know
12485     // about.
12486   } else
12487     return;
12488 
12489   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12490     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12491     // target-specific builtins, perhaps?
12492     if (!FD->hasAttr<FormatAttr>())
12493       FD->addAttr(FormatAttr::CreateImplicit(Context,
12494                                              &Context.Idents.get("printf"), 2,
12495                                              Name->isStr("vasprintf") ? 0 : 3,
12496                                              FD->getLocation()));
12497   }
12498 
12499   if (Name->isStr("__CFStringMakeConstantString")) {
12500     // We already have a __builtin___CFStringMakeConstantString,
12501     // but builds that use -fno-constant-cfstrings don't go through that.
12502     if (!FD->hasAttr<FormatArgAttr>())
12503       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12504                                                 FD->getLocation()));
12505   }
12506 }
12507 
12508 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12509                                     TypeSourceInfo *TInfo) {
12510   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12511   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12512 
12513   if (!TInfo) {
12514     assert(D.isInvalidType() && "no declarator info for valid type");
12515     TInfo = Context.getTrivialTypeSourceInfo(T);
12516   }
12517 
12518   // Scope manipulation handled by caller.
12519   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12520                                            D.getLocStart(),
12521                                            D.getIdentifierLoc(),
12522                                            D.getIdentifier(),
12523                                            TInfo);
12524 
12525   // Bail out immediately if we have an invalid declaration.
12526   if (D.isInvalidType()) {
12527     NewTD->setInvalidDecl();
12528     return NewTD;
12529   }
12530 
12531   if (D.getDeclSpec().isModulePrivateSpecified()) {
12532     if (CurContext->isFunctionOrMethod())
12533       Diag(NewTD->getLocation(), diag::err_module_private_local)
12534         << 2 << NewTD->getDeclName()
12535         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12536         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12537     else
12538       NewTD->setModulePrivate();
12539   }
12540 
12541   // C++ [dcl.typedef]p8:
12542   //   If the typedef declaration defines an unnamed class (or
12543   //   enum), the first typedef-name declared by the declaration
12544   //   to be that class type (or enum type) is used to denote the
12545   //   class type (or enum type) for linkage purposes only.
12546   // We need to check whether the type was declared in the declaration.
12547   switch (D.getDeclSpec().getTypeSpecType()) {
12548   case TST_enum:
12549   case TST_struct:
12550   case TST_interface:
12551   case TST_union:
12552   case TST_class: {
12553     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12554     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12555     break;
12556   }
12557 
12558   default:
12559     break;
12560   }
12561 
12562   return NewTD;
12563 }
12564 
12565 /// \brief Check that this is a valid underlying type for an enum declaration.
12566 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12567   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12568   QualType T = TI->getType();
12569 
12570   if (T->isDependentType())
12571     return false;
12572 
12573   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12574     if (BT->isInteger())
12575       return false;
12576 
12577   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12578   return true;
12579 }
12580 
12581 /// Check whether this is a valid redeclaration of a previous enumeration.
12582 /// \return true if the redeclaration was invalid.
12583 bool Sema::CheckEnumRedeclaration(
12584     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12585     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12586   bool IsFixed = !EnumUnderlyingTy.isNull();
12587 
12588   if (IsScoped != Prev->isScoped()) {
12589     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12590       << Prev->isScoped();
12591     Diag(Prev->getLocation(), diag::note_previous_declaration);
12592     return true;
12593   }
12594 
12595   if (IsFixed && Prev->isFixed()) {
12596     if (!EnumUnderlyingTy->isDependentType() &&
12597         !Prev->getIntegerType()->isDependentType() &&
12598         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12599                                         Prev->getIntegerType())) {
12600       // TODO: Highlight the underlying type of the redeclaration.
12601       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12602         << EnumUnderlyingTy << Prev->getIntegerType();
12603       Diag(Prev->getLocation(), diag::note_previous_declaration)
12604           << Prev->getIntegerTypeRange();
12605       return true;
12606     }
12607   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12608     ;
12609   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12610     ;
12611   } else if (IsFixed != Prev->isFixed()) {
12612     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12613       << Prev->isFixed();
12614     Diag(Prev->getLocation(), diag::note_previous_declaration);
12615     return true;
12616   }
12617 
12618   return false;
12619 }
12620 
12621 /// \brief Get diagnostic %select index for tag kind for
12622 /// redeclaration diagnostic message.
12623 /// WARNING: Indexes apply to particular diagnostics only!
12624 ///
12625 /// \returns diagnostic %select index.
12626 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12627   switch (Tag) {
12628   case TTK_Struct: return 0;
12629   case TTK_Interface: return 1;
12630   case TTK_Class:  return 2;
12631   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12632   }
12633 }
12634 
12635 /// \brief Determine if tag kind is a class-key compatible with
12636 /// class for redeclaration (class, struct, or __interface).
12637 ///
12638 /// \returns true iff the tag kind is compatible.
12639 static bool isClassCompatTagKind(TagTypeKind Tag)
12640 {
12641   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12642 }
12643 
12644 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12645                                              TagTypeKind TTK) {
12646   if (isa<TypedefDecl>(PrevDecl))
12647     return NTK_Typedef;
12648   else if (isa<TypeAliasDecl>(PrevDecl))
12649     return NTK_TypeAlias;
12650   else if (isa<ClassTemplateDecl>(PrevDecl))
12651     return NTK_Template;
12652   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12653     return NTK_TypeAliasTemplate;
12654   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12655     return NTK_TemplateTemplateArgument;
12656   switch (TTK) {
12657   case TTK_Struct:
12658   case TTK_Interface:
12659   case TTK_Class:
12660     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12661   case TTK_Union:
12662     return NTK_NonUnion;
12663   case TTK_Enum:
12664     return NTK_NonEnum;
12665   }
12666   llvm_unreachable("invalid TTK");
12667 }
12668 
12669 /// \brief Determine whether a tag with a given kind is acceptable
12670 /// as a redeclaration of the given tag declaration.
12671 ///
12672 /// \returns true if the new tag kind is acceptable, false otherwise.
12673 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12674                                         TagTypeKind NewTag, bool isDefinition,
12675                                         SourceLocation NewTagLoc,
12676                                         const IdentifierInfo *Name) {
12677   // C++ [dcl.type.elab]p3:
12678   //   The class-key or enum keyword present in the
12679   //   elaborated-type-specifier shall agree in kind with the
12680   //   declaration to which the name in the elaborated-type-specifier
12681   //   refers. This rule also applies to the form of
12682   //   elaborated-type-specifier that declares a class-name or
12683   //   friend class since it can be construed as referring to the
12684   //   definition of the class. Thus, in any
12685   //   elaborated-type-specifier, the enum keyword shall be used to
12686   //   refer to an enumeration (7.2), the union class-key shall be
12687   //   used to refer to a union (clause 9), and either the class or
12688   //   struct class-key shall be used to refer to a class (clause 9)
12689   //   declared using the class or struct class-key.
12690   TagTypeKind OldTag = Previous->getTagKind();
12691   if (!isDefinition || !isClassCompatTagKind(NewTag))
12692     if (OldTag == NewTag)
12693       return true;
12694 
12695   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12696     // Warn about the struct/class tag mismatch.
12697     bool isTemplate = false;
12698     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12699       isTemplate = Record->getDescribedClassTemplate();
12700 
12701     if (!ActiveTemplateInstantiations.empty()) {
12702       // In a template instantiation, do not offer fix-its for tag mismatches
12703       // since they usually mess up the template instead of fixing the problem.
12704       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12705         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12706         << getRedeclDiagFromTagKind(OldTag);
12707       return true;
12708     }
12709 
12710     if (isDefinition) {
12711       // On definitions, check previous tags and issue a fix-it for each
12712       // one that doesn't match the current tag.
12713       if (Previous->getDefinition()) {
12714         // Don't suggest fix-its for redefinitions.
12715         return true;
12716       }
12717 
12718       bool previousMismatch = false;
12719       for (auto I : Previous->redecls()) {
12720         if (I->getTagKind() != NewTag) {
12721           if (!previousMismatch) {
12722             previousMismatch = true;
12723             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12724               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12725               << getRedeclDiagFromTagKind(I->getTagKind());
12726           }
12727           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12728             << getRedeclDiagFromTagKind(NewTag)
12729             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12730                  TypeWithKeyword::getTagTypeKindName(NewTag));
12731         }
12732       }
12733       return true;
12734     }
12735 
12736     // Check for a previous definition.  If current tag and definition
12737     // are same type, do nothing.  If no definition, but disagree with
12738     // with previous tag type, give a warning, but no fix-it.
12739     const TagDecl *Redecl = Previous->getDefinition() ?
12740                             Previous->getDefinition() : Previous;
12741     if (Redecl->getTagKind() == NewTag) {
12742       return true;
12743     }
12744 
12745     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12746       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12747       << getRedeclDiagFromTagKind(OldTag);
12748     Diag(Redecl->getLocation(), diag::note_previous_use);
12749 
12750     // If there is a previous definition, suggest a fix-it.
12751     if (Previous->getDefinition()) {
12752         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12753           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12754           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12755                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12756     }
12757 
12758     return true;
12759   }
12760   return false;
12761 }
12762 
12763 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12764 /// from an outer enclosing namespace or file scope inside a friend declaration.
12765 /// This should provide the commented out code in the following snippet:
12766 ///   namespace N {
12767 ///     struct X;
12768 ///     namespace M {
12769 ///       struct Y { friend struct /*N::*/ X; };
12770 ///     }
12771 ///   }
12772 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12773                                          SourceLocation NameLoc) {
12774   // While the decl is in a namespace, do repeated lookup of that name and see
12775   // if we get the same namespace back.  If we do not, continue until
12776   // translation unit scope, at which point we have a fully qualified NNS.
12777   SmallVector<IdentifierInfo *, 4> Namespaces;
12778   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12779   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12780     // This tag should be declared in a namespace, which can only be enclosed by
12781     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12782     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12783     if (!Namespace || Namespace->isAnonymousNamespace())
12784       return FixItHint();
12785     IdentifierInfo *II = Namespace->getIdentifier();
12786     Namespaces.push_back(II);
12787     NamedDecl *Lookup = SemaRef.LookupSingleName(
12788         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12789     if (Lookup == Namespace)
12790       break;
12791   }
12792 
12793   // Once we have all the namespaces, reverse them to go outermost first, and
12794   // build an NNS.
12795   SmallString<64> Insertion;
12796   llvm::raw_svector_ostream OS(Insertion);
12797   if (DC->isTranslationUnit())
12798     OS << "::";
12799   std::reverse(Namespaces.begin(), Namespaces.end());
12800   for (auto *II : Namespaces)
12801     OS << II->getName() << "::";
12802   return FixItHint::CreateInsertion(NameLoc, Insertion);
12803 }
12804 
12805 /// \brief Determine whether a tag originally declared in context \p OldDC can
12806 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12807 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12808 /// using-declaration).
12809 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12810                                          DeclContext *NewDC) {
12811   OldDC = OldDC->getRedeclContext();
12812   NewDC = NewDC->getRedeclContext();
12813 
12814   if (OldDC->Equals(NewDC))
12815     return true;
12816 
12817   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12818   // encloses the other).
12819   if (S.getLangOpts().MSVCCompat &&
12820       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12821     return true;
12822 
12823   return false;
12824 }
12825 
12826 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12827 /// former case, Name will be non-null.  In the later case, Name will be null.
12828 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12829 /// reference/declaration/definition of a tag.
12830 ///
12831 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12832 /// trailing-type-specifier) other than one in an alias-declaration.
12833 ///
12834 /// \param SkipBody If non-null, will be set to indicate if the caller should
12835 /// skip the definition of this tag and treat it as if it were a declaration.
12836 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12837                      SourceLocation KWLoc, CXXScopeSpec &SS,
12838                      IdentifierInfo *Name, SourceLocation NameLoc,
12839                      AttributeList *Attr, AccessSpecifier AS,
12840                      SourceLocation ModulePrivateLoc,
12841                      MultiTemplateParamsArg TemplateParameterLists,
12842                      bool &OwnedDecl, bool &IsDependent,
12843                      SourceLocation ScopedEnumKWLoc,
12844                      bool ScopedEnumUsesClassTag,
12845                      TypeResult UnderlyingType,
12846                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12847   // If this is not a definition, it must have a name.
12848   IdentifierInfo *OrigName = Name;
12849   assert((Name != nullptr || TUK == TUK_Definition) &&
12850          "Nameless record must be a definition!");
12851   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12852 
12853   OwnedDecl = false;
12854   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12855   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12856 
12857   // FIXME: Check member specializations more carefully.
12858   bool isMemberSpecialization = false;
12859   bool Invalid = false;
12860 
12861   // We only need to do this matching if we have template parameters
12862   // or a scope specifier, which also conveniently avoids this work
12863   // for non-C++ cases.
12864   if (TemplateParameterLists.size() > 0 ||
12865       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12866     if (TemplateParameterList *TemplateParams =
12867             MatchTemplateParametersToScopeSpecifier(
12868                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12869                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12870       if (Kind == TTK_Enum) {
12871         Diag(KWLoc, diag::err_enum_template);
12872         return nullptr;
12873       }
12874 
12875       if (TemplateParams->size() > 0) {
12876         // This is a declaration or definition of a class template (which may
12877         // be a member of another template).
12878 
12879         if (Invalid)
12880           return nullptr;
12881 
12882         OwnedDecl = false;
12883         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12884                                                SS, Name, NameLoc, Attr,
12885                                                TemplateParams, AS,
12886                                                ModulePrivateLoc,
12887                                                /*FriendLoc*/SourceLocation(),
12888                                                TemplateParameterLists.size()-1,
12889                                                TemplateParameterLists.data(),
12890                                                SkipBody);
12891         return Result.get();
12892       } else {
12893         // The "template<>" header is extraneous.
12894         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12895           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12896         isMemberSpecialization = true;
12897       }
12898     }
12899   }
12900 
12901   // Figure out the underlying type if this a enum declaration. We need to do
12902   // this early, because it's needed to detect if this is an incompatible
12903   // redeclaration.
12904   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12905   bool EnumUnderlyingIsImplicit = false;
12906 
12907   if (Kind == TTK_Enum) {
12908     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12909       // No underlying type explicitly specified, or we failed to parse the
12910       // type, default to int.
12911       EnumUnderlying = Context.IntTy.getTypePtr();
12912     else if (UnderlyingType.get()) {
12913       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12914       // integral type; any cv-qualification is ignored.
12915       TypeSourceInfo *TI = nullptr;
12916       GetTypeFromParser(UnderlyingType.get(), &TI);
12917       EnumUnderlying = TI;
12918 
12919       if (CheckEnumUnderlyingType(TI))
12920         // Recover by falling back to int.
12921         EnumUnderlying = Context.IntTy.getTypePtr();
12922 
12923       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12924                                           UPPC_FixedUnderlyingType))
12925         EnumUnderlying = Context.IntTy.getTypePtr();
12926 
12927     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12928       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12929         // Microsoft enums are always of int type.
12930         EnumUnderlying = Context.IntTy.getTypePtr();
12931         EnumUnderlyingIsImplicit = true;
12932       }
12933     }
12934   }
12935 
12936   DeclContext *SearchDC = CurContext;
12937   DeclContext *DC = CurContext;
12938   bool isStdBadAlloc = false;
12939   bool isStdAlignValT = false;
12940 
12941   RedeclarationKind Redecl = ForRedeclaration;
12942   if (TUK == TUK_Friend || TUK == TUK_Reference)
12943     Redecl = NotForRedeclaration;
12944 
12945   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12946   if (Name && SS.isNotEmpty()) {
12947     // We have a nested-name tag ('struct foo::bar').
12948 
12949     // Check for invalid 'foo::'.
12950     if (SS.isInvalid()) {
12951       Name = nullptr;
12952       goto CreateNewDecl;
12953     }
12954 
12955     // If this is a friend or a reference to a class in a dependent
12956     // context, don't try to make a decl for it.
12957     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12958       DC = computeDeclContext(SS, false);
12959       if (!DC) {
12960         IsDependent = true;
12961         return nullptr;
12962       }
12963     } else {
12964       DC = computeDeclContext(SS, true);
12965       if (!DC) {
12966         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12967           << SS.getRange();
12968         return nullptr;
12969       }
12970     }
12971 
12972     if (RequireCompleteDeclContext(SS, DC))
12973       return nullptr;
12974 
12975     SearchDC = DC;
12976     // Look-up name inside 'foo::'.
12977     LookupQualifiedName(Previous, DC);
12978 
12979     if (Previous.isAmbiguous())
12980       return nullptr;
12981 
12982     if (Previous.empty()) {
12983       // Name lookup did not find anything. However, if the
12984       // nested-name-specifier refers to the current instantiation,
12985       // and that current instantiation has any dependent base
12986       // classes, we might find something at instantiation time: treat
12987       // this as a dependent elaborated-type-specifier.
12988       // But this only makes any sense for reference-like lookups.
12989       if (Previous.wasNotFoundInCurrentInstantiation() &&
12990           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12991         IsDependent = true;
12992         return nullptr;
12993       }
12994 
12995       // A tag 'foo::bar' must already exist.
12996       Diag(NameLoc, diag::err_not_tag_in_scope)
12997         << Kind << Name << DC << SS.getRange();
12998       Name = nullptr;
12999       Invalid = true;
13000       goto CreateNewDecl;
13001     }
13002   } else if (Name) {
13003     // C++14 [class.mem]p14:
13004     //   If T is the name of a class, then each of the following shall have a
13005     //   name different from T:
13006     //    -- every member of class T that is itself a type
13007     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13008         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13009       return nullptr;
13010 
13011     // If this is a named struct, check to see if there was a previous forward
13012     // declaration or definition.
13013     // FIXME: We're looking into outer scopes here, even when we
13014     // shouldn't be. Doing so can result in ambiguities that we
13015     // shouldn't be diagnosing.
13016     LookupName(Previous, S);
13017 
13018     // When declaring or defining a tag, ignore ambiguities introduced
13019     // by types using'ed into this scope.
13020     if (Previous.isAmbiguous() &&
13021         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13022       LookupResult::Filter F = Previous.makeFilter();
13023       while (F.hasNext()) {
13024         NamedDecl *ND = F.next();
13025         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13026                 SearchDC->getRedeclContext()))
13027           F.erase();
13028       }
13029       F.done();
13030     }
13031 
13032     // C++11 [namespace.memdef]p3:
13033     //   If the name in a friend declaration is neither qualified nor
13034     //   a template-id and the declaration is a function or an
13035     //   elaborated-type-specifier, the lookup to determine whether
13036     //   the entity has been previously declared shall not consider
13037     //   any scopes outside the innermost enclosing namespace.
13038     //
13039     // MSVC doesn't implement the above rule for types, so a friend tag
13040     // declaration may be a redeclaration of a type declared in an enclosing
13041     // scope.  They do implement this rule for friend functions.
13042     //
13043     // Does it matter that this should be by scope instead of by
13044     // semantic context?
13045     if (!Previous.empty() && TUK == TUK_Friend) {
13046       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13047       LookupResult::Filter F = Previous.makeFilter();
13048       bool FriendSawTagOutsideEnclosingNamespace = false;
13049       while (F.hasNext()) {
13050         NamedDecl *ND = F.next();
13051         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13052         if (DC->isFileContext() &&
13053             !EnclosingNS->Encloses(ND->getDeclContext())) {
13054           if (getLangOpts().MSVCCompat)
13055             FriendSawTagOutsideEnclosingNamespace = true;
13056           else
13057             F.erase();
13058         }
13059       }
13060       F.done();
13061 
13062       // Diagnose this MSVC extension in the easy case where lookup would have
13063       // unambiguously found something outside the enclosing namespace.
13064       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13065         NamedDecl *ND = Previous.getFoundDecl();
13066         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13067             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13068       }
13069     }
13070 
13071     // Note:  there used to be some attempt at recovery here.
13072     if (Previous.isAmbiguous())
13073       return nullptr;
13074 
13075     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13076       // FIXME: This makes sure that we ignore the contexts associated
13077       // with C structs, unions, and enums when looking for a matching
13078       // tag declaration or definition. See the similar lookup tweak
13079       // in Sema::LookupName; is there a better way to deal with this?
13080       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13081         SearchDC = SearchDC->getParent();
13082     }
13083   }
13084 
13085   if (Previous.isSingleResult() &&
13086       Previous.getFoundDecl()->isTemplateParameter()) {
13087     // Maybe we will complain about the shadowed template parameter.
13088     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13089     // Just pretend that we didn't see the previous declaration.
13090     Previous.clear();
13091   }
13092 
13093   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13094       DC->Equals(getStdNamespace())) {
13095     if (Name->isStr("bad_alloc")) {
13096       // This is a declaration of or a reference to "std::bad_alloc".
13097       isStdBadAlloc = true;
13098 
13099       // If std::bad_alloc has been implicitly declared (but made invisible to
13100       // name lookup), fill in this implicit declaration as the previous
13101       // declaration, so that the declarations get chained appropriately.
13102       if (Previous.empty() && StdBadAlloc)
13103         Previous.addDecl(getStdBadAlloc());
13104     } else if (Name->isStr("align_val_t")) {
13105       isStdAlignValT = true;
13106       if (Previous.empty() && StdAlignValT)
13107         Previous.addDecl(getStdAlignValT());
13108     }
13109   }
13110 
13111   // If we didn't find a previous declaration, and this is a reference
13112   // (or friend reference), move to the correct scope.  In C++, we
13113   // also need to do a redeclaration lookup there, just in case
13114   // there's a shadow friend decl.
13115   if (Name && Previous.empty() &&
13116       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13117     if (Invalid) goto CreateNewDecl;
13118     assert(SS.isEmpty());
13119 
13120     if (TUK == TUK_Reference) {
13121       // C++ [basic.scope.pdecl]p5:
13122       //   -- for an elaborated-type-specifier of the form
13123       //
13124       //          class-key identifier
13125       //
13126       //      if the elaborated-type-specifier is used in the
13127       //      decl-specifier-seq or parameter-declaration-clause of a
13128       //      function defined in namespace scope, the identifier is
13129       //      declared as a class-name in the namespace that contains
13130       //      the declaration; otherwise, except as a friend
13131       //      declaration, the identifier is declared in the smallest
13132       //      non-class, non-function-prototype scope that contains the
13133       //      declaration.
13134       //
13135       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13136       // C structs and unions.
13137       //
13138       // It is an error in C++ to declare (rather than define) an enum
13139       // type, including via an elaborated type specifier.  We'll
13140       // diagnose that later; for now, declare the enum in the same
13141       // scope as we would have picked for any other tag type.
13142       //
13143       // GNU C also supports this behavior as part of its incomplete
13144       // enum types extension, while GNU C++ does not.
13145       //
13146       // Find the context where we'll be declaring the tag.
13147       // FIXME: We would like to maintain the current DeclContext as the
13148       // lexical context,
13149       SearchDC = getTagInjectionContext(SearchDC);
13150 
13151       // Find the scope where we'll be declaring the tag.
13152       S = getTagInjectionScope(S, getLangOpts());
13153     } else {
13154       assert(TUK == TUK_Friend);
13155       // C++ [namespace.memdef]p3:
13156       //   If a friend declaration in a non-local class first declares a
13157       //   class or function, the friend class or function is a member of
13158       //   the innermost enclosing namespace.
13159       SearchDC = SearchDC->getEnclosingNamespaceContext();
13160     }
13161 
13162     // In C++, we need to do a redeclaration lookup to properly
13163     // diagnose some problems.
13164     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13165     // hidden declaration so that we don't get ambiguity errors when using a
13166     // type declared by an elaborated-type-specifier.  In C that is not correct
13167     // and we should instead merge compatible types found by lookup.
13168     if (getLangOpts().CPlusPlus) {
13169       Previous.setRedeclarationKind(ForRedeclaration);
13170       LookupQualifiedName(Previous, SearchDC);
13171     } else {
13172       Previous.setRedeclarationKind(ForRedeclaration);
13173       LookupName(Previous, S);
13174     }
13175   }
13176 
13177   // If we have a known previous declaration to use, then use it.
13178   if (Previous.empty() && SkipBody && SkipBody->Previous)
13179     Previous.addDecl(SkipBody->Previous);
13180 
13181   if (!Previous.empty()) {
13182     NamedDecl *PrevDecl = Previous.getFoundDecl();
13183     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13184 
13185     // It's okay to have a tag decl in the same scope as a typedef
13186     // which hides a tag decl in the same scope.  Finding this
13187     // insanity with a redeclaration lookup can only actually happen
13188     // in C++.
13189     //
13190     // This is also okay for elaborated-type-specifiers, which is
13191     // technically forbidden by the current standard but which is
13192     // okay according to the likely resolution of an open issue;
13193     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13194     if (getLangOpts().CPlusPlus) {
13195       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13196         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13197           TagDecl *Tag = TT->getDecl();
13198           if (Tag->getDeclName() == Name &&
13199               Tag->getDeclContext()->getRedeclContext()
13200                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13201             PrevDecl = Tag;
13202             Previous.clear();
13203             Previous.addDecl(Tag);
13204             Previous.resolveKind();
13205           }
13206         }
13207       }
13208     }
13209 
13210     // If this is a redeclaration of a using shadow declaration, it must
13211     // declare a tag in the same context. In MSVC mode, we allow a
13212     // redefinition if either context is within the other.
13213     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13214       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13215       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13216           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13217           !(OldTag && isAcceptableTagRedeclContext(
13218                           *this, OldTag->getDeclContext(), SearchDC))) {
13219         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13220         Diag(Shadow->getTargetDecl()->getLocation(),
13221              diag::note_using_decl_target);
13222         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13223             << 0;
13224         // Recover by ignoring the old declaration.
13225         Previous.clear();
13226         goto CreateNewDecl;
13227       }
13228     }
13229 
13230     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13231       // If this is a use of a previous tag, or if the tag is already declared
13232       // in the same scope (so that the definition/declaration completes or
13233       // rementions the tag), reuse the decl.
13234       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13235           isDeclInScope(DirectPrevDecl, SearchDC, S,
13236                         SS.isNotEmpty() || isMemberSpecialization)) {
13237         // Make sure that this wasn't declared as an enum and now used as a
13238         // struct or something similar.
13239         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13240                                           TUK == TUK_Definition, KWLoc,
13241                                           Name)) {
13242           bool SafeToContinue
13243             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13244                Kind != TTK_Enum);
13245           if (SafeToContinue)
13246             Diag(KWLoc, diag::err_use_with_wrong_tag)
13247               << Name
13248               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13249                                               PrevTagDecl->getKindName());
13250           else
13251             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13252           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13253 
13254           if (SafeToContinue)
13255             Kind = PrevTagDecl->getTagKind();
13256           else {
13257             // Recover by making this an anonymous redefinition.
13258             Name = nullptr;
13259             Previous.clear();
13260             Invalid = true;
13261           }
13262         }
13263 
13264         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13265           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13266 
13267           // If this is an elaborated-type-specifier for a scoped enumeration,
13268           // the 'class' keyword is not necessary and not permitted.
13269           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13270             if (ScopedEnum)
13271               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13272                 << PrevEnum->isScoped()
13273                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13274             return PrevTagDecl;
13275           }
13276 
13277           QualType EnumUnderlyingTy;
13278           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13279             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13280           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13281             EnumUnderlyingTy = QualType(T, 0);
13282 
13283           // All conflicts with previous declarations are recovered by
13284           // returning the previous declaration, unless this is a definition,
13285           // in which case we want the caller to bail out.
13286           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13287                                      ScopedEnum, EnumUnderlyingTy,
13288                                      EnumUnderlyingIsImplicit, PrevEnum))
13289             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13290         }
13291 
13292         // C++11 [class.mem]p1:
13293         //   A member shall not be declared twice in the member-specification,
13294         //   except that a nested class or member class template can be declared
13295         //   and then later defined.
13296         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13297             S->isDeclScope(PrevDecl)) {
13298           Diag(NameLoc, diag::ext_member_redeclared);
13299           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13300         }
13301 
13302         if (!Invalid) {
13303           // If this is a use, just return the declaration we found, unless
13304           // we have attributes.
13305           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13306             if (Attr) {
13307               // FIXME: Diagnose these attributes. For now, we create a new
13308               // declaration to hold them.
13309             } else if (TUK == TUK_Reference &&
13310                        (PrevTagDecl->getFriendObjectKind() ==
13311                             Decl::FOK_Undeclared ||
13312                         PP.getModuleContainingLocation(
13313                             PrevDecl->getLocation()) !=
13314                             PP.getModuleContainingLocation(KWLoc)) &&
13315                        SS.isEmpty()) {
13316               // This declaration is a reference to an existing entity, but
13317               // has different visibility from that entity: it either makes
13318               // a friend visible or it makes a type visible in a new module.
13319               // In either case, create a new declaration. We only do this if
13320               // the declaration would have meant the same thing if no prior
13321               // declaration were found, that is, if it was found in the same
13322               // scope where we would have injected a declaration.
13323               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13324                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13325                 return PrevTagDecl;
13326               // This is in the injected scope, create a new declaration in
13327               // that scope.
13328               S = getTagInjectionScope(S, getLangOpts());
13329             } else {
13330               return PrevTagDecl;
13331             }
13332           }
13333 
13334           // Diagnose attempts to redefine a tag.
13335           if (TUK == TUK_Definition) {
13336             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13337               // If we're defining a specialization and the previous definition
13338               // is from an implicit instantiation, don't emit an error
13339               // here; we'll catch this in the general case below.
13340               bool IsExplicitSpecializationAfterInstantiation = false;
13341               if (isMemberSpecialization) {
13342                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13343                   IsExplicitSpecializationAfterInstantiation =
13344                     RD->getTemplateSpecializationKind() !=
13345                     TSK_ExplicitSpecialization;
13346                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13347                   IsExplicitSpecializationAfterInstantiation =
13348                     ED->getTemplateSpecializationKind() !=
13349                     TSK_ExplicitSpecialization;
13350               }
13351 
13352               NamedDecl *Hidden = nullptr;
13353               if (SkipBody && getLangOpts().CPlusPlus &&
13354                   !hasVisibleDefinition(Def, &Hidden)) {
13355                 // There is a definition of this tag, but it is not visible. We
13356                 // explicitly make use of C++'s one definition rule here, and
13357                 // assume that this definition is identical to the hidden one
13358                 // we already have. Make the existing definition visible and
13359                 // use it in place of this one.
13360                 SkipBody->ShouldSkip = true;
13361                 makeMergedDefinitionVisible(Hidden, KWLoc);
13362                 return Def;
13363               } else if (!IsExplicitSpecializationAfterInstantiation) {
13364                 // A redeclaration in function prototype scope in C isn't
13365                 // visible elsewhere, so merely issue a warning.
13366                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13367                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13368                 else
13369                   Diag(NameLoc, diag::err_redefinition) << Name;
13370                 Diag(Def->getLocation(), diag::note_previous_definition);
13371                 // If this is a redefinition, recover by making this
13372                 // struct be anonymous, which will make any later
13373                 // references get the previous definition.
13374                 Name = nullptr;
13375                 Previous.clear();
13376                 Invalid = true;
13377               }
13378             } else {
13379               // If the type is currently being defined, complain
13380               // about a nested redefinition.
13381               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13382               if (TD->isBeingDefined()) {
13383                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13384                 Diag(PrevTagDecl->getLocation(),
13385                      diag::note_previous_definition);
13386                 Name = nullptr;
13387                 Previous.clear();
13388                 Invalid = true;
13389               }
13390             }
13391 
13392             // Okay, this is definition of a previously declared or referenced
13393             // tag. We're going to create a new Decl for it.
13394           }
13395 
13396           // Okay, we're going to make a redeclaration.  If this is some kind
13397           // of reference, make sure we build the redeclaration in the same DC
13398           // as the original, and ignore the current access specifier.
13399           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13400             SearchDC = PrevTagDecl->getDeclContext();
13401             AS = AS_none;
13402           }
13403         }
13404         // If we get here we have (another) forward declaration or we
13405         // have a definition.  Just create a new decl.
13406 
13407       } else {
13408         // If we get here, this is a definition of a new tag type in a nested
13409         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13410         // new decl/type.  We set PrevDecl to NULL so that the entities
13411         // have distinct types.
13412         Previous.clear();
13413       }
13414       // If we get here, we're going to create a new Decl. If PrevDecl
13415       // is non-NULL, it's a definition of the tag declared by
13416       // PrevDecl. If it's NULL, we have a new definition.
13417 
13418     // Otherwise, PrevDecl is not a tag, but was found with tag
13419     // lookup.  This is only actually possible in C++, where a few
13420     // things like templates still live in the tag namespace.
13421     } else {
13422       // Use a better diagnostic if an elaborated-type-specifier
13423       // found the wrong kind of type on the first
13424       // (non-redeclaration) lookup.
13425       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13426           !Previous.isForRedeclaration()) {
13427         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13428         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13429                                                        << Kind;
13430         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13431         Invalid = true;
13432 
13433       // Otherwise, only diagnose if the declaration is in scope.
13434       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13435                                 SS.isNotEmpty() || isMemberSpecialization)) {
13436         // do nothing
13437 
13438       // Diagnose implicit declarations introduced by elaborated types.
13439       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13440         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13441         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13442         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13443         Invalid = true;
13444 
13445       // Otherwise it's a declaration.  Call out a particularly common
13446       // case here.
13447       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13448         unsigned Kind = 0;
13449         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13450         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13451           << Name << Kind << TND->getUnderlyingType();
13452         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13453         Invalid = true;
13454 
13455       // Otherwise, diagnose.
13456       } else {
13457         // The tag name clashes with something else in the target scope,
13458         // issue an error and recover by making this tag be anonymous.
13459         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13460         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13461         Name = nullptr;
13462         Invalid = true;
13463       }
13464 
13465       // The existing declaration isn't relevant to us; we're in a
13466       // new scope, so clear out the previous declaration.
13467       Previous.clear();
13468     }
13469   }
13470 
13471 CreateNewDecl:
13472 
13473   TagDecl *PrevDecl = nullptr;
13474   if (Previous.isSingleResult())
13475     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13476 
13477   // If there is an identifier, use the location of the identifier as the
13478   // location of the decl, otherwise use the location of the struct/union
13479   // keyword.
13480   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13481 
13482   // Otherwise, create a new declaration. If there is a previous
13483   // declaration of the same entity, the two will be linked via
13484   // PrevDecl.
13485   TagDecl *New;
13486 
13487   bool IsForwardReference = false;
13488   if (Kind == TTK_Enum) {
13489     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13490     // enum X { A, B, C } D;    D should chain to X.
13491     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13492                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13493                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13494 
13495     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13496       StdAlignValT = cast<EnumDecl>(New);
13497 
13498     // If this is an undefined enum, warn.
13499     if (TUK != TUK_Definition && !Invalid) {
13500       TagDecl *Def;
13501       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13502           cast<EnumDecl>(New)->isFixed()) {
13503         // C++0x: 7.2p2: opaque-enum-declaration.
13504         // Conflicts are diagnosed above. Do nothing.
13505       }
13506       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13507         Diag(Loc, diag::ext_forward_ref_enum_def)
13508           << New;
13509         Diag(Def->getLocation(), diag::note_previous_definition);
13510       } else {
13511         unsigned DiagID = diag::ext_forward_ref_enum;
13512         if (getLangOpts().MSVCCompat)
13513           DiagID = diag::ext_ms_forward_ref_enum;
13514         else if (getLangOpts().CPlusPlus)
13515           DiagID = diag::err_forward_ref_enum;
13516         Diag(Loc, DiagID);
13517 
13518         // If this is a forward-declared reference to an enumeration, make a
13519         // note of it; we won't actually be introducing the declaration into
13520         // the declaration context.
13521         if (TUK == TUK_Reference)
13522           IsForwardReference = true;
13523       }
13524     }
13525 
13526     if (EnumUnderlying) {
13527       EnumDecl *ED = cast<EnumDecl>(New);
13528       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13529         ED->setIntegerTypeSourceInfo(TI);
13530       else
13531         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13532       ED->setPromotionType(ED->getIntegerType());
13533     }
13534   } else {
13535     // struct/union/class
13536 
13537     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13538     // struct X { int A; } D;    D should chain to X.
13539     if (getLangOpts().CPlusPlus) {
13540       // FIXME: Look for a way to use RecordDecl for simple structs.
13541       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13542                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13543 
13544       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13545         StdBadAlloc = cast<CXXRecordDecl>(New);
13546     } else
13547       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13548                                cast_or_null<RecordDecl>(PrevDecl));
13549   }
13550 
13551   // C++11 [dcl.type]p3:
13552   //   A type-specifier-seq shall not define a class or enumeration [...].
13553   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13554     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13555       << Context.getTagDeclType(New);
13556     Invalid = true;
13557   }
13558 
13559   // Maybe add qualifier info.
13560   if (SS.isNotEmpty()) {
13561     if (SS.isSet()) {
13562       // If this is either a declaration or a definition, check the
13563       // nested-name-specifier against the current context. We don't do this
13564       // for explicit specializations, because they have similar checking
13565       // (with more specific diagnostics) in the call to
13566       // CheckMemberSpecialization, below.
13567       if (!isMemberSpecialization &&
13568           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13569           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13570         Invalid = true;
13571 
13572       New->setQualifierInfo(SS.getWithLocInContext(Context));
13573       if (TemplateParameterLists.size() > 0) {
13574         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13575       }
13576     }
13577     else
13578       Invalid = true;
13579   }
13580 
13581   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13582     // Add alignment attributes if necessary; these attributes are checked when
13583     // the ASTContext lays out the structure.
13584     //
13585     // It is important for implementing the correct semantics that this
13586     // happen here (in act on tag decl). The #pragma pack stack is
13587     // maintained as a result of parser callbacks which can occur at
13588     // many points during the parsing of a struct declaration (because
13589     // the #pragma tokens are effectively skipped over during the
13590     // parsing of the struct).
13591     if (TUK == TUK_Definition) {
13592       AddAlignmentAttributesForRecord(RD);
13593       AddMsStructLayoutForRecord(RD);
13594     }
13595   }
13596 
13597   if (ModulePrivateLoc.isValid()) {
13598     if (isMemberSpecialization)
13599       Diag(New->getLocation(), diag::err_module_private_specialization)
13600         << 2
13601         << FixItHint::CreateRemoval(ModulePrivateLoc);
13602     // __module_private__ does not apply to local classes. However, we only
13603     // diagnose this as an error when the declaration specifiers are
13604     // freestanding. Here, we just ignore the __module_private__.
13605     else if (!SearchDC->isFunctionOrMethod())
13606       New->setModulePrivate();
13607   }
13608 
13609   // If this is a specialization of a member class (of a class template),
13610   // check the specialization.
13611   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13612     Invalid = true;
13613 
13614   // If we're declaring or defining a tag in function prototype scope in C,
13615   // note that this type can only be used within the function and add it to
13616   // the list of decls to inject into the function definition scope.
13617   if ((Name || Kind == TTK_Enum) &&
13618       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13619     if (getLangOpts().CPlusPlus) {
13620       // C++ [dcl.fct]p6:
13621       //   Types shall not be defined in return or parameter types.
13622       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13623         Diag(Loc, diag::err_type_defined_in_param_type)
13624             << Name;
13625         Invalid = true;
13626       }
13627     } else if (!PrevDecl) {
13628       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13629     }
13630   }
13631 
13632   if (Invalid)
13633     New->setInvalidDecl();
13634 
13635   if (Attr)
13636     ProcessDeclAttributeList(S, New, Attr);
13637 
13638   // Set the lexical context. If the tag has a C++ scope specifier, the
13639   // lexical context will be different from the semantic context.
13640   New->setLexicalDeclContext(CurContext);
13641 
13642   // Mark this as a friend decl if applicable.
13643   // In Microsoft mode, a friend declaration also acts as a forward
13644   // declaration so we always pass true to setObjectOfFriendDecl to make
13645   // the tag name visible.
13646   if (TUK == TUK_Friend)
13647     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13648 
13649   // Set the access specifier.
13650   if (!Invalid && SearchDC->isRecord())
13651     SetMemberAccessSpecifier(New, PrevDecl, AS);
13652 
13653   if (TUK == TUK_Definition)
13654     New->startDefinition();
13655 
13656   // If this has an identifier, add it to the scope stack.
13657   if (TUK == TUK_Friend) {
13658     // We might be replacing an existing declaration in the lookup tables;
13659     // if so, borrow its access specifier.
13660     if (PrevDecl)
13661       New->setAccess(PrevDecl->getAccess());
13662 
13663     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13664     DC->makeDeclVisibleInContext(New);
13665     if (Name) // can be null along some error paths
13666       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13667         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13668   } else if (Name) {
13669     S = getNonFieldDeclScope(S);
13670     PushOnScopeChains(New, S, !IsForwardReference);
13671     if (IsForwardReference)
13672       SearchDC->makeDeclVisibleInContext(New);
13673   } else {
13674     CurContext->addDecl(New);
13675   }
13676 
13677   // If this is the C FILE type, notify the AST context.
13678   if (IdentifierInfo *II = New->getIdentifier())
13679     if (!New->isInvalidDecl() &&
13680         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13681         II->isStr("FILE"))
13682       Context.setFILEDecl(New);
13683 
13684   if (PrevDecl)
13685     mergeDeclAttributes(New, PrevDecl);
13686 
13687   // If there's a #pragma GCC visibility in scope, set the visibility of this
13688   // record.
13689   AddPushedVisibilityAttribute(New);
13690 
13691   OwnedDecl = true;
13692   // In C++, don't return an invalid declaration. We can't recover well from
13693   // the cases where we make the type anonymous.
13694   if (Invalid && getLangOpts().CPlusPlus) {
13695     if (New->isBeingDefined())
13696       if (auto RD = dyn_cast<RecordDecl>(New))
13697         RD->completeDefinition();
13698     return nullptr;
13699   } else {
13700     return New;
13701   }
13702 }
13703 
13704 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13705   AdjustDeclIfTemplate(TagD);
13706   TagDecl *Tag = cast<TagDecl>(TagD);
13707 
13708   // Enter the tag context.
13709   PushDeclContext(S, Tag);
13710 
13711   ActOnDocumentableDecl(TagD);
13712 
13713   // If there's a #pragma GCC visibility in scope, set the visibility of this
13714   // record.
13715   AddPushedVisibilityAttribute(Tag);
13716 }
13717 
13718 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13719   assert(isa<ObjCContainerDecl>(IDecl) &&
13720          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13721   DeclContext *OCD = cast<DeclContext>(IDecl);
13722   assert(getContainingDC(OCD) == CurContext &&
13723       "The next DeclContext should be lexically contained in the current one.");
13724   CurContext = OCD;
13725   return IDecl;
13726 }
13727 
13728 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13729                                            SourceLocation FinalLoc,
13730                                            bool IsFinalSpelledSealed,
13731                                            SourceLocation LBraceLoc) {
13732   AdjustDeclIfTemplate(TagD);
13733   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13734 
13735   FieldCollector->StartClass();
13736 
13737   if (!Record->getIdentifier())
13738     return;
13739 
13740   if (FinalLoc.isValid())
13741     Record->addAttr(new (Context)
13742                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13743 
13744   // C++ [class]p2:
13745   //   [...] The class-name is also inserted into the scope of the
13746   //   class itself; this is known as the injected-class-name. For
13747   //   purposes of access checking, the injected-class-name is treated
13748   //   as if it were a public member name.
13749   CXXRecordDecl *InjectedClassName
13750     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13751                             Record->getLocStart(), Record->getLocation(),
13752                             Record->getIdentifier(),
13753                             /*PrevDecl=*/nullptr,
13754                             /*DelayTypeCreation=*/true);
13755   Context.getTypeDeclType(InjectedClassName, Record);
13756   InjectedClassName->setImplicit();
13757   InjectedClassName->setAccess(AS_public);
13758   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13759       InjectedClassName->setDescribedClassTemplate(Template);
13760   PushOnScopeChains(InjectedClassName, S);
13761   assert(InjectedClassName->isInjectedClassName() &&
13762          "Broken injected-class-name");
13763 }
13764 
13765 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13766                                     SourceRange BraceRange) {
13767   AdjustDeclIfTemplate(TagD);
13768   TagDecl *Tag = cast<TagDecl>(TagD);
13769   Tag->setBraceRange(BraceRange);
13770 
13771   // Make sure we "complete" the definition even it is invalid.
13772   if (Tag->isBeingDefined()) {
13773     assert(Tag->isInvalidDecl() && "We should already have completed it");
13774     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13775       RD->completeDefinition();
13776   }
13777 
13778   if (isa<CXXRecordDecl>(Tag))
13779     FieldCollector->FinishClass();
13780 
13781   // Exit this scope of this tag's definition.
13782   PopDeclContext();
13783 
13784   if (getCurLexicalContext()->isObjCContainer() &&
13785       Tag->getDeclContext()->isFileContext())
13786     Tag->setTopLevelDeclInObjCContainer();
13787 
13788   // Notify the consumer that we've defined a tag.
13789   if (!Tag->isInvalidDecl())
13790     Consumer.HandleTagDeclDefinition(Tag);
13791 }
13792 
13793 void Sema::ActOnObjCContainerFinishDefinition() {
13794   // Exit this scope of this interface definition.
13795   PopDeclContext();
13796 }
13797 
13798 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13799   assert(DC == CurContext && "Mismatch of container contexts");
13800   OriginalLexicalContext = DC;
13801   ActOnObjCContainerFinishDefinition();
13802 }
13803 
13804 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13805   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13806   OriginalLexicalContext = nullptr;
13807 }
13808 
13809 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13810   AdjustDeclIfTemplate(TagD);
13811   TagDecl *Tag = cast<TagDecl>(TagD);
13812   Tag->setInvalidDecl();
13813 
13814   // Make sure we "complete" the definition even it is invalid.
13815   if (Tag->isBeingDefined()) {
13816     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13817       RD->completeDefinition();
13818   }
13819 
13820   // We're undoing ActOnTagStartDefinition here, not
13821   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13822   // the FieldCollector.
13823 
13824   PopDeclContext();
13825 }
13826 
13827 // Note that FieldName may be null for anonymous bitfields.
13828 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13829                                 IdentifierInfo *FieldName,
13830                                 QualType FieldTy, bool IsMsStruct,
13831                                 Expr *BitWidth, bool *ZeroWidth) {
13832   // Default to true; that shouldn't confuse checks for emptiness
13833   if (ZeroWidth)
13834     *ZeroWidth = true;
13835 
13836   // C99 6.7.2.1p4 - verify the field type.
13837   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13838   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13839     // Handle incomplete types with specific error.
13840     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13841       return ExprError();
13842     if (FieldName)
13843       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13844         << FieldName << FieldTy << BitWidth->getSourceRange();
13845     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13846       << FieldTy << BitWidth->getSourceRange();
13847   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13848                                              UPPC_BitFieldWidth))
13849     return ExprError();
13850 
13851   // If the bit-width is type- or value-dependent, don't try to check
13852   // it now.
13853   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13854     return BitWidth;
13855 
13856   llvm::APSInt Value;
13857   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13858   if (ICE.isInvalid())
13859     return ICE;
13860   BitWidth = ICE.get();
13861 
13862   if (Value != 0 && ZeroWidth)
13863     *ZeroWidth = false;
13864 
13865   // Zero-width bitfield is ok for anonymous field.
13866   if (Value == 0 && FieldName)
13867     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13868 
13869   if (Value.isSigned() && Value.isNegative()) {
13870     if (FieldName)
13871       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13872                << FieldName << Value.toString(10);
13873     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13874       << Value.toString(10);
13875   }
13876 
13877   if (!FieldTy->isDependentType()) {
13878     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13879     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13880     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13881 
13882     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13883     // ABI.
13884     bool CStdConstraintViolation =
13885         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13886     bool MSBitfieldViolation =
13887         Value.ugt(TypeStorageSize) &&
13888         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13889     if (CStdConstraintViolation || MSBitfieldViolation) {
13890       unsigned DiagWidth =
13891           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13892       if (FieldName)
13893         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13894                << FieldName << (unsigned)Value.getZExtValue()
13895                << !CStdConstraintViolation << DiagWidth;
13896 
13897       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13898              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13899              << DiagWidth;
13900     }
13901 
13902     // Warn on types where the user might conceivably expect to get all
13903     // specified bits as value bits: that's all integral types other than
13904     // 'bool'.
13905     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13906       if (FieldName)
13907         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13908             << FieldName << (unsigned)Value.getZExtValue()
13909             << (unsigned)TypeWidth;
13910       else
13911         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13912             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13913     }
13914   }
13915 
13916   return BitWidth;
13917 }
13918 
13919 /// ActOnField - Each field of a C struct/union is passed into this in order
13920 /// to create a FieldDecl object for it.
13921 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13922                        Declarator &D, Expr *BitfieldWidth) {
13923   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13924                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13925                                /*InitStyle=*/ICIS_NoInit, AS_public);
13926   return Res;
13927 }
13928 
13929 /// HandleField - Analyze a field of a C struct or a C++ data member.
13930 ///
13931 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13932                              SourceLocation DeclStart,
13933                              Declarator &D, Expr *BitWidth,
13934                              InClassInitStyle InitStyle,
13935                              AccessSpecifier AS) {
13936   if (D.isDecompositionDeclarator()) {
13937     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13938     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13939       << Decomp.getSourceRange();
13940     return nullptr;
13941   }
13942 
13943   IdentifierInfo *II = D.getIdentifier();
13944   SourceLocation Loc = DeclStart;
13945   if (II) Loc = D.getIdentifierLoc();
13946 
13947   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13948   QualType T = TInfo->getType();
13949   if (getLangOpts().CPlusPlus) {
13950     CheckExtraCXXDefaultArguments(D);
13951 
13952     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13953                                         UPPC_DataMemberType)) {
13954       D.setInvalidType();
13955       T = Context.IntTy;
13956       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13957     }
13958   }
13959 
13960   // TR 18037 does not allow fields to be declared with address spaces.
13961   if (T.getQualifiers().hasAddressSpace()) {
13962     Diag(Loc, diag::err_field_with_address_space);
13963     D.setInvalidType();
13964   }
13965 
13966   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13967   // used as structure or union field: image, sampler, event or block types.
13968   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13969                           T->isSamplerT() || T->isBlockPointerType())) {
13970     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13971     D.setInvalidType();
13972   }
13973 
13974   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13975 
13976   if (D.getDeclSpec().isInlineSpecified())
13977     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13978         << getLangOpts().CPlusPlus1z;
13979   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13980     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13981          diag::err_invalid_thread)
13982       << DeclSpec::getSpecifierName(TSCS);
13983 
13984   // Check to see if this name was declared as a member previously
13985   NamedDecl *PrevDecl = nullptr;
13986   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13987   LookupName(Previous, S);
13988   switch (Previous.getResultKind()) {
13989     case LookupResult::Found:
13990     case LookupResult::FoundUnresolvedValue:
13991       PrevDecl = Previous.getAsSingle<NamedDecl>();
13992       break;
13993 
13994     case LookupResult::FoundOverloaded:
13995       PrevDecl = Previous.getRepresentativeDecl();
13996       break;
13997 
13998     case LookupResult::NotFound:
13999     case LookupResult::NotFoundInCurrentInstantiation:
14000     case LookupResult::Ambiguous:
14001       break;
14002   }
14003   Previous.suppressDiagnostics();
14004 
14005   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14006     // Maybe we will complain about the shadowed template parameter.
14007     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14008     // Just pretend that we didn't see the previous declaration.
14009     PrevDecl = nullptr;
14010   }
14011 
14012   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14013     PrevDecl = nullptr;
14014 
14015   bool Mutable
14016     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14017   SourceLocation TSSL = D.getLocStart();
14018   FieldDecl *NewFD
14019     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14020                      TSSL, AS, PrevDecl, &D);
14021 
14022   if (NewFD->isInvalidDecl())
14023     Record->setInvalidDecl();
14024 
14025   if (D.getDeclSpec().isModulePrivateSpecified())
14026     NewFD->setModulePrivate();
14027 
14028   if (NewFD->isInvalidDecl() && PrevDecl) {
14029     // Don't introduce NewFD into scope; there's already something
14030     // with the same name in the same scope.
14031   } else if (II) {
14032     PushOnScopeChains(NewFD, S);
14033   } else
14034     Record->addDecl(NewFD);
14035 
14036   return NewFD;
14037 }
14038 
14039 /// \brief Build a new FieldDecl and check its well-formedness.
14040 ///
14041 /// This routine builds a new FieldDecl given the fields name, type,
14042 /// record, etc. \p PrevDecl should refer to any previous declaration
14043 /// with the same name and in the same scope as the field to be
14044 /// created.
14045 ///
14046 /// \returns a new FieldDecl.
14047 ///
14048 /// \todo The Declarator argument is a hack. It will be removed once
14049 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14050                                 TypeSourceInfo *TInfo,
14051                                 RecordDecl *Record, SourceLocation Loc,
14052                                 bool Mutable, Expr *BitWidth,
14053                                 InClassInitStyle InitStyle,
14054                                 SourceLocation TSSL,
14055                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14056                                 Declarator *D) {
14057   IdentifierInfo *II = Name.getAsIdentifierInfo();
14058   bool InvalidDecl = false;
14059   if (D) InvalidDecl = D->isInvalidType();
14060 
14061   // If we receive a broken type, recover by assuming 'int' and
14062   // marking this declaration as invalid.
14063   if (T.isNull()) {
14064     InvalidDecl = true;
14065     T = Context.IntTy;
14066   }
14067 
14068   QualType EltTy = Context.getBaseElementType(T);
14069   if (!EltTy->isDependentType()) {
14070     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14071       // Fields of incomplete type force their record to be invalid.
14072       Record->setInvalidDecl();
14073       InvalidDecl = true;
14074     } else {
14075       NamedDecl *Def;
14076       EltTy->isIncompleteType(&Def);
14077       if (Def && Def->isInvalidDecl()) {
14078         Record->setInvalidDecl();
14079         InvalidDecl = true;
14080       }
14081     }
14082   }
14083 
14084   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14085   if (BitWidth && getLangOpts().OpenCL) {
14086     Diag(Loc, diag::err_opencl_bitfields);
14087     InvalidDecl = true;
14088   }
14089 
14090   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14091   // than a variably modified type.
14092   if (!InvalidDecl && T->isVariablyModifiedType()) {
14093     bool SizeIsNegative;
14094     llvm::APSInt Oversized;
14095 
14096     TypeSourceInfo *FixedTInfo =
14097       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14098                                                     SizeIsNegative,
14099                                                     Oversized);
14100     if (FixedTInfo) {
14101       Diag(Loc, diag::warn_illegal_constant_array_size);
14102       TInfo = FixedTInfo;
14103       T = FixedTInfo->getType();
14104     } else {
14105       if (SizeIsNegative)
14106         Diag(Loc, diag::err_typecheck_negative_array_size);
14107       else if (Oversized.getBoolValue())
14108         Diag(Loc, diag::err_array_too_large)
14109           << Oversized.toString(10);
14110       else
14111         Diag(Loc, diag::err_typecheck_field_variable_size);
14112       InvalidDecl = true;
14113     }
14114   }
14115 
14116   // Fields can not have abstract class types
14117   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14118                                              diag::err_abstract_type_in_decl,
14119                                              AbstractFieldType))
14120     InvalidDecl = true;
14121 
14122   bool ZeroWidth = false;
14123   if (InvalidDecl)
14124     BitWidth = nullptr;
14125   // If this is declared as a bit-field, check the bit-field.
14126   if (BitWidth) {
14127     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14128                               &ZeroWidth).get();
14129     if (!BitWidth) {
14130       InvalidDecl = true;
14131       BitWidth = nullptr;
14132       ZeroWidth = false;
14133     }
14134   }
14135 
14136   // Check that 'mutable' is consistent with the type of the declaration.
14137   if (!InvalidDecl && Mutable) {
14138     unsigned DiagID = 0;
14139     if (T->isReferenceType())
14140       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14141                                         : diag::err_mutable_reference;
14142     else if (T.isConstQualified())
14143       DiagID = diag::err_mutable_const;
14144 
14145     if (DiagID) {
14146       SourceLocation ErrLoc = Loc;
14147       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14148         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14149       Diag(ErrLoc, DiagID);
14150       if (DiagID != diag::ext_mutable_reference) {
14151         Mutable = false;
14152         InvalidDecl = true;
14153       }
14154     }
14155   }
14156 
14157   // C++11 [class.union]p8 (DR1460):
14158   //   At most one variant member of a union may have a
14159   //   brace-or-equal-initializer.
14160   if (InitStyle != ICIS_NoInit)
14161     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14162 
14163   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14164                                        BitWidth, Mutable, InitStyle);
14165   if (InvalidDecl)
14166     NewFD->setInvalidDecl();
14167 
14168   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14169     Diag(Loc, diag::err_duplicate_member) << II;
14170     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14171     NewFD->setInvalidDecl();
14172   }
14173 
14174   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14175     if (Record->isUnion()) {
14176       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14177         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14178         if (RDecl->getDefinition()) {
14179           // C++ [class.union]p1: An object of a class with a non-trivial
14180           // constructor, a non-trivial copy constructor, a non-trivial
14181           // destructor, or a non-trivial copy assignment operator
14182           // cannot be a member of a union, nor can an array of such
14183           // objects.
14184           if (CheckNontrivialField(NewFD))
14185             NewFD->setInvalidDecl();
14186         }
14187       }
14188 
14189       // C++ [class.union]p1: If a union contains a member of reference type,
14190       // the program is ill-formed, except when compiling with MSVC extensions
14191       // enabled.
14192       if (EltTy->isReferenceType()) {
14193         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14194                                     diag::ext_union_member_of_reference_type :
14195                                     diag::err_union_member_of_reference_type)
14196           << NewFD->getDeclName() << EltTy;
14197         if (!getLangOpts().MicrosoftExt)
14198           NewFD->setInvalidDecl();
14199       }
14200     }
14201   }
14202 
14203   // FIXME: We need to pass in the attributes given an AST
14204   // representation, not a parser representation.
14205   if (D) {
14206     // FIXME: The current scope is almost... but not entirely... correct here.
14207     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14208 
14209     if (NewFD->hasAttrs())
14210       CheckAlignasUnderalignment(NewFD);
14211   }
14212 
14213   // In auto-retain/release, infer strong retension for fields of
14214   // retainable type.
14215   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14216     NewFD->setInvalidDecl();
14217 
14218   if (T.isObjCGCWeak())
14219     Diag(Loc, diag::warn_attribute_weak_on_field);
14220 
14221   NewFD->setAccess(AS);
14222   return NewFD;
14223 }
14224 
14225 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14226   assert(FD);
14227   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14228 
14229   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14230     return false;
14231 
14232   QualType EltTy = Context.getBaseElementType(FD->getType());
14233   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14234     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14235     if (RDecl->getDefinition()) {
14236       // We check for copy constructors before constructors
14237       // because otherwise we'll never get complaints about
14238       // copy constructors.
14239 
14240       CXXSpecialMember member = CXXInvalid;
14241       // We're required to check for any non-trivial constructors. Since the
14242       // implicit default constructor is suppressed if there are any
14243       // user-declared constructors, we just need to check that there is a
14244       // trivial default constructor and a trivial copy constructor. (We don't
14245       // worry about move constructors here, since this is a C++98 check.)
14246       if (RDecl->hasNonTrivialCopyConstructor())
14247         member = CXXCopyConstructor;
14248       else if (!RDecl->hasTrivialDefaultConstructor())
14249         member = CXXDefaultConstructor;
14250       else if (RDecl->hasNonTrivialCopyAssignment())
14251         member = CXXCopyAssignment;
14252       else if (RDecl->hasNonTrivialDestructor())
14253         member = CXXDestructor;
14254 
14255       if (member != CXXInvalid) {
14256         if (!getLangOpts().CPlusPlus11 &&
14257             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14258           // Objective-C++ ARC: it is an error to have a non-trivial field of
14259           // a union. However, system headers in Objective-C programs
14260           // occasionally have Objective-C lifetime objects within unions,
14261           // and rather than cause the program to fail, we make those
14262           // members unavailable.
14263           SourceLocation Loc = FD->getLocation();
14264           if (getSourceManager().isInSystemHeader(Loc)) {
14265             if (!FD->hasAttr<UnavailableAttr>())
14266               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14267                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14268             return false;
14269           }
14270         }
14271 
14272         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14273                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14274                diag::err_illegal_union_or_anon_struct_member)
14275           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14276         DiagnoseNontrivial(RDecl, member);
14277         return !getLangOpts().CPlusPlus11;
14278       }
14279     }
14280   }
14281 
14282   return false;
14283 }
14284 
14285 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14286 ///  AST enum value.
14287 static ObjCIvarDecl::AccessControl
14288 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14289   switch (ivarVisibility) {
14290   default: llvm_unreachable("Unknown visitibility kind");
14291   case tok::objc_private: return ObjCIvarDecl::Private;
14292   case tok::objc_public: return ObjCIvarDecl::Public;
14293   case tok::objc_protected: return ObjCIvarDecl::Protected;
14294   case tok::objc_package: return ObjCIvarDecl::Package;
14295   }
14296 }
14297 
14298 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14299 /// in order to create an IvarDecl object for it.
14300 Decl *Sema::ActOnIvar(Scope *S,
14301                                 SourceLocation DeclStart,
14302                                 Declarator &D, Expr *BitfieldWidth,
14303                                 tok::ObjCKeywordKind Visibility) {
14304 
14305   IdentifierInfo *II = D.getIdentifier();
14306   Expr *BitWidth = (Expr*)BitfieldWidth;
14307   SourceLocation Loc = DeclStart;
14308   if (II) Loc = D.getIdentifierLoc();
14309 
14310   // FIXME: Unnamed fields can be handled in various different ways, for
14311   // example, unnamed unions inject all members into the struct namespace!
14312 
14313   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14314   QualType T = TInfo->getType();
14315 
14316   if (BitWidth) {
14317     // 6.7.2.1p3, 6.7.2.1p4
14318     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14319     if (!BitWidth)
14320       D.setInvalidType();
14321   } else {
14322     // Not a bitfield.
14323 
14324     // validate II.
14325 
14326   }
14327   if (T->isReferenceType()) {
14328     Diag(Loc, diag::err_ivar_reference_type);
14329     D.setInvalidType();
14330   }
14331   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14332   // than a variably modified type.
14333   else if (T->isVariablyModifiedType()) {
14334     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14335     D.setInvalidType();
14336   }
14337 
14338   // Get the visibility (access control) for this ivar.
14339   ObjCIvarDecl::AccessControl ac =
14340     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14341                                         : ObjCIvarDecl::None;
14342   // Must set ivar's DeclContext to its enclosing interface.
14343   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14344   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14345     return nullptr;
14346   ObjCContainerDecl *EnclosingContext;
14347   if (ObjCImplementationDecl *IMPDecl =
14348       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14349     if (LangOpts.ObjCRuntime.isFragile()) {
14350     // Case of ivar declared in an implementation. Context is that of its class.
14351       EnclosingContext = IMPDecl->getClassInterface();
14352       assert(EnclosingContext && "Implementation has no class interface!");
14353     }
14354     else
14355       EnclosingContext = EnclosingDecl;
14356   } else {
14357     if (ObjCCategoryDecl *CDecl =
14358         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14359       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14360         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14361         return nullptr;
14362       }
14363     }
14364     EnclosingContext = EnclosingDecl;
14365   }
14366 
14367   // Construct the decl.
14368   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14369                                              DeclStart, Loc, II, T,
14370                                              TInfo, ac, (Expr *)BitfieldWidth);
14371 
14372   if (II) {
14373     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14374                                            ForRedeclaration);
14375     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14376         && !isa<TagDecl>(PrevDecl)) {
14377       Diag(Loc, diag::err_duplicate_member) << II;
14378       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14379       NewID->setInvalidDecl();
14380     }
14381   }
14382 
14383   // Process attributes attached to the ivar.
14384   ProcessDeclAttributes(S, NewID, D);
14385 
14386   if (D.isInvalidType())
14387     NewID->setInvalidDecl();
14388 
14389   // In ARC, infer 'retaining' for ivars of retainable type.
14390   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14391     NewID->setInvalidDecl();
14392 
14393   if (D.getDeclSpec().isModulePrivateSpecified())
14394     NewID->setModulePrivate();
14395 
14396   if (II) {
14397     // FIXME: When interfaces are DeclContexts, we'll need to add
14398     // these to the interface.
14399     S->AddDecl(NewID);
14400     IdResolver.AddDecl(NewID);
14401   }
14402 
14403   if (LangOpts.ObjCRuntime.isNonFragile() &&
14404       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14405     Diag(Loc, diag::warn_ivars_in_interface);
14406 
14407   return NewID;
14408 }
14409 
14410 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14411 /// class and class extensions. For every class \@interface and class
14412 /// extension \@interface, if the last ivar is a bitfield of any type,
14413 /// then add an implicit `char :0` ivar to the end of that interface.
14414 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14415                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14416   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14417     return;
14418 
14419   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14420   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14421 
14422   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14423     return;
14424   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14425   if (!ID) {
14426     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14427       if (!CD->IsClassExtension())
14428         return;
14429     }
14430     // No need to add this to end of @implementation.
14431     else
14432       return;
14433   }
14434   // All conditions are met. Add a new bitfield to the tail end of ivars.
14435   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14436   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14437 
14438   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14439                               DeclLoc, DeclLoc, nullptr,
14440                               Context.CharTy,
14441                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14442                                                                DeclLoc),
14443                               ObjCIvarDecl::Private, BW,
14444                               true);
14445   AllIvarDecls.push_back(Ivar);
14446 }
14447 
14448 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14449                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14450                        SourceLocation RBrac, AttributeList *Attr) {
14451   assert(EnclosingDecl && "missing record or interface decl");
14452 
14453   // If this is an Objective-C @implementation or category and we have
14454   // new fields here we should reset the layout of the interface since
14455   // it will now change.
14456   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14457     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14458     switch (DC->getKind()) {
14459     default: break;
14460     case Decl::ObjCCategory:
14461       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14462       break;
14463     case Decl::ObjCImplementation:
14464       Context.
14465         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14466       break;
14467     }
14468   }
14469 
14470   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14471 
14472   // Start counting up the number of named members; make sure to include
14473   // members of anonymous structs and unions in the total.
14474   unsigned NumNamedMembers = 0;
14475   if (Record) {
14476     for (const auto *I : Record->decls()) {
14477       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14478         if (IFD->getDeclName())
14479           ++NumNamedMembers;
14480     }
14481   }
14482 
14483   // Verify that all the fields are okay.
14484   SmallVector<FieldDecl*, 32> RecFields;
14485 
14486   bool ARCErrReported = false;
14487   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14488        i != end; ++i) {
14489     FieldDecl *FD = cast<FieldDecl>(*i);
14490 
14491     // Get the type for the field.
14492     const Type *FDTy = FD->getType().getTypePtr();
14493 
14494     if (!FD->isAnonymousStructOrUnion()) {
14495       // Remember all fields written by the user.
14496       RecFields.push_back(FD);
14497     }
14498 
14499     // If the field is already invalid for some reason, don't emit more
14500     // diagnostics about it.
14501     if (FD->isInvalidDecl()) {
14502       EnclosingDecl->setInvalidDecl();
14503       continue;
14504     }
14505 
14506     // C99 6.7.2.1p2:
14507     //   A structure or union shall not contain a member with
14508     //   incomplete or function type (hence, a structure shall not
14509     //   contain an instance of itself, but may contain a pointer to
14510     //   an instance of itself), except that the last member of a
14511     //   structure with more than one named member may have incomplete
14512     //   array type; such a structure (and any union containing,
14513     //   possibly recursively, a member that is such a structure)
14514     //   shall not be a member of a structure or an element of an
14515     //   array.
14516     if (FDTy->isFunctionType()) {
14517       // Field declared as a function.
14518       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14519         << FD->getDeclName();
14520       FD->setInvalidDecl();
14521       EnclosingDecl->setInvalidDecl();
14522       continue;
14523     } else if (FDTy->isIncompleteArrayType() && Record &&
14524                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14525                 ((getLangOpts().MicrosoftExt ||
14526                   getLangOpts().CPlusPlus) &&
14527                  (i + 1 == Fields.end() || Record->isUnion())))) {
14528       // Flexible array member.
14529       // Microsoft and g++ is more permissive regarding flexible array.
14530       // It will accept flexible array in union and also
14531       // as the sole element of a struct/class.
14532       unsigned DiagID = 0;
14533       if (Record->isUnion())
14534         DiagID = getLangOpts().MicrosoftExt
14535                      ? diag::ext_flexible_array_union_ms
14536                      : getLangOpts().CPlusPlus
14537                            ? diag::ext_flexible_array_union_gnu
14538                            : diag::err_flexible_array_union;
14539       else if (NumNamedMembers < 1)
14540         DiagID = getLangOpts().MicrosoftExt
14541                      ? diag::ext_flexible_array_empty_aggregate_ms
14542                      : getLangOpts().CPlusPlus
14543                            ? diag::ext_flexible_array_empty_aggregate_gnu
14544                            : diag::err_flexible_array_empty_aggregate;
14545 
14546       if (DiagID)
14547         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14548                                         << Record->getTagKind();
14549       // While the layout of types that contain virtual bases is not specified
14550       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14551       // virtual bases after the derived members.  This would make a flexible
14552       // array member declared at the end of an object not adjacent to the end
14553       // of the type.
14554       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14555         if (RD->getNumVBases() != 0)
14556           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14557             << FD->getDeclName() << Record->getTagKind();
14558       if (!getLangOpts().C99)
14559         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14560           << FD->getDeclName() << Record->getTagKind();
14561 
14562       // If the element type has a non-trivial destructor, we would not
14563       // implicitly destroy the elements, so disallow it for now.
14564       //
14565       // FIXME: GCC allows this. We should probably either implicitly delete
14566       // the destructor of the containing class, or just allow this.
14567       QualType BaseElem = Context.getBaseElementType(FD->getType());
14568       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14569         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14570           << FD->getDeclName() << FD->getType();
14571         FD->setInvalidDecl();
14572         EnclosingDecl->setInvalidDecl();
14573         continue;
14574       }
14575       // Okay, we have a legal flexible array member at the end of the struct.
14576       Record->setHasFlexibleArrayMember(true);
14577     } else if (!FDTy->isDependentType() &&
14578                RequireCompleteType(FD->getLocation(), FD->getType(),
14579                                    diag::err_field_incomplete)) {
14580       // Incomplete type
14581       FD->setInvalidDecl();
14582       EnclosingDecl->setInvalidDecl();
14583       continue;
14584     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14585       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14586         // A type which contains a flexible array member is considered to be a
14587         // flexible array member.
14588         Record->setHasFlexibleArrayMember(true);
14589         if (!Record->isUnion()) {
14590           // If this is a struct/class and this is not the last element, reject
14591           // it.  Note that GCC supports variable sized arrays in the middle of
14592           // structures.
14593           if (i + 1 != Fields.end())
14594             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14595               << FD->getDeclName() << FD->getType();
14596           else {
14597             // We support flexible arrays at the end of structs in
14598             // other structs as an extension.
14599             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14600               << FD->getDeclName();
14601           }
14602         }
14603       }
14604       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14605           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14606                                  diag::err_abstract_type_in_decl,
14607                                  AbstractIvarType)) {
14608         // Ivars can not have abstract class types
14609         FD->setInvalidDecl();
14610       }
14611       if (Record && FDTTy->getDecl()->hasObjectMember())
14612         Record->setHasObjectMember(true);
14613       if (Record && FDTTy->getDecl()->hasVolatileMember())
14614         Record->setHasVolatileMember(true);
14615     } else if (FDTy->isObjCObjectType()) {
14616       /// A field cannot be an Objective-c object
14617       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14618         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14619       QualType T = Context.getObjCObjectPointerType(FD->getType());
14620       FD->setType(T);
14621     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14622                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14623       // It's an error in ARC if a field has lifetime.
14624       // We don't want to report this in a system header, though,
14625       // so we just make the field unavailable.
14626       // FIXME: that's really not sufficient; we need to make the type
14627       // itself invalid to, say, initialize or copy.
14628       QualType T = FD->getType();
14629       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14630       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
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           }
14637         } else {
14638           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14639             << T->isBlockPointerType() << Record->getTagKind();
14640         }
14641         ARCErrReported = true;
14642       }
14643     } else if (getLangOpts().ObjC1 &&
14644                getLangOpts().getGC() != LangOptions::NonGC &&
14645                Record && !Record->hasObjectMember()) {
14646       if (FD->getType()->isObjCObjectPointerType() ||
14647           FD->getType().isObjCGCStrong())
14648         Record->setHasObjectMember(true);
14649       else if (Context.getAsArrayType(FD->getType())) {
14650         QualType BaseType = Context.getBaseElementType(FD->getType());
14651         if (BaseType->isRecordType() &&
14652             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14653           Record->setHasObjectMember(true);
14654         else if (BaseType->isObjCObjectPointerType() ||
14655                  BaseType.isObjCGCStrong())
14656                Record->setHasObjectMember(true);
14657       }
14658     }
14659     if (Record && FD->getType().isVolatileQualified())
14660       Record->setHasVolatileMember(true);
14661     // Keep track of the number of named members.
14662     if (FD->getIdentifier())
14663       ++NumNamedMembers;
14664   }
14665 
14666   // Okay, we successfully defined 'Record'.
14667   if (Record) {
14668     bool Completed = false;
14669     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14670       if (!CXXRecord->isInvalidDecl()) {
14671         // Set access bits correctly on the directly-declared conversions.
14672         for (CXXRecordDecl::conversion_iterator
14673                I = CXXRecord->conversion_begin(),
14674                E = CXXRecord->conversion_end(); I != E; ++I)
14675           I.setAccess((*I)->getAccess());
14676       }
14677 
14678       if (!CXXRecord->isDependentType()) {
14679         if (CXXRecord->hasUserDeclaredDestructor()) {
14680           // Adjust user-defined destructor exception spec.
14681           if (getLangOpts().CPlusPlus11)
14682             AdjustDestructorExceptionSpec(CXXRecord,
14683                                           CXXRecord->getDestructor());
14684         }
14685 
14686         if (!CXXRecord->isInvalidDecl()) {
14687           // Add any implicitly-declared members to this class.
14688           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14689 
14690           // If we have virtual base classes, we may end up finding multiple
14691           // final overriders for a given virtual function. Check for this
14692           // problem now.
14693           if (CXXRecord->getNumVBases()) {
14694             CXXFinalOverriderMap FinalOverriders;
14695             CXXRecord->getFinalOverriders(FinalOverriders);
14696 
14697             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14698                                              MEnd = FinalOverriders.end();
14699                  M != MEnd; ++M) {
14700               for (OverridingMethods::iterator SO = M->second.begin(),
14701                                             SOEnd = M->second.end();
14702                    SO != SOEnd; ++SO) {
14703                 assert(SO->second.size() > 0 &&
14704                        "Virtual function without overridding functions?");
14705                 if (SO->second.size() == 1)
14706                   continue;
14707 
14708                 // C++ [class.virtual]p2:
14709                 //   In a derived class, if a virtual member function of a base
14710                 //   class subobject has more than one final overrider the
14711                 //   program is ill-formed.
14712                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14713                   << (const NamedDecl *)M->first << Record;
14714                 Diag(M->first->getLocation(),
14715                      diag::note_overridden_virtual_function);
14716                 for (OverridingMethods::overriding_iterator
14717                           OM = SO->second.begin(),
14718                        OMEnd = SO->second.end();
14719                      OM != OMEnd; ++OM)
14720                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14721                     << (const NamedDecl *)M->first << OM->Method->getParent();
14722 
14723                 Record->setInvalidDecl();
14724               }
14725             }
14726             CXXRecord->completeDefinition(&FinalOverriders);
14727             Completed = true;
14728           }
14729         }
14730       }
14731     }
14732 
14733     if (!Completed)
14734       Record->completeDefinition();
14735 
14736     // We may have deferred checking for a deleted destructor. Check now.
14737     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14738       auto *Dtor = CXXRecord->getDestructor();
14739       if (Dtor && Dtor->isImplicit() &&
14740           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14741         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14742     }
14743 
14744     if (Record->hasAttrs()) {
14745       CheckAlignasUnderalignment(Record);
14746 
14747       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14748         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14749                                            IA->getRange(), IA->getBestCase(),
14750                                            IA->getSemanticSpelling());
14751     }
14752 
14753     // Check if the structure/union declaration is a type that can have zero
14754     // size in C. For C this is a language extension, for C++ it may cause
14755     // compatibility problems.
14756     bool CheckForZeroSize;
14757     if (!getLangOpts().CPlusPlus) {
14758       CheckForZeroSize = true;
14759     } else {
14760       // For C++ filter out types that cannot be referenced in C code.
14761       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14762       CheckForZeroSize =
14763           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14764           !CXXRecord->isDependentType() &&
14765           CXXRecord->isCLike();
14766     }
14767     if (CheckForZeroSize) {
14768       bool ZeroSize = true;
14769       bool IsEmpty = true;
14770       unsigned NonBitFields = 0;
14771       for (RecordDecl::field_iterator I = Record->field_begin(),
14772                                       E = Record->field_end();
14773            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14774         IsEmpty = false;
14775         if (I->isUnnamedBitfield()) {
14776           if (I->getBitWidthValue(Context) > 0)
14777             ZeroSize = false;
14778         } else {
14779           ++NonBitFields;
14780           QualType FieldType = I->getType();
14781           if (FieldType->isIncompleteType() ||
14782               !Context.getTypeSizeInChars(FieldType).isZero())
14783             ZeroSize = false;
14784         }
14785       }
14786 
14787       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14788       // allowed in C++, but warn if its declaration is inside
14789       // extern "C" block.
14790       if (ZeroSize) {
14791         Diag(RecLoc, getLangOpts().CPlusPlus ?
14792                          diag::warn_zero_size_struct_union_in_extern_c :
14793                          diag::warn_zero_size_struct_union_compat)
14794           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14795       }
14796 
14797       // Structs without named members are extension in C (C99 6.7.2.1p7),
14798       // but are accepted by GCC.
14799       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14800         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14801                                diag::ext_no_named_members_in_struct_union)
14802           << Record->isUnion();
14803       }
14804     }
14805   } else {
14806     ObjCIvarDecl **ClsFields =
14807       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14808     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14809       ID->setEndOfDefinitionLoc(RBrac);
14810       // Add ivar's to class's DeclContext.
14811       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14812         ClsFields[i]->setLexicalDeclContext(ID);
14813         ID->addDecl(ClsFields[i]);
14814       }
14815       // Must enforce the rule that ivars in the base classes may not be
14816       // duplicates.
14817       if (ID->getSuperClass())
14818         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14819     } else if (ObjCImplementationDecl *IMPDecl =
14820                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14821       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14822       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14823         // Ivar declared in @implementation never belongs to the implementation.
14824         // Only it is in implementation's lexical context.
14825         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14826       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14827       IMPDecl->setIvarLBraceLoc(LBrac);
14828       IMPDecl->setIvarRBraceLoc(RBrac);
14829     } else if (ObjCCategoryDecl *CDecl =
14830                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14831       // case of ivars in class extension; all other cases have been
14832       // reported as errors elsewhere.
14833       // FIXME. Class extension does not have a LocEnd field.
14834       // CDecl->setLocEnd(RBrac);
14835       // Add ivar's to class extension's DeclContext.
14836       // Diagnose redeclaration of private ivars.
14837       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14838       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14839         if (IDecl) {
14840           if (const ObjCIvarDecl *ClsIvar =
14841               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14842             Diag(ClsFields[i]->getLocation(),
14843                  diag::err_duplicate_ivar_declaration);
14844             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14845             continue;
14846           }
14847           for (const auto *Ext : IDecl->known_extensions()) {
14848             if (const ObjCIvarDecl *ClsExtIvar
14849                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14850               Diag(ClsFields[i]->getLocation(),
14851                    diag::err_duplicate_ivar_declaration);
14852               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14853               continue;
14854             }
14855           }
14856         }
14857         ClsFields[i]->setLexicalDeclContext(CDecl);
14858         CDecl->addDecl(ClsFields[i]);
14859       }
14860       CDecl->setIvarLBraceLoc(LBrac);
14861       CDecl->setIvarRBraceLoc(RBrac);
14862     }
14863   }
14864 
14865   if (Attr)
14866     ProcessDeclAttributeList(S, Record, Attr);
14867 }
14868 
14869 /// \brief Determine whether the given integral value is representable within
14870 /// the given type T.
14871 static bool isRepresentableIntegerValue(ASTContext &Context,
14872                                         llvm::APSInt &Value,
14873                                         QualType T) {
14874   assert(T->isIntegralType(Context) && "Integral type required!");
14875   unsigned BitWidth = Context.getIntWidth(T);
14876 
14877   if (Value.isUnsigned() || Value.isNonNegative()) {
14878     if (T->isSignedIntegerOrEnumerationType())
14879       --BitWidth;
14880     return Value.getActiveBits() <= BitWidth;
14881   }
14882   return Value.getMinSignedBits() <= BitWidth;
14883 }
14884 
14885 // \brief Given an integral type, return the next larger integral type
14886 // (or a NULL type of no such type exists).
14887 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14888   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14889   // enum checking below.
14890   assert(T->isIntegralType(Context) && "Integral type required!");
14891   const unsigned NumTypes = 4;
14892   QualType SignedIntegralTypes[NumTypes] = {
14893     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14894   };
14895   QualType UnsignedIntegralTypes[NumTypes] = {
14896     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14897     Context.UnsignedLongLongTy
14898   };
14899 
14900   unsigned BitWidth = Context.getTypeSize(T);
14901   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14902                                                         : UnsignedIntegralTypes;
14903   for (unsigned I = 0; I != NumTypes; ++I)
14904     if (Context.getTypeSize(Types[I]) > BitWidth)
14905       return Types[I];
14906 
14907   return QualType();
14908 }
14909 
14910 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14911                                           EnumConstantDecl *LastEnumConst,
14912                                           SourceLocation IdLoc,
14913                                           IdentifierInfo *Id,
14914                                           Expr *Val) {
14915   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14916   llvm::APSInt EnumVal(IntWidth);
14917   QualType EltTy;
14918 
14919   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14920     Val = nullptr;
14921 
14922   if (Val)
14923     Val = DefaultLvalueConversion(Val).get();
14924 
14925   if (Val) {
14926     if (Enum->isDependentType() || Val->isTypeDependent())
14927       EltTy = Context.DependentTy;
14928     else {
14929       SourceLocation ExpLoc;
14930       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14931           !getLangOpts().MSVCCompat) {
14932         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14933         // constant-expression in the enumerator-definition shall be a converted
14934         // constant expression of the underlying type.
14935         EltTy = Enum->getIntegerType();
14936         ExprResult Converted =
14937           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14938                                            CCEK_Enumerator);
14939         if (Converted.isInvalid())
14940           Val = nullptr;
14941         else
14942           Val = Converted.get();
14943       } else if (!Val->isValueDependent() &&
14944                  !(Val = VerifyIntegerConstantExpression(Val,
14945                                                          &EnumVal).get())) {
14946         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14947       } else {
14948         if (Enum->isFixed()) {
14949           EltTy = Enum->getIntegerType();
14950 
14951           // In Obj-C and Microsoft mode, require the enumeration value to be
14952           // representable in the underlying type of the enumeration. In C++11,
14953           // we perform a non-narrowing conversion as part of converted constant
14954           // expression checking.
14955           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14956             if (getLangOpts().MSVCCompat) {
14957               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14958               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14959             } else
14960               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14961           } else
14962             Val = ImpCastExprToType(Val, EltTy,
14963                                     EltTy->isBooleanType() ?
14964                                     CK_IntegralToBoolean : CK_IntegralCast)
14965                     .get();
14966         } else if (getLangOpts().CPlusPlus) {
14967           // C++11 [dcl.enum]p5:
14968           //   If the underlying type is not fixed, the type of each enumerator
14969           //   is the type of its initializing value:
14970           //     - If an initializer is specified for an enumerator, the
14971           //       initializing value has the same type as the expression.
14972           EltTy = Val->getType();
14973         } else {
14974           // C99 6.7.2.2p2:
14975           //   The expression that defines the value of an enumeration constant
14976           //   shall be an integer constant expression that has a value
14977           //   representable as an int.
14978 
14979           // Complain if the value is not representable in an int.
14980           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14981             Diag(IdLoc, diag::ext_enum_value_not_int)
14982               << EnumVal.toString(10) << Val->getSourceRange()
14983               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14984           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14985             // Force the type of the expression to 'int'.
14986             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14987           }
14988           EltTy = Val->getType();
14989         }
14990       }
14991     }
14992   }
14993 
14994   if (!Val) {
14995     if (Enum->isDependentType())
14996       EltTy = Context.DependentTy;
14997     else if (!LastEnumConst) {
14998       // C++0x [dcl.enum]p5:
14999       //   If the underlying type is not fixed, the type of each enumerator
15000       //   is the type of its initializing value:
15001       //     - If no initializer is specified for the first enumerator, the
15002       //       initializing value has an unspecified integral type.
15003       //
15004       // GCC uses 'int' for its unspecified integral type, as does
15005       // C99 6.7.2.2p3.
15006       if (Enum->isFixed()) {
15007         EltTy = Enum->getIntegerType();
15008       }
15009       else {
15010         EltTy = Context.IntTy;
15011       }
15012     } else {
15013       // Assign the last value + 1.
15014       EnumVal = LastEnumConst->getInitVal();
15015       ++EnumVal;
15016       EltTy = LastEnumConst->getType();
15017 
15018       // Check for overflow on increment.
15019       if (EnumVal < LastEnumConst->getInitVal()) {
15020         // C++0x [dcl.enum]p5:
15021         //   If the underlying type is not fixed, the type of each enumerator
15022         //   is the type of its initializing value:
15023         //
15024         //     - Otherwise the type of the initializing value is the same as
15025         //       the type of the initializing value of the preceding enumerator
15026         //       unless the incremented value is not representable in that type,
15027         //       in which case the type is an unspecified integral type
15028         //       sufficient to contain the incremented value. If no such type
15029         //       exists, the program is ill-formed.
15030         QualType T = getNextLargerIntegralType(Context, EltTy);
15031         if (T.isNull() || Enum->isFixed()) {
15032           // There is no integral type larger enough to represent this
15033           // value. Complain, then allow the value to wrap around.
15034           EnumVal = LastEnumConst->getInitVal();
15035           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15036           ++EnumVal;
15037           if (Enum->isFixed())
15038             // When the underlying type is fixed, this is ill-formed.
15039             Diag(IdLoc, diag::err_enumerator_wrapped)
15040               << EnumVal.toString(10)
15041               << EltTy;
15042           else
15043             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15044               << EnumVal.toString(10);
15045         } else {
15046           EltTy = T;
15047         }
15048 
15049         // Retrieve the last enumerator's value, extent that type to the
15050         // type that is supposed to be large enough to represent the incremented
15051         // value, then increment.
15052         EnumVal = LastEnumConst->getInitVal();
15053         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15054         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15055         ++EnumVal;
15056 
15057         // If we're not in C++, diagnose the overflow of enumerator values,
15058         // which in C99 means that the enumerator value is not representable in
15059         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15060         // permits enumerator values that are representable in some larger
15061         // integral type.
15062         if (!getLangOpts().CPlusPlus && !T.isNull())
15063           Diag(IdLoc, diag::warn_enum_value_overflow);
15064       } else if (!getLangOpts().CPlusPlus &&
15065                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15066         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15067         Diag(IdLoc, diag::ext_enum_value_not_int)
15068           << EnumVal.toString(10) << 1;
15069       }
15070     }
15071   }
15072 
15073   if (!EltTy->isDependentType()) {
15074     // Make the enumerator value match the signedness and size of the
15075     // enumerator's type.
15076     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15077     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15078   }
15079 
15080   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15081                                   Val, EnumVal);
15082 }
15083 
15084 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15085                                                 SourceLocation IILoc) {
15086   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15087       !getLangOpts().CPlusPlus)
15088     return SkipBodyInfo();
15089 
15090   // We have an anonymous enum definition. Look up the first enumerator to
15091   // determine if we should merge the definition with an existing one and
15092   // skip the body.
15093   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15094                                          ForRedeclaration);
15095   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15096   if (!PrevECD)
15097     return SkipBodyInfo();
15098 
15099   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15100   NamedDecl *Hidden;
15101   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15102     SkipBodyInfo Skip;
15103     Skip.Previous = Hidden;
15104     return Skip;
15105   }
15106 
15107   return SkipBodyInfo();
15108 }
15109 
15110 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15111                               SourceLocation IdLoc, IdentifierInfo *Id,
15112                               AttributeList *Attr,
15113                               SourceLocation EqualLoc, Expr *Val) {
15114   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15115   EnumConstantDecl *LastEnumConst =
15116     cast_or_null<EnumConstantDecl>(lastEnumConst);
15117 
15118   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15119   // we find one that is.
15120   S = getNonFieldDeclScope(S);
15121 
15122   // Verify that there isn't already something declared with this name in this
15123   // scope.
15124   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15125                                          ForRedeclaration);
15126   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15127     // Maybe we will complain about the shadowed template parameter.
15128     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15129     // Just pretend that we didn't see the previous declaration.
15130     PrevDecl = nullptr;
15131   }
15132 
15133   // C++ [class.mem]p15:
15134   // If T is the name of a class, then each of the following shall have a name
15135   // different from T:
15136   // - every enumerator of every member of class T that is an unscoped
15137   // enumerated type
15138   if (!TheEnumDecl->isScoped())
15139     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15140                             DeclarationNameInfo(Id, IdLoc));
15141 
15142   EnumConstantDecl *New =
15143     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15144   if (!New)
15145     return nullptr;
15146 
15147   if (PrevDecl) {
15148     // When in C++, we may get a TagDecl with the same name; in this case the
15149     // enum constant will 'hide' the tag.
15150     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15151            "Received TagDecl when not in C++!");
15152     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15153         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15154       if (isa<EnumConstantDecl>(PrevDecl))
15155         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15156       else
15157         Diag(IdLoc, diag::err_redefinition) << Id;
15158       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15159       return nullptr;
15160     }
15161   }
15162 
15163   // Process attributes.
15164   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15165 
15166   // Register this decl in the current scope stack.
15167   New->setAccess(TheEnumDecl->getAccess());
15168   PushOnScopeChains(New, S);
15169 
15170   ActOnDocumentableDecl(New);
15171 
15172   return New;
15173 }
15174 
15175 // Returns true when the enum initial expression does not trigger the
15176 // duplicate enum warning.  A few common cases are exempted as follows:
15177 // Element2 = Element1
15178 // Element2 = Element1 + 1
15179 // Element2 = Element1 - 1
15180 // Where Element2 and Element1 are from the same enum.
15181 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15182   Expr *InitExpr = ECD->getInitExpr();
15183   if (!InitExpr)
15184     return true;
15185   InitExpr = InitExpr->IgnoreImpCasts();
15186 
15187   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15188     if (!BO->isAdditiveOp())
15189       return true;
15190     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15191     if (!IL)
15192       return true;
15193     if (IL->getValue() != 1)
15194       return true;
15195 
15196     InitExpr = BO->getLHS();
15197   }
15198 
15199   // This checks if the elements are from the same enum.
15200   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15201   if (!DRE)
15202     return true;
15203 
15204   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15205   if (!EnumConstant)
15206     return true;
15207 
15208   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15209       Enum)
15210     return true;
15211 
15212   return false;
15213 }
15214 
15215 namespace {
15216 struct DupKey {
15217   int64_t val;
15218   bool isTombstoneOrEmptyKey;
15219   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15220     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15221 };
15222 
15223 static DupKey GetDupKey(const llvm::APSInt& Val) {
15224   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15225                 false);
15226 }
15227 
15228 struct DenseMapInfoDupKey {
15229   static DupKey getEmptyKey() { return DupKey(0, true); }
15230   static DupKey getTombstoneKey() { return DupKey(1, true); }
15231   static unsigned getHashValue(const DupKey Key) {
15232     return (unsigned)(Key.val * 37);
15233   }
15234   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15235     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15236            LHS.val == RHS.val;
15237   }
15238 };
15239 } // end anonymous namespace
15240 
15241 // Emits a warning when an element is implicitly set a value that
15242 // a previous element has already been set to.
15243 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15244                                         EnumDecl *Enum,
15245                                         QualType EnumType) {
15246   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15247     return;
15248   // Avoid anonymous enums
15249   if (!Enum->getIdentifier())
15250     return;
15251 
15252   // Only check for small enums.
15253   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15254     return;
15255 
15256   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15257   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15258 
15259   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15260   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15261           ValueToVectorMap;
15262 
15263   DuplicatesVector DupVector;
15264   ValueToVectorMap EnumMap;
15265 
15266   // Populate the EnumMap with all values represented by enum constants without
15267   // an initialier.
15268   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15269     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15270 
15271     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15272     // this constant.  Skip this enum since it may be ill-formed.
15273     if (!ECD) {
15274       return;
15275     }
15276 
15277     if (ECD->getInitExpr())
15278       continue;
15279 
15280     DupKey Key = GetDupKey(ECD->getInitVal());
15281     DeclOrVector &Entry = EnumMap[Key];
15282 
15283     // First time encountering this value.
15284     if (Entry.isNull())
15285       Entry = ECD;
15286   }
15287 
15288   // Create vectors for any values that has duplicates.
15289   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15290     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15291     if (!ValidDuplicateEnum(ECD, Enum))
15292       continue;
15293 
15294     DupKey Key = GetDupKey(ECD->getInitVal());
15295 
15296     DeclOrVector& Entry = EnumMap[Key];
15297     if (Entry.isNull())
15298       continue;
15299 
15300     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15301       // Ensure constants are different.
15302       if (D == ECD)
15303         continue;
15304 
15305       // Create new vector and push values onto it.
15306       ECDVector *Vec = new ECDVector();
15307       Vec->push_back(D);
15308       Vec->push_back(ECD);
15309 
15310       // Update entry to point to the duplicates vector.
15311       Entry = Vec;
15312 
15313       // Store the vector somewhere we can consult later for quick emission of
15314       // diagnostics.
15315       DupVector.push_back(Vec);
15316       continue;
15317     }
15318 
15319     ECDVector *Vec = Entry.get<ECDVector*>();
15320     // Make sure constants are not added more than once.
15321     if (*Vec->begin() == ECD)
15322       continue;
15323 
15324     Vec->push_back(ECD);
15325   }
15326 
15327   // Emit diagnostics.
15328   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15329                                   DupVectorEnd = DupVector.end();
15330        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15331     ECDVector *Vec = *DupVectorIter;
15332     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15333 
15334     // Emit warning for one enum constant.
15335     ECDVector::iterator I = Vec->begin();
15336     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15337       << (*I)->getName() << (*I)->getInitVal().toString(10)
15338       << (*I)->getSourceRange();
15339     ++I;
15340 
15341     // Emit one note for each of the remaining enum constants with
15342     // the same value.
15343     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15344       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15345         << (*I)->getName() << (*I)->getInitVal().toString(10)
15346         << (*I)->getSourceRange();
15347     delete Vec;
15348   }
15349 }
15350 
15351 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15352                              bool AllowMask) const {
15353   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15354   assert(ED->isCompleteDefinition() && "expected enum definition");
15355 
15356   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15357   llvm::APInt &FlagBits = R.first->second;
15358 
15359   if (R.second) {
15360     for (auto *E : ED->enumerators()) {
15361       const auto &EVal = E->getInitVal();
15362       // Only single-bit enumerators introduce new flag values.
15363       if (EVal.isPowerOf2())
15364         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15365     }
15366   }
15367 
15368   // A value is in a flag enum if either its bits are a subset of the enum's
15369   // flag bits (the first condition) or we are allowing masks and the same is
15370   // true of its complement (the second condition). When masks are allowed, we
15371   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15372   //
15373   // While it's true that any value could be used as a mask, the assumption is
15374   // that a mask will have all of the insignificant bits set. Anything else is
15375   // likely a logic error.
15376   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15377   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15378 }
15379 
15380 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15381                          Decl *EnumDeclX,
15382                          ArrayRef<Decl *> Elements,
15383                          Scope *S, AttributeList *Attr) {
15384   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15385   QualType EnumType = Context.getTypeDeclType(Enum);
15386 
15387   if (Attr)
15388     ProcessDeclAttributeList(S, Enum, Attr);
15389 
15390   if (Enum->isDependentType()) {
15391     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15392       EnumConstantDecl *ECD =
15393         cast_or_null<EnumConstantDecl>(Elements[i]);
15394       if (!ECD) continue;
15395 
15396       ECD->setType(EnumType);
15397     }
15398 
15399     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15400     return;
15401   }
15402 
15403   // TODO: If the result value doesn't fit in an int, it must be a long or long
15404   // long value.  ISO C does not support this, but GCC does as an extension,
15405   // emit a warning.
15406   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15407   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15408   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15409 
15410   // Verify that all the values are okay, compute the size of the values, and
15411   // reverse the list.
15412   unsigned NumNegativeBits = 0;
15413   unsigned NumPositiveBits = 0;
15414 
15415   // Keep track of whether all elements have type int.
15416   bool AllElementsInt = true;
15417 
15418   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15419     EnumConstantDecl *ECD =
15420       cast_or_null<EnumConstantDecl>(Elements[i]);
15421     if (!ECD) continue;  // Already issued a diagnostic.
15422 
15423     const llvm::APSInt &InitVal = ECD->getInitVal();
15424 
15425     // Keep track of the size of positive and negative values.
15426     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15427       NumPositiveBits = std::max(NumPositiveBits,
15428                                  (unsigned)InitVal.getActiveBits());
15429     else
15430       NumNegativeBits = std::max(NumNegativeBits,
15431                                  (unsigned)InitVal.getMinSignedBits());
15432 
15433     // Keep track of whether every enum element has type int (very commmon).
15434     if (AllElementsInt)
15435       AllElementsInt = ECD->getType() == Context.IntTy;
15436   }
15437 
15438   // Figure out the type that should be used for this enum.
15439   QualType BestType;
15440   unsigned BestWidth;
15441 
15442   // C++0x N3000 [conv.prom]p3:
15443   //   An rvalue of an unscoped enumeration type whose underlying
15444   //   type is not fixed can be converted to an rvalue of the first
15445   //   of the following types that can represent all the values of
15446   //   the enumeration: int, unsigned int, long int, unsigned long
15447   //   int, long long int, or unsigned long long int.
15448   // C99 6.4.4.3p2:
15449   //   An identifier declared as an enumeration constant has type int.
15450   // The C99 rule is modified by a gcc extension
15451   QualType BestPromotionType;
15452 
15453   bool Packed = Enum->hasAttr<PackedAttr>();
15454   // -fshort-enums is the equivalent to specifying the packed attribute on all
15455   // enum definitions.
15456   if (LangOpts.ShortEnums)
15457     Packed = true;
15458 
15459   if (Enum->isFixed()) {
15460     BestType = Enum->getIntegerType();
15461     if (BestType->isPromotableIntegerType())
15462       BestPromotionType = Context.getPromotedIntegerType(BestType);
15463     else
15464       BestPromotionType = BestType;
15465 
15466     BestWidth = Context.getIntWidth(BestType);
15467   }
15468   else if (NumNegativeBits) {
15469     // If there is a negative value, figure out the smallest integer type (of
15470     // int/long/longlong) that fits.
15471     // If it's packed, check also if it fits a char or a short.
15472     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15473       BestType = Context.SignedCharTy;
15474       BestWidth = CharWidth;
15475     } else if (Packed && NumNegativeBits <= ShortWidth &&
15476                NumPositiveBits < ShortWidth) {
15477       BestType = Context.ShortTy;
15478       BestWidth = ShortWidth;
15479     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15480       BestType = Context.IntTy;
15481       BestWidth = IntWidth;
15482     } else {
15483       BestWidth = Context.getTargetInfo().getLongWidth();
15484 
15485       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15486         BestType = Context.LongTy;
15487       } else {
15488         BestWidth = Context.getTargetInfo().getLongLongWidth();
15489 
15490         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15491           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15492         BestType = Context.LongLongTy;
15493       }
15494     }
15495     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15496   } else {
15497     // If there is no negative value, figure out the smallest type that fits
15498     // all of the enumerator values.
15499     // If it's packed, check also if it fits a char or a short.
15500     if (Packed && NumPositiveBits <= CharWidth) {
15501       BestType = Context.UnsignedCharTy;
15502       BestPromotionType = Context.IntTy;
15503       BestWidth = CharWidth;
15504     } else if (Packed && NumPositiveBits <= ShortWidth) {
15505       BestType = Context.UnsignedShortTy;
15506       BestPromotionType = Context.IntTy;
15507       BestWidth = ShortWidth;
15508     } else if (NumPositiveBits <= IntWidth) {
15509       BestType = Context.UnsignedIntTy;
15510       BestWidth = IntWidth;
15511       BestPromotionType
15512         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15513                            ? Context.UnsignedIntTy : Context.IntTy;
15514     } else if (NumPositiveBits <=
15515                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15516       BestType = Context.UnsignedLongTy;
15517       BestPromotionType
15518         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15519                            ? Context.UnsignedLongTy : Context.LongTy;
15520     } else {
15521       BestWidth = Context.getTargetInfo().getLongLongWidth();
15522       assert(NumPositiveBits <= BestWidth &&
15523              "How could an initializer get larger than ULL?");
15524       BestType = Context.UnsignedLongLongTy;
15525       BestPromotionType
15526         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15527                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15528     }
15529   }
15530 
15531   // Loop over all of the enumerator constants, changing their types to match
15532   // the type of the enum if needed.
15533   for (auto *D : Elements) {
15534     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15535     if (!ECD) continue;  // Already issued a diagnostic.
15536 
15537     // Standard C says the enumerators have int type, but we allow, as an
15538     // extension, the enumerators to be larger than int size.  If each
15539     // enumerator value fits in an int, type it as an int, otherwise type it the
15540     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15541     // that X has type 'int', not 'unsigned'.
15542 
15543     // Determine whether the value fits into an int.
15544     llvm::APSInt InitVal = ECD->getInitVal();
15545 
15546     // If it fits into an integer type, force it.  Otherwise force it to match
15547     // the enum decl type.
15548     QualType NewTy;
15549     unsigned NewWidth;
15550     bool NewSign;
15551     if (!getLangOpts().CPlusPlus &&
15552         !Enum->isFixed() &&
15553         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15554       NewTy = Context.IntTy;
15555       NewWidth = IntWidth;
15556       NewSign = true;
15557     } else if (ECD->getType() == BestType) {
15558       // Already the right type!
15559       if (getLangOpts().CPlusPlus)
15560         // C++ [dcl.enum]p4: Following the closing brace of an
15561         // enum-specifier, each enumerator has the type of its
15562         // enumeration.
15563         ECD->setType(EnumType);
15564       continue;
15565     } else {
15566       NewTy = BestType;
15567       NewWidth = BestWidth;
15568       NewSign = BestType->isSignedIntegerOrEnumerationType();
15569     }
15570 
15571     // Adjust the APSInt value.
15572     InitVal = InitVal.extOrTrunc(NewWidth);
15573     InitVal.setIsSigned(NewSign);
15574     ECD->setInitVal(InitVal);
15575 
15576     // Adjust the Expr initializer and type.
15577     if (ECD->getInitExpr() &&
15578         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15579       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15580                                                 CK_IntegralCast,
15581                                                 ECD->getInitExpr(),
15582                                                 /*base paths*/ nullptr,
15583                                                 VK_RValue));
15584     if (getLangOpts().CPlusPlus)
15585       // C++ [dcl.enum]p4: Following the closing brace of an
15586       // enum-specifier, each enumerator has the type of its
15587       // enumeration.
15588       ECD->setType(EnumType);
15589     else
15590       ECD->setType(NewTy);
15591   }
15592 
15593   Enum->completeDefinition(BestType, BestPromotionType,
15594                            NumPositiveBits, NumNegativeBits);
15595 
15596   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15597 
15598   if (Enum->hasAttr<FlagEnumAttr>()) {
15599     for (Decl *D : Elements) {
15600       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15601       if (!ECD) continue;  // Already issued a diagnostic.
15602 
15603       llvm::APSInt InitVal = ECD->getInitVal();
15604       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15605           !IsValueInFlagEnum(Enum, InitVal, true))
15606         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15607           << ECD << Enum;
15608     }
15609   }
15610 
15611   // Now that the enum type is defined, ensure it's not been underaligned.
15612   if (Enum->hasAttrs())
15613     CheckAlignasUnderalignment(Enum);
15614 }
15615 
15616 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15617                                   SourceLocation StartLoc,
15618                                   SourceLocation EndLoc) {
15619   StringLiteral *AsmString = cast<StringLiteral>(expr);
15620 
15621   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15622                                                    AsmString, StartLoc,
15623                                                    EndLoc);
15624   CurContext->addDecl(New);
15625   return New;
15626 }
15627 
15628 static void checkModuleImportContext(Sema &S, Module *M,
15629                                      SourceLocation ImportLoc, DeclContext *DC,
15630                                      bool FromInclude = false) {
15631   SourceLocation ExternCLoc;
15632 
15633   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15634     switch (LSD->getLanguage()) {
15635     case LinkageSpecDecl::lang_c:
15636       if (ExternCLoc.isInvalid())
15637         ExternCLoc = LSD->getLocStart();
15638       break;
15639     case LinkageSpecDecl::lang_cxx:
15640       break;
15641     }
15642     DC = LSD->getParent();
15643   }
15644 
15645   while (isa<LinkageSpecDecl>(DC))
15646     DC = DC->getParent();
15647 
15648   if (!isa<TranslationUnitDecl>(DC)) {
15649     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15650                           ? diag::ext_module_import_not_at_top_level_noop
15651                           : diag::err_module_import_not_at_top_level_fatal)
15652         << M->getFullModuleName() << DC;
15653     S.Diag(cast<Decl>(DC)->getLocStart(),
15654            diag::note_module_import_not_at_top_level) << DC;
15655   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15656     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15657       << M->getFullModuleName();
15658     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15659   }
15660 }
15661 
15662 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15663                                            ModuleDeclKind MDK,
15664                                            ModuleIdPath Path) {
15665   // 'module implementation' requires that we are not compiling a module of any
15666   // kind. 'module' and 'module partition' require that we are compiling a
15667   // module inteface (not a module map).
15668   auto CMK = getLangOpts().getCompilingModule();
15669   if (MDK == ModuleDeclKind::Implementation
15670           ? CMK != LangOptions::CMK_None
15671           : CMK != LangOptions::CMK_ModuleInterface) {
15672     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15673       << (unsigned)MDK;
15674     return nullptr;
15675   }
15676 
15677   // FIXME: Create a ModuleDecl and return it.
15678 
15679   // FIXME: Most of this work should be done by the preprocessor rather than
15680   // here, in case we look ahead across something where the current
15681   // module matters (eg a #include).
15682 
15683   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15684   // hierarchical module map modules, the dots here are just another character
15685   // that can appear in a module name. Flatten down to the actual module name.
15686   std::string ModuleName;
15687   for (auto &Piece : Path) {
15688     if (!ModuleName.empty())
15689       ModuleName += ".";
15690     ModuleName += Piece.first->getName();
15691   }
15692 
15693   // If a module name was explicitly specified on the command line, it must be
15694   // correct.
15695   if (!getLangOpts().CurrentModule.empty() &&
15696       getLangOpts().CurrentModule != ModuleName) {
15697     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15698         << SourceRange(Path.front().second, Path.back().second)
15699         << getLangOpts().CurrentModule;
15700     return nullptr;
15701   }
15702   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15703 
15704   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15705 
15706   switch (MDK) {
15707   case ModuleDeclKind::Module: {
15708     // FIXME: Check we're not in a submodule.
15709 
15710     // We can't have imported a definition of this module or parsed a module
15711     // map defining it already.
15712     if (auto *M = Map.findModule(ModuleName)) {
15713       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15714       if (M->DefinitionLoc.isValid())
15715         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15716       else if (const auto *FE = M->getASTFile())
15717         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15718             << FE->getName();
15719       return nullptr;
15720     }
15721 
15722     // Create a Module for the module that we're defining.
15723     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15724     assert(Mod && "module creation should not fail");
15725 
15726     // Enter the semantic scope of the module.
15727     ActOnModuleBegin(ModuleLoc, Mod);
15728     return nullptr;
15729   }
15730 
15731   case ModuleDeclKind::Partition:
15732     // FIXME: Check we are in a submodule of the named module.
15733     return nullptr;
15734 
15735   case ModuleDeclKind::Implementation:
15736     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15737         PP.getIdentifierInfo(ModuleName), Path[0].second);
15738 
15739     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15740     if (Import.isInvalid())
15741       return nullptr;
15742     return ConvertDeclToDeclGroup(Import.get());
15743   }
15744 
15745   llvm_unreachable("unexpected module decl kind");
15746 }
15747 
15748 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15749                                    SourceLocation ImportLoc,
15750                                    ModuleIdPath Path) {
15751   Module *Mod =
15752       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15753                                    /*IsIncludeDirective=*/false);
15754   if (!Mod)
15755     return true;
15756 
15757   VisibleModules.setVisible(Mod, ImportLoc);
15758 
15759   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15760 
15761   // FIXME: we should support importing a submodule within a different submodule
15762   // of the same top-level module. Until we do, make it an error rather than
15763   // silently ignoring the import.
15764   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15765   // warn on a redundant import of the current module?
15766   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15767       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15768     Diag(ImportLoc, getLangOpts().isCompilingModule()
15769                         ? diag::err_module_self_import
15770                         : diag::err_module_import_in_implementation)
15771         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15772 
15773   SmallVector<SourceLocation, 2> IdentifierLocs;
15774   Module *ModCheck = Mod;
15775   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15776     // If we've run out of module parents, just drop the remaining identifiers.
15777     // We need the length to be consistent.
15778     if (!ModCheck)
15779       break;
15780     ModCheck = ModCheck->Parent;
15781 
15782     IdentifierLocs.push_back(Path[I].second);
15783   }
15784 
15785   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15786   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15787                                           Mod, IdentifierLocs);
15788   if (!ModuleScopes.empty())
15789     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15790   TU->addDecl(Import);
15791   return Import;
15792 }
15793 
15794 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15795   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15796   BuildModuleInclude(DirectiveLoc, Mod);
15797 }
15798 
15799 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15800   // Determine whether we're in the #include buffer for a module. The #includes
15801   // in that buffer do not qualify as module imports; they're just an
15802   // implementation detail of us building the module.
15803   //
15804   // FIXME: Should we even get ActOnModuleInclude calls for those?
15805   bool IsInModuleIncludes =
15806       TUKind == TU_Module &&
15807       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15808 
15809   bool ShouldAddImport = !IsInModuleIncludes;
15810 
15811   // If this module import was due to an inclusion directive, create an
15812   // implicit import declaration to capture it in the AST.
15813   if (ShouldAddImport) {
15814     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15815     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15816                                                      DirectiveLoc, Mod,
15817                                                      DirectiveLoc);
15818     if (!ModuleScopes.empty())
15819       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15820     TU->addDecl(ImportD);
15821     Consumer.HandleImplicitImportDecl(ImportD);
15822   }
15823 
15824   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15825   VisibleModules.setVisible(Mod, DirectiveLoc);
15826 }
15827 
15828 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15829   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15830 
15831   ModuleScopes.push_back({});
15832   ModuleScopes.back().Module = Mod;
15833   if (getLangOpts().ModulesLocalVisibility)
15834     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15835 
15836   VisibleModules.setVisible(Mod, DirectiveLoc);
15837 }
15838 
15839 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15840   if (getLangOpts().ModulesLocalVisibility) {
15841     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15842     // Leaving a module hides namespace names, so our visible namespace cache
15843     // is now out of date.
15844     VisibleNamespaceCache.clear();
15845   }
15846 
15847   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15848          "left the wrong module scope");
15849   ModuleScopes.pop_back();
15850 
15851   // We got to the end of processing a #include of a local module. Create an
15852   // ImportDecl as we would for an imported module.
15853   FileID File = getSourceManager().getFileID(EofLoc);
15854   assert(File != getSourceManager().getMainFileID() &&
15855          "end of submodule in main source file");
15856   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15857   BuildModuleInclude(DirectiveLoc, Mod);
15858 }
15859 
15860 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15861                                                       Module *Mod) {
15862   // Bail if we're not allowed to implicitly import a module here.
15863   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15864     return;
15865 
15866   // Create the implicit import declaration.
15867   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15868   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15869                                                    Loc, Mod, Loc);
15870   TU->addDecl(ImportD);
15871   Consumer.HandleImplicitImportDecl(ImportD);
15872 
15873   // Make the module visible.
15874   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15875   VisibleModules.setVisible(Mod, Loc);
15876 }
15877 
15878 /// We have parsed the start of an export declaration, including the '{'
15879 /// (if present).
15880 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15881                                  SourceLocation LBraceLoc) {
15882   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15883 
15884   // C++ Modules TS draft:
15885   //   An export-declaration [...] shall not contain more than one
15886   //   export keyword.
15887   //
15888   // The intent here is that an export-declaration cannot appear within another
15889   // export-declaration.
15890   if (D->isExported())
15891     Diag(ExportLoc, diag::err_export_within_export);
15892 
15893   CurContext->addDecl(D);
15894   PushDeclContext(S, D);
15895   return D;
15896 }
15897 
15898 /// Complete the definition of an export declaration.
15899 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15900   auto *ED = cast<ExportDecl>(D);
15901   if (RBraceLoc.isValid())
15902     ED->setRBraceLoc(RBraceLoc);
15903 
15904   // FIXME: Diagnose export of internal-linkage declaration (including
15905   // anonymous namespace).
15906 
15907   PopDeclContext();
15908   return D;
15909 }
15910 
15911 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15912                                       IdentifierInfo* AliasName,
15913                                       SourceLocation PragmaLoc,
15914                                       SourceLocation NameLoc,
15915                                       SourceLocation AliasNameLoc) {
15916   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15917                                          LookupOrdinaryName);
15918   AsmLabelAttr *Attr =
15919       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15920 
15921   // If a declaration that:
15922   // 1) declares a function or a variable
15923   // 2) has external linkage
15924   // already exists, add a label attribute to it.
15925   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15926     if (isDeclExternC(PrevDecl))
15927       PrevDecl->addAttr(Attr);
15928     else
15929       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15930           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15931   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15932   } else
15933     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15934 }
15935 
15936 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15937                              SourceLocation PragmaLoc,
15938                              SourceLocation NameLoc) {
15939   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15940 
15941   if (PrevDecl) {
15942     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15943   } else {
15944     (void)WeakUndeclaredIdentifiers.insert(
15945       std::pair<IdentifierInfo*,WeakInfo>
15946         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15947   }
15948 }
15949 
15950 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15951                                 IdentifierInfo* AliasName,
15952                                 SourceLocation PragmaLoc,
15953                                 SourceLocation NameLoc,
15954                                 SourceLocation AliasNameLoc) {
15955   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15956                                     LookupOrdinaryName);
15957   WeakInfo W = WeakInfo(Name, NameLoc);
15958 
15959   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15960     if (!PrevDecl->hasAttr<AliasAttr>())
15961       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15962         DeclApplyPragmaWeak(TUScope, ND, W);
15963   } else {
15964     (void)WeakUndeclaredIdentifiers.insert(
15965       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15966   }
15967 }
15968 
15969 Decl *Sema::getObjCDeclContext() const {
15970   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15971 }
15972