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 (!inTemplateInstantiation()) {
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 
5534   // Find the shadowed declaration before filtering for scope.
5535   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5536 
5537   // Merge the decl with the existing one if appropriate. If the decl is
5538   // in an outer scope, it isn't the same thing.
5539   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5540                        /*AllowInlineNamespace*/false);
5541   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5542   if (!Previous.empty()) {
5543     Redeclaration = true;
5544     MergeTypedefNameDecl(S, NewTD, Previous);
5545   }
5546 
5547   if (ShadowedDecl && !Redeclaration)
5548     CheckShadow(NewTD, ShadowedDecl, Previous);
5549 
5550   // If this is the C FILE type, notify the AST context.
5551   if (IdentifierInfo *II = NewTD->getIdentifier())
5552     if (!NewTD->isInvalidDecl() &&
5553         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5554       if (II->isStr("FILE"))
5555         Context.setFILEDecl(NewTD);
5556       else if (II->isStr("jmp_buf"))
5557         Context.setjmp_bufDecl(NewTD);
5558       else if (II->isStr("sigjmp_buf"))
5559         Context.setsigjmp_bufDecl(NewTD);
5560       else if (II->isStr("ucontext_t"))
5561         Context.setucontext_tDecl(NewTD);
5562     }
5563 
5564   return NewTD;
5565 }
5566 
5567 /// \brief Determines whether the given declaration is an out-of-scope
5568 /// previous declaration.
5569 ///
5570 /// This routine should be invoked when name lookup has found a
5571 /// previous declaration (PrevDecl) that is not in the scope where a
5572 /// new declaration by the same name is being introduced. If the new
5573 /// declaration occurs in a local scope, previous declarations with
5574 /// linkage may still be considered previous declarations (C99
5575 /// 6.2.2p4-5, C++ [basic.link]p6).
5576 ///
5577 /// \param PrevDecl the previous declaration found by name
5578 /// lookup
5579 ///
5580 /// \param DC the context in which the new declaration is being
5581 /// declared.
5582 ///
5583 /// \returns true if PrevDecl is an out-of-scope previous declaration
5584 /// for a new delcaration with the same name.
5585 static bool
5586 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5587                                 ASTContext &Context) {
5588   if (!PrevDecl)
5589     return false;
5590 
5591   if (!PrevDecl->hasLinkage())
5592     return false;
5593 
5594   if (Context.getLangOpts().CPlusPlus) {
5595     // C++ [basic.link]p6:
5596     //   If there is a visible declaration of an entity with linkage
5597     //   having the same name and type, ignoring entities declared
5598     //   outside the innermost enclosing namespace scope, the block
5599     //   scope declaration declares that same entity and receives the
5600     //   linkage of the previous declaration.
5601     DeclContext *OuterContext = DC->getRedeclContext();
5602     if (!OuterContext->isFunctionOrMethod())
5603       // This rule only applies to block-scope declarations.
5604       return false;
5605 
5606     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5607     if (PrevOuterContext->isRecord())
5608       // We found a member function: ignore it.
5609       return false;
5610 
5611     // Find the innermost enclosing namespace for the new and
5612     // previous declarations.
5613     OuterContext = OuterContext->getEnclosingNamespaceContext();
5614     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5615 
5616     // The previous declaration is in a different namespace, so it
5617     // isn't the same function.
5618     if (!OuterContext->Equals(PrevOuterContext))
5619       return false;
5620   }
5621 
5622   return true;
5623 }
5624 
5625 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5626   CXXScopeSpec &SS = D.getCXXScopeSpec();
5627   if (!SS.isSet()) return;
5628   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5629 }
5630 
5631 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5632   QualType type = decl->getType();
5633   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5634   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5635     // Various kinds of declaration aren't allowed to be __autoreleasing.
5636     unsigned kind = -1U;
5637     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5638       if (var->hasAttr<BlocksAttr>())
5639         kind = 0; // __block
5640       else if (!var->hasLocalStorage())
5641         kind = 1; // global
5642     } else if (isa<ObjCIvarDecl>(decl)) {
5643       kind = 3; // ivar
5644     } else if (isa<FieldDecl>(decl)) {
5645       kind = 2; // field
5646     }
5647 
5648     if (kind != -1U) {
5649       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5650         << kind;
5651     }
5652   } else if (lifetime == Qualifiers::OCL_None) {
5653     // Try to infer lifetime.
5654     if (!type->isObjCLifetimeType())
5655       return false;
5656 
5657     lifetime = type->getObjCARCImplicitLifetime();
5658     type = Context.getLifetimeQualifiedType(type, lifetime);
5659     decl->setType(type);
5660   }
5661 
5662   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5663     // Thread-local variables cannot have lifetime.
5664     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5665         var->getTLSKind()) {
5666       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5667         << var->getType();
5668       return true;
5669     }
5670   }
5671 
5672   return false;
5673 }
5674 
5675 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5676   // Ensure that an auto decl is deduced otherwise the checks below might cache
5677   // the wrong linkage.
5678   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5679 
5680   // 'weak' only applies to declarations with external linkage.
5681   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5682     if (!ND.isExternallyVisible()) {
5683       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5684       ND.dropAttr<WeakAttr>();
5685     }
5686   }
5687   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5688     if (ND.isExternallyVisible()) {
5689       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5690       ND.dropAttr<WeakRefAttr>();
5691       ND.dropAttr<AliasAttr>();
5692     }
5693   }
5694 
5695   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5696     if (VD->hasInit()) {
5697       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5698         assert(VD->isThisDeclarationADefinition() &&
5699                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5700         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5701         VD->dropAttr<AliasAttr>();
5702       }
5703     }
5704   }
5705 
5706   // 'selectany' only applies to externally visible variable declarations.
5707   // It does not apply to functions.
5708   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5709     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5710       S.Diag(Attr->getLocation(),
5711              diag::err_attribute_selectany_non_extern_data);
5712       ND.dropAttr<SelectAnyAttr>();
5713     }
5714   }
5715 
5716   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5717     // dll attributes require external linkage. Static locals may have external
5718     // linkage but still cannot be explicitly imported or exported.
5719     auto *VD = dyn_cast<VarDecl>(&ND);
5720     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5721       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5722         << &ND << Attr;
5723       ND.setInvalidDecl();
5724     }
5725   }
5726 
5727   // Virtual functions cannot be marked as 'notail'.
5728   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5729     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5730       if (MD->isVirtual()) {
5731         S.Diag(ND.getLocation(),
5732                diag::err_invalid_attribute_on_virtual_function)
5733             << Attr;
5734         ND.dropAttr<NotTailCalledAttr>();
5735       }
5736 }
5737 
5738 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5739                                            NamedDecl *NewDecl,
5740                                            bool IsSpecialization,
5741                                            bool IsDefinition) {
5742   if (OldDecl->isInvalidDecl())
5743     return;
5744 
5745   bool IsTemplate = false;
5746   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5747     OldDecl = OldTD->getTemplatedDecl();
5748     IsTemplate = true;
5749     if (!IsSpecialization)
5750       IsDefinition = false;
5751   }
5752   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5753     NewDecl = NewTD->getTemplatedDecl();
5754     IsTemplate = true;
5755   }
5756 
5757   if (!OldDecl || !NewDecl)
5758     return;
5759 
5760   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5761   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5762   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5763   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5764 
5765   // dllimport and dllexport are inheritable attributes so we have to exclude
5766   // inherited attribute instances.
5767   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5768                     (NewExportAttr && !NewExportAttr->isInherited());
5769 
5770   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5771   // the only exception being explicit specializations.
5772   // Implicitly generated declarations are also excluded for now because there
5773   // is no other way to switch these to use dllimport or dllexport.
5774   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5775 
5776   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5777     // Allow with a warning for free functions and global variables.
5778     bool JustWarn = false;
5779     if (!OldDecl->isCXXClassMember()) {
5780       auto *VD = dyn_cast<VarDecl>(OldDecl);
5781       if (VD && !VD->getDescribedVarTemplate())
5782         JustWarn = true;
5783       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5784       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5785         JustWarn = true;
5786     }
5787 
5788     // We cannot change a declaration that's been used because IR has already
5789     // been emitted. Dllimported functions will still work though (modulo
5790     // address equality) as they can use the thunk.
5791     if (OldDecl->isUsed())
5792       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5793         JustWarn = false;
5794 
5795     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5796                                : diag::err_attribute_dll_redeclaration;
5797     S.Diag(NewDecl->getLocation(), DiagID)
5798         << NewDecl
5799         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5800     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5801     if (!JustWarn) {
5802       NewDecl->setInvalidDecl();
5803       return;
5804     }
5805   }
5806 
5807   // A redeclaration is not allowed to drop a dllimport attribute, the only
5808   // exceptions being inline function definitions (except for function
5809   // templates), local extern declarations, qualified friend declarations or
5810   // special MSVC extension: in the last case, the declaration is treated as if
5811   // it were marked dllexport.
5812   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5813   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5814   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5815     // Ignore static data because out-of-line definitions are diagnosed
5816     // separately.
5817     IsStaticDataMember = VD->isStaticDataMember();
5818     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5819                    VarDecl::DeclarationOnly;
5820   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5821     IsInline = FD->isInlined();
5822     IsQualifiedFriend = FD->getQualifier() &&
5823                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5824   }
5825 
5826   if (OldImportAttr && !HasNewAttr &&
5827       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5828       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5829     if (IsMicrosoft && IsDefinition) {
5830       S.Diag(NewDecl->getLocation(),
5831              diag::warn_redeclaration_without_import_attribute)
5832           << NewDecl;
5833       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5834       NewDecl->dropAttr<DLLImportAttr>();
5835       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5836           NewImportAttr->getRange(), S.Context,
5837           NewImportAttr->getSpellingListIndex()));
5838     } else {
5839       S.Diag(NewDecl->getLocation(),
5840              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5841           << NewDecl << OldImportAttr;
5842       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5843       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5844       OldDecl->dropAttr<DLLImportAttr>();
5845       NewDecl->dropAttr<DLLImportAttr>();
5846     }
5847   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5848     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5849     OldDecl->dropAttr<DLLImportAttr>();
5850     NewDecl->dropAttr<DLLImportAttr>();
5851     S.Diag(NewDecl->getLocation(),
5852            diag::warn_dllimport_dropped_from_inline_function)
5853         << NewDecl << OldImportAttr;
5854   }
5855 }
5856 
5857 /// Given that we are within the definition of the given function,
5858 /// will that definition behave like C99's 'inline', where the
5859 /// definition is discarded except for optimization purposes?
5860 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5861   // Try to avoid calling GetGVALinkageForFunction.
5862 
5863   // All cases of this require the 'inline' keyword.
5864   if (!FD->isInlined()) return false;
5865 
5866   // This is only possible in C++ with the gnu_inline attribute.
5867   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5868     return false;
5869 
5870   // Okay, go ahead and call the relatively-more-expensive function.
5871   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5872 }
5873 
5874 /// Determine whether a variable is extern "C" prior to attaching
5875 /// an initializer. We can't just call isExternC() here, because that
5876 /// will also compute and cache whether the declaration is externally
5877 /// visible, which might change when we attach the initializer.
5878 ///
5879 /// This can only be used if the declaration is known to not be a
5880 /// redeclaration of an internal linkage declaration.
5881 ///
5882 /// For instance:
5883 ///
5884 ///   auto x = []{};
5885 ///
5886 /// Attaching the initializer here makes this declaration not externally
5887 /// visible, because its type has internal linkage.
5888 ///
5889 /// FIXME: This is a hack.
5890 template<typename T>
5891 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5892   if (S.getLangOpts().CPlusPlus) {
5893     // In C++, the overloadable attribute negates the effects of extern "C".
5894     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5895       return false;
5896 
5897     // So do CUDA's host/device attributes.
5898     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5899                                  D->template hasAttr<CUDAHostAttr>()))
5900       return false;
5901   }
5902   return D->isExternC();
5903 }
5904 
5905 static bool shouldConsiderLinkage(const VarDecl *VD) {
5906   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5907   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5908     return VD->hasExternalStorage();
5909   if (DC->isFileContext())
5910     return true;
5911   if (DC->isRecord())
5912     return false;
5913   llvm_unreachable("Unexpected context");
5914 }
5915 
5916 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5917   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5918   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5919       isa<OMPDeclareReductionDecl>(DC))
5920     return true;
5921   if (DC->isRecord())
5922     return false;
5923   llvm_unreachable("Unexpected context");
5924 }
5925 
5926 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5927                           AttributeList::Kind Kind) {
5928   for (const AttributeList *L = AttrList; L; L = L->getNext())
5929     if (L->getKind() == Kind)
5930       return true;
5931   return false;
5932 }
5933 
5934 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5935                           AttributeList::Kind Kind) {
5936   // Check decl attributes on the DeclSpec.
5937   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5938     return true;
5939 
5940   // Walk the declarator structure, checking decl attributes that were in a type
5941   // position to the decl itself.
5942   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5943     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5944       return true;
5945   }
5946 
5947   // Finally, check attributes on the decl itself.
5948   return hasParsedAttr(S, PD.getAttributes(), Kind);
5949 }
5950 
5951 /// Adjust the \c DeclContext for a function or variable that might be a
5952 /// function-local external declaration.
5953 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5954   if (!DC->isFunctionOrMethod())
5955     return false;
5956 
5957   // If this is a local extern function or variable declared within a function
5958   // template, don't add it into the enclosing namespace scope until it is
5959   // instantiated; it might have a dependent type right now.
5960   if (DC->isDependentContext())
5961     return true;
5962 
5963   // C++11 [basic.link]p7:
5964   //   When a block scope declaration of an entity with linkage is not found to
5965   //   refer to some other declaration, then that entity is a member of the
5966   //   innermost enclosing namespace.
5967   //
5968   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5969   // semantically-enclosing namespace, not a lexically-enclosing one.
5970   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5971     DC = DC->getParent();
5972   return true;
5973 }
5974 
5975 /// \brief Returns true if given declaration has external C language linkage.
5976 static bool isDeclExternC(const Decl *D) {
5977   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5978     return FD->isExternC();
5979   if (const auto *VD = dyn_cast<VarDecl>(D))
5980     return VD->isExternC();
5981 
5982   llvm_unreachable("Unknown type of decl!");
5983 }
5984 
5985 NamedDecl *Sema::ActOnVariableDeclarator(
5986     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5987     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5988     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5989   QualType R = TInfo->getType();
5990   DeclarationName Name = GetNameForDeclarator(D).getName();
5991 
5992   IdentifierInfo *II = Name.getAsIdentifierInfo();
5993 
5994   if (D.isDecompositionDeclarator()) {
5995     AddToScope = false;
5996     // Take the name of the first declarator as our name for diagnostic
5997     // purposes.
5998     auto &Decomp = D.getDecompositionDeclarator();
5999     if (!Decomp.bindings().empty()) {
6000       II = Decomp.bindings()[0].Name;
6001       Name = II;
6002     }
6003   } else if (!II) {
6004     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6005     return nullptr;
6006   }
6007 
6008   if (getLangOpts().OpenCL) {
6009     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6010     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6011     // argument.
6012     if (R->isImageType() || R->isPipeType()) {
6013       Diag(D.getIdentifierLoc(),
6014            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6015           << R;
6016       D.setInvalidType();
6017       return nullptr;
6018     }
6019 
6020     // OpenCL v1.2 s6.9.r:
6021     // The event type cannot be used to declare a program scope variable.
6022     // OpenCL v2.0 s6.9.q:
6023     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6024     if (NULL == S->getParent()) {
6025       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6026         Diag(D.getIdentifierLoc(),
6027              diag::err_invalid_type_for_program_scope_var) << R;
6028         D.setInvalidType();
6029         return nullptr;
6030       }
6031     }
6032 
6033     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6034     QualType NR = R;
6035     while (NR->isPointerType()) {
6036       if (NR->isFunctionPointerType()) {
6037         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6038         D.setInvalidType();
6039         break;
6040       }
6041       NR = NR->getPointeeType();
6042     }
6043 
6044     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6045       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6046       // half array type (unless the cl_khr_fp16 extension is enabled).
6047       if (Context.getBaseElementType(R)->isHalfType()) {
6048         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6049         D.setInvalidType();
6050       }
6051     }
6052 
6053     // OpenCL v1.2 s6.9.b p4:
6054     // The sampler type cannot be used with the __local and __global address
6055     // space qualifiers.
6056     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6057       R.getAddressSpace() == LangAS::opencl_global)) {
6058       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6059     }
6060 
6061     // OpenCL v1.2 s6.9.r:
6062     // The event type cannot be used with the __local, __constant and __global
6063     // address space qualifiers.
6064     if (R->isEventT()) {
6065       if (R.getAddressSpace()) {
6066         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6067         D.setInvalidType();
6068       }
6069     }
6070   }
6071 
6072   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6073   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6074 
6075   // dllimport globals without explicit storage class are treated as extern. We
6076   // have to change the storage class this early to get the right DeclContext.
6077   if (SC == SC_None && !DC->isRecord() &&
6078       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6079       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6080     SC = SC_Extern;
6081 
6082   DeclContext *OriginalDC = DC;
6083   bool IsLocalExternDecl = SC == SC_Extern &&
6084                            adjustContextForLocalExternDecl(DC);
6085 
6086   if (SCSpec == DeclSpec::SCS_mutable) {
6087     // mutable can only appear on non-static class members, so it's always
6088     // an error here
6089     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6090     D.setInvalidType();
6091     SC = SC_None;
6092   }
6093 
6094   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6095       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6096                               D.getDeclSpec().getStorageClassSpecLoc())) {
6097     // In C++11, the 'register' storage class specifier is deprecated.
6098     // Suppress the warning in system macros, it's used in macros in some
6099     // popular C system headers, such as in glibc's htonl() macro.
6100     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6101          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6102                                    : diag::warn_deprecated_register)
6103       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6104   }
6105 
6106   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6107 
6108   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6109     // C99 6.9p2: The storage-class specifiers auto and register shall not
6110     // appear in the declaration specifiers in an external declaration.
6111     // Global Register+Asm is a GNU extension we support.
6112     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6113       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6114       D.setInvalidType();
6115     }
6116   }
6117 
6118   bool IsMemberSpecialization = false;
6119   bool IsVariableTemplateSpecialization = false;
6120   bool IsPartialSpecialization = false;
6121   bool IsVariableTemplate = false;
6122   VarDecl *NewVD = nullptr;
6123   VarTemplateDecl *NewTemplate = nullptr;
6124   TemplateParameterList *TemplateParams = nullptr;
6125   if (!getLangOpts().CPlusPlus) {
6126     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6127                             D.getIdentifierLoc(), II,
6128                             R, TInfo, SC);
6129 
6130     if (R->getContainedDeducedType())
6131       ParsingInitForAutoVars.insert(NewVD);
6132 
6133     if (D.isInvalidType())
6134       NewVD->setInvalidDecl();
6135   } else {
6136     bool Invalid = false;
6137 
6138     if (DC->isRecord() && !CurContext->isRecord()) {
6139       // This is an out-of-line definition of a static data member.
6140       switch (SC) {
6141       case SC_None:
6142         break;
6143       case SC_Static:
6144         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6145              diag::err_static_out_of_line)
6146           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6147         break;
6148       case SC_Auto:
6149       case SC_Register:
6150       case SC_Extern:
6151         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6152         // to names of variables declared in a block or to function parameters.
6153         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6154         // of class members
6155 
6156         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6157              diag::err_storage_class_for_static_member)
6158           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6159         break;
6160       case SC_PrivateExtern:
6161         llvm_unreachable("C storage class in c++!");
6162       }
6163     }
6164 
6165     if (SC == SC_Static && CurContext->isRecord()) {
6166       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6167         if (RD->isLocalClass())
6168           Diag(D.getIdentifierLoc(),
6169                diag::err_static_data_member_not_allowed_in_local_class)
6170             << Name << RD->getDeclName();
6171 
6172         // C++98 [class.union]p1: If a union contains a static data member,
6173         // the program is ill-formed. C++11 drops this restriction.
6174         if (RD->isUnion())
6175           Diag(D.getIdentifierLoc(),
6176                getLangOpts().CPlusPlus11
6177                  ? diag::warn_cxx98_compat_static_data_member_in_union
6178                  : diag::ext_static_data_member_in_union) << Name;
6179         // We conservatively disallow static data members in anonymous structs.
6180         else if (!RD->getDeclName())
6181           Diag(D.getIdentifierLoc(),
6182                diag::err_static_data_member_not_allowed_in_anon_struct)
6183             << Name << RD->isUnion();
6184       }
6185     }
6186 
6187     // Match up the template parameter lists with the scope specifier, then
6188     // determine whether we have a template or a template specialization.
6189     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6190         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6191         D.getCXXScopeSpec(),
6192         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6193             ? D.getName().TemplateId
6194             : nullptr,
6195         TemplateParamLists,
6196         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6197 
6198     if (TemplateParams) {
6199       if (!TemplateParams->size() &&
6200           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6201         // There is an extraneous 'template<>' for this variable. Complain
6202         // about it, but allow the declaration of the variable.
6203         Diag(TemplateParams->getTemplateLoc(),
6204              diag::err_template_variable_noparams)
6205           << II
6206           << SourceRange(TemplateParams->getTemplateLoc(),
6207                          TemplateParams->getRAngleLoc());
6208         TemplateParams = nullptr;
6209       } else {
6210         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6211           // This is an explicit specialization or a partial specialization.
6212           // FIXME: Check that we can declare a specialization here.
6213           IsVariableTemplateSpecialization = true;
6214           IsPartialSpecialization = TemplateParams->size() > 0;
6215         } else { // if (TemplateParams->size() > 0)
6216           // This is a template declaration.
6217           IsVariableTemplate = true;
6218 
6219           // Check that we can declare a template here.
6220           if (CheckTemplateDeclScope(S, TemplateParams))
6221             return nullptr;
6222 
6223           // Only C++1y supports variable templates (N3651).
6224           Diag(D.getIdentifierLoc(),
6225                getLangOpts().CPlusPlus14
6226                    ? diag::warn_cxx11_compat_variable_template
6227                    : diag::ext_variable_template);
6228         }
6229       }
6230     } else {
6231       assert(
6232           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6233           "should have a 'template<>' for this decl");
6234     }
6235 
6236     if (IsVariableTemplateSpecialization) {
6237       SourceLocation TemplateKWLoc =
6238           TemplateParamLists.size() > 0
6239               ? TemplateParamLists[0]->getTemplateLoc()
6240               : SourceLocation();
6241       DeclResult Res = ActOnVarTemplateSpecialization(
6242           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6243           IsPartialSpecialization);
6244       if (Res.isInvalid())
6245         return nullptr;
6246       NewVD = cast<VarDecl>(Res.get());
6247       AddToScope = false;
6248     } else if (D.isDecompositionDeclarator()) {
6249       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6250                                         D.getIdentifierLoc(), R, TInfo, SC,
6251                                         Bindings);
6252     } else
6253       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6254                               D.getIdentifierLoc(), II, R, TInfo, SC);
6255 
6256     // If this is supposed to be a variable template, create it as such.
6257     if (IsVariableTemplate) {
6258       NewTemplate =
6259           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6260                                   TemplateParams, NewVD);
6261       NewVD->setDescribedVarTemplate(NewTemplate);
6262     }
6263 
6264     // If this decl has an auto type in need of deduction, make a note of the
6265     // Decl so we can diagnose uses of it in its own initializer.
6266     if (R->getContainedDeducedType())
6267       ParsingInitForAutoVars.insert(NewVD);
6268 
6269     if (D.isInvalidType() || Invalid) {
6270       NewVD->setInvalidDecl();
6271       if (NewTemplate)
6272         NewTemplate->setInvalidDecl();
6273     }
6274 
6275     SetNestedNameSpecifier(NewVD, D);
6276 
6277     // If we have any template parameter lists that don't directly belong to
6278     // the variable (matching the scope specifier), store them.
6279     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6280     if (TemplateParamLists.size() > VDTemplateParamLists)
6281       NewVD->setTemplateParameterListsInfo(
6282           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6283 
6284     if (D.getDeclSpec().isConstexprSpecified()) {
6285       NewVD->setConstexpr(true);
6286       // C++1z [dcl.spec.constexpr]p1:
6287       //   A static data member declared with the constexpr specifier is
6288       //   implicitly an inline variable.
6289       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6290         NewVD->setImplicitlyInline();
6291     }
6292 
6293     if (D.getDeclSpec().isConceptSpecified()) {
6294       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6295         VTD->setConcept();
6296 
6297       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6298       // be declared with the thread_local, inline, friend, or constexpr
6299       // specifiers, [...]
6300       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6301         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6302              diag::err_concept_decl_invalid_specifiers)
6303             << 0 << 0;
6304         NewVD->setInvalidDecl(true);
6305       }
6306 
6307       if (D.getDeclSpec().isConstexprSpecified()) {
6308         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6309              diag::err_concept_decl_invalid_specifiers)
6310             << 0 << 3;
6311         NewVD->setInvalidDecl(true);
6312       }
6313 
6314       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6315       // applied only to the definition of a function template or variable
6316       // template, declared in namespace scope.
6317       if (IsVariableTemplateSpecialization) {
6318         Diag(D.getDeclSpec().getConceptSpecLoc(),
6319              diag::err_concept_specified_specialization)
6320             << (IsPartialSpecialization ? 2 : 1);
6321       }
6322 
6323       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6324       // following restrictions:
6325       // - The declared type shall have the type bool.
6326       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6327           !NewVD->isInvalidDecl()) {
6328         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6329         NewVD->setInvalidDecl(true);
6330       }
6331     }
6332   }
6333 
6334   if (D.getDeclSpec().isInlineSpecified()) {
6335     if (!getLangOpts().CPlusPlus) {
6336       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6337           << 0;
6338     } else if (CurContext->isFunctionOrMethod()) {
6339       // 'inline' is not allowed on block scope variable declaration.
6340       Diag(D.getDeclSpec().getInlineSpecLoc(),
6341            diag::err_inline_declaration_block_scope) << Name
6342         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6343     } else {
6344       Diag(D.getDeclSpec().getInlineSpecLoc(),
6345            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6346                                      : diag::ext_inline_variable);
6347       NewVD->setInlineSpecified();
6348     }
6349   }
6350 
6351   // Set the lexical context. If the declarator has a C++ scope specifier, the
6352   // lexical context will be different from the semantic context.
6353   NewVD->setLexicalDeclContext(CurContext);
6354   if (NewTemplate)
6355     NewTemplate->setLexicalDeclContext(CurContext);
6356 
6357   if (IsLocalExternDecl) {
6358     if (D.isDecompositionDeclarator())
6359       for (auto *B : Bindings)
6360         B->setLocalExternDecl();
6361     else
6362       NewVD->setLocalExternDecl();
6363   }
6364 
6365   bool EmitTLSUnsupportedError = false;
6366   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6367     // C++11 [dcl.stc]p4:
6368     //   When thread_local is applied to a variable of block scope the
6369     //   storage-class-specifier static is implied if it does not appear
6370     //   explicitly.
6371     // Core issue: 'static' is not implied if the variable is declared
6372     //   'extern'.
6373     if (NewVD->hasLocalStorage() &&
6374         (SCSpec != DeclSpec::SCS_unspecified ||
6375          TSCS != DeclSpec::TSCS_thread_local ||
6376          !DC->isFunctionOrMethod()))
6377       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6378            diag::err_thread_non_global)
6379         << DeclSpec::getSpecifierName(TSCS);
6380     else if (!Context.getTargetInfo().isTLSSupported()) {
6381       if (getLangOpts().CUDA) {
6382         // Postpone error emission until we've collected attributes required to
6383         // figure out whether it's a host or device variable and whether the
6384         // error should be ignored.
6385         EmitTLSUnsupportedError = true;
6386         // We still need to mark the variable as TLS so it shows up in AST with
6387         // proper storage class for other tools to use even if we're not going
6388         // to emit any code for it.
6389         NewVD->setTSCSpec(TSCS);
6390       } else
6391         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6392              diag::err_thread_unsupported);
6393     } else
6394       NewVD->setTSCSpec(TSCS);
6395   }
6396 
6397   // C99 6.7.4p3
6398   //   An inline definition of a function with external linkage shall
6399   //   not contain a definition of a modifiable object with static or
6400   //   thread storage duration...
6401   // We only apply this when the function is required to be defined
6402   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6403   // that a local variable with thread storage duration still has to
6404   // be marked 'static'.  Also note that it's possible to get these
6405   // semantics in C++ using __attribute__((gnu_inline)).
6406   if (SC == SC_Static && S->getFnParent() != nullptr &&
6407       !NewVD->getType().isConstQualified()) {
6408     FunctionDecl *CurFD = getCurFunctionDecl();
6409     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6410       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6411            diag::warn_static_local_in_extern_inline);
6412       MaybeSuggestAddingStaticToDecl(CurFD);
6413     }
6414   }
6415 
6416   if (D.getDeclSpec().isModulePrivateSpecified()) {
6417     if (IsVariableTemplateSpecialization)
6418       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6419           << (IsPartialSpecialization ? 1 : 0)
6420           << FixItHint::CreateRemoval(
6421                  D.getDeclSpec().getModulePrivateSpecLoc());
6422     else if (IsMemberSpecialization)
6423       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6424         << 2
6425         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6426     else if (NewVD->hasLocalStorage())
6427       Diag(NewVD->getLocation(), diag::err_module_private_local)
6428         << 0 << NewVD->getDeclName()
6429         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6430         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6431     else {
6432       NewVD->setModulePrivate();
6433       if (NewTemplate)
6434         NewTemplate->setModulePrivate();
6435       for (auto *B : Bindings)
6436         B->setModulePrivate();
6437     }
6438   }
6439 
6440   // Handle attributes prior to checking for duplicates in MergeVarDecl
6441   ProcessDeclAttributes(S, NewVD, D);
6442 
6443   if (getLangOpts().CUDA) {
6444     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6445       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6446            diag::err_thread_unsupported);
6447     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6448     // storage [duration]."
6449     if (SC == SC_None && S->getFnParent() != nullptr &&
6450         (NewVD->hasAttr<CUDASharedAttr>() ||
6451          NewVD->hasAttr<CUDAConstantAttr>())) {
6452       NewVD->setStorageClass(SC_Static);
6453     }
6454   }
6455 
6456   // Ensure that dllimport globals without explicit storage class are treated as
6457   // extern. The storage class is set above using parsed attributes. Now we can
6458   // check the VarDecl itself.
6459   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6460          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6461          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6462 
6463   // In auto-retain/release, infer strong retension for variables of
6464   // retainable type.
6465   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6466     NewVD->setInvalidDecl();
6467 
6468   // Handle GNU asm-label extension (encoded as an attribute).
6469   if (Expr *E = (Expr*)D.getAsmLabel()) {
6470     // The parser guarantees this is a string.
6471     StringLiteral *SE = cast<StringLiteral>(E);
6472     StringRef Label = SE->getString();
6473     if (S->getFnParent() != nullptr) {
6474       switch (SC) {
6475       case SC_None:
6476       case SC_Auto:
6477         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6478         break;
6479       case SC_Register:
6480         // Local Named register
6481         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6482             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6483           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6484         break;
6485       case SC_Static:
6486       case SC_Extern:
6487       case SC_PrivateExtern:
6488         break;
6489       }
6490     } else if (SC == SC_Register) {
6491       // Global Named register
6492       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6493         const auto &TI = Context.getTargetInfo();
6494         bool HasSizeMismatch;
6495 
6496         if (!TI.isValidGCCRegisterName(Label))
6497           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6498         else if (!TI.validateGlobalRegisterVariable(Label,
6499                                                     Context.getTypeSize(R),
6500                                                     HasSizeMismatch))
6501           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6502         else if (HasSizeMismatch)
6503           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6504       }
6505 
6506       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6507         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6508         NewVD->setInvalidDecl(true);
6509       }
6510     }
6511 
6512     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6513                                                 Context, Label, 0));
6514   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6515     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6516       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6517     if (I != ExtnameUndeclaredIdentifiers.end()) {
6518       if (isDeclExternC(NewVD)) {
6519         NewVD->addAttr(I->second);
6520         ExtnameUndeclaredIdentifiers.erase(I);
6521       } else
6522         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6523             << /*Variable*/1 << NewVD;
6524     }
6525   }
6526 
6527   // Find the shadowed declaration before filtering for scope.
6528   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6529                                 ? getShadowedDeclaration(NewVD, Previous)
6530                                 : nullptr;
6531 
6532   // Don't consider existing declarations that are in a different
6533   // scope and are out-of-semantic-context declarations (if the new
6534   // declaration has linkage).
6535   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6536                        D.getCXXScopeSpec().isNotEmpty() ||
6537                        IsMemberSpecialization ||
6538                        IsVariableTemplateSpecialization);
6539 
6540   // Check whether the previous declaration is in the same block scope. This
6541   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6542   if (getLangOpts().CPlusPlus &&
6543       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6544     NewVD->setPreviousDeclInSameBlockScope(
6545         Previous.isSingleResult() && !Previous.isShadowed() &&
6546         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6547 
6548   if (!getLangOpts().CPlusPlus) {
6549     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6550   } else {
6551     // If this is an explicit specialization of a static data member, check it.
6552     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6553         CheckMemberSpecialization(NewVD, Previous))
6554       NewVD->setInvalidDecl();
6555 
6556     // Merge the decl with the existing one if appropriate.
6557     if (!Previous.empty()) {
6558       if (Previous.isSingleResult() &&
6559           isa<FieldDecl>(Previous.getFoundDecl()) &&
6560           D.getCXXScopeSpec().isSet()) {
6561         // The user tried to define a non-static data member
6562         // out-of-line (C++ [dcl.meaning]p1).
6563         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6564           << D.getCXXScopeSpec().getRange();
6565         Previous.clear();
6566         NewVD->setInvalidDecl();
6567       }
6568     } else if (D.getCXXScopeSpec().isSet()) {
6569       // No previous declaration in the qualifying scope.
6570       Diag(D.getIdentifierLoc(), diag::err_no_member)
6571         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6572         << D.getCXXScopeSpec().getRange();
6573       NewVD->setInvalidDecl();
6574     }
6575 
6576     if (!IsVariableTemplateSpecialization)
6577       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6578 
6579     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6580     // an explicit specialization (14.8.3) or a partial specialization of a
6581     // concept definition.
6582     if (IsVariableTemplateSpecialization &&
6583         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6584         Previous.isSingleResult()) {
6585       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6586       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6587         if (VarTmpl->isConcept()) {
6588           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6589               << 1                            /*variable*/
6590               << (IsPartialSpecialization ? 2 /*partially specialized*/
6591                                           : 1 /*explicitly specialized*/);
6592           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6593           NewVD->setInvalidDecl();
6594         }
6595       }
6596     }
6597 
6598     if (NewTemplate) {
6599       VarTemplateDecl *PrevVarTemplate =
6600           NewVD->getPreviousDecl()
6601               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6602               : nullptr;
6603 
6604       // Check the template parameter list of this declaration, possibly
6605       // merging in the template parameter list from the previous variable
6606       // template declaration.
6607       if (CheckTemplateParameterList(
6608               TemplateParams,
6609               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6610                               : nullptr,
6611               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6612                DC->isDependentContext())
6613                   ? TPC_ClassTemplateMember
6614                   : TPC_VarTemplate))
6615         NewVD->setInvalidDecl();
6616 
6617       // If we are providing an explicit specialization of a static variable
6618       // template, make a note of that.
6619       if (PrevVarTemplate &&
6620           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6621         PrevVarTemplate->setMemberSpecialization();
6622     }
6623   }
6624 
6625   // Diagnose shadowed variables iff this isn't a redeclaration.
6626   if (ShadowedDecl && !D.isRedeclaration())
6627     CheckShadow(NewVD, ShadowedDecl, Previous);
6628 
6629   ProcessPragmaWeak(S, NewVD);
6630 
6631   // If this is the first declaration of an extern C variable, update
6632   // the map of such variables.
6633   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6634       isIncompleteDeclExternC(*this, NewVD))
6635     RegisterLocallyScopedExternCDecl(NewVD, S);
6636 
6637   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6638     Decl *ManglingContextDecl;
6639     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6640             NewVD->getDeclContext(), ManglingContextDecl)) {
6641       Context.setManglingNumber(
6642           NewVD, MCtx->getManglingNumber(
6643                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6644       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6645     }
6646   }
6647 
6648   // Special handling of variable named 'main'.
6649   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6650       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6651       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6652 
6653     // C++ [basic.start.main]p3
6654     // A program that declares a variable main at global scope is ill-formed.
6655     if (getLangOpts().CPlusPlus)
6656       Diag(D.getLocStart(), diag::err_main_global_variable);
6657 
6658     // In C, and external-linkage variable named main results in undefined
6659     // behavior.
6660     else if (NewVD->hasExternalFormalLinkage())
6661       Diag(D.getLocStart(), diag::warn_main_redefined);
6662   }
6663 
6664   if (D.isRedeclaration() && !Previous.empty()) {
6665     checkDLLAttributeRedeclaration(
6666         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6667         IsMemberSpecialization, D.isFunctionDefinition());
6668   }
6669 
6670   if (NewTemplate) {
6671     if (NewVD->isInvalidDecl())
6672       NewTemplate->setInvalidDecl();
6673     ActOnDocumentableDecl(NewTemplate);
6674     return NewTemplate;
6675   }
6676 
6677   return NewVD;
6678 }
6679 
6680 /// Enum describing the %select options in diag::warn_decl_shadow.
6681 enum ShadowedDeclKind {
6682   SDK_Local,
6683   SDK_Global,
6684   SDK_StaticMember,
6685   SDK_Field,
6686   SDK_Typedef,
6687   SDK_Using
6688 };
6689 
6690 /// Determine what kind of declaration we're shadowing.
6691 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6692                                                 const DeclContext *OldDC) {
6693   if (isa<TypeAliasDecl>(ShadowedDecl))
6694     return SDK_Using;
6695   else if (isa<TypedefDecl>(ShadowedDecl))
6696     return SDK_Typedef;
6697   else if (isa<RecordDecl>(OldDC))
6698     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6699 
6700   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6701 }
6702 
6703 /// Return the location of the capture if the given lambda captures the given
6704 /// variable \p VD, or an invalid source location otherwise.
6705 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6706                                          const VarDecl *VD) {
6707   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6708     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6709       return Capture.getLocation();
6710   }
6711   return SourceLocation();
6712 }
6713 
6714 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6715                                      const LookupResult &R) {
6716   // Only diagnose if we're shadowing an unambiguous field or variable.
6717   if (R.getResultKind() != LookupResult::Found)
6718     return false;
6719 
6720   // Return false if warning is ignored.
6721   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6722 }
6723 
6724 /// \brief Return the declaration shadowed by the given variable \p D, or null
6725 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6726 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6727                                         const LookupResult &R) {
6728   if (!shouldWarnIfShadowedDecl(Diags, R))
6729     return nullptr;
6730 
6731   // Don't diagnose declarations at file scope.
6732   if (D->hasGlobalStorage())
6733     return nullptr;
6734 
6735   NamedDecl *ShadowedDecl = R.getFoundDecl();
6736   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6737              ? ShadowedDecl
6738              : nullptr;
6739 }
6740 
6741 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6742 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6743 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6744                                         const LookupResult &R) {
6745   if (!shouldWarnIfShadowedDecl(Diags, R))
6746     return nullptr;
6747 
6748   NamedDecl *ShadowedDecl = R.getFoundDecl();
6749   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6750 }
6751 
6752 /// \brief Diagnose variable or built-in function shadowing.  Implements
6753 /// -Wshadow.
6754 ///
6755 /// This method is called whenever a VarDecl is added to a "useful"
6756 /// scope.
6757 ///
6758 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6759 /// \param R the lookup of the name
6760 ///
6761 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6762                        const LookupResult &R) {
6763   DeclContext *NewDC = D->getDeclContext();
6764 
6765   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6766     // Fields are not shadowed by variables in C++ static methods.
6767     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6768       if (MD->isStatic())
6769         return;
6770 
6771     // Fields shadowed by constructor parameters are a special case. Usually
6772     // the constructor initializes the field with the parameter.
6773     if (isa<CXXConstructorDecl>(NewDC))
6774       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6775         // Remember that this was shadowed so we can either warn about its
6776         // modification or its existence depending on warning settings.
6777         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6778         return;
6779       }
6780   }
6781 
6782   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6783     if (shadowedVar->isExternC()) {
6784       // For shadowing external vars, make sure that we point to the global
6785       // declaration, not a locally scoped extern declaration.
6786       for (auto I : shadowedVar->redecls())
6787         if (I->isFileVarDecl()) {
6788           ShadowedDecl = I;
6789           break;
6790         }
6791     }
6792 
6793   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6794 
6795   unsigned WarningDiag = diag::warn_decl_shadow;
6796   SourceLocation CaptureLoc;
6797   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6798       isa<CXXMethodDecl>(NewDC)) {
6799     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6800       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6801         if (RD->getLambdaCaptureDefault() == LCD_None) {
6802           // Try to avoid warnings for lambdas with an explicit capture list.
6803           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6804           // Warn only when the lambda captures the shadowed decl explicitly.
6805           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6806           if (CaptureLoc.isInvalid())
6807             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6808         } else {
6809           // Remember that this was shadowed so we can avoid the warning if the
6810           // shadowed decl isn't captured and the warning settings allow it.
6811           cast<LambdaScopeInfo>(getCurFunction())
6812               ->ShadowingDecls.push_back(
6813                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6814           return;
6815         }
6816       }
6817     }
6818   }
6819 
6820   // Only warn about certain kinds of shadowing for class members.
6821   if (NewDC && NewDC->isRecord()) {
6822     // In particular, don't warn about shadowing non-class members.
6823     if (!OldDC->isRecord())
6824       return;
6825 
6826     // TODO: should we warn about static data members shadowing
6827     // static data members from base classes?
6828 
6829     // TODO: don't diagnose for inaccessible shadowed members.
6830     // This is hard to do perfectly because we might friend the
6831     // shadowing context, but that's just a false negative.
6832   }
6833 
6834 
6835   DeclarationName Name = R.getLookupName();
6836 
6837   // Emit warning and note.
6838   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6839     return;
6840   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6841   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6842   if (!CaptureLoc.isInvalid())
6843     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6844         << Name << /*explicitly*/ 1;
6845   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6846 }
6847 
6848 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6849 /// when these variables are captured by the lambda.
6850 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6851   for (const auto &Shadow : LSI->ShadowingDecls) {
6852     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6853     // Try to avoid the warning when the shadowed decl isn't captured.
6854     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6855     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6856     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6857                                        ? diag::warn_decl_shadow_uncaptured_local
6858                                        : diag::warn_decl_shadow)
6859         << Shadow.VD->getDeclName()
6860         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6861     if (!CaptureLoc.isInvalid())
6862       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6863           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6864     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6865   }
6866 }
6867 
6868 /// \brief Check -Wshadow without the advantage of a previous lookup.
6869 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6870   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6871     return;
6872 
6873   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6874                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6875   LookupName(R, S);
6876   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6877     CheckShadow(D, ShadowedDecl, R);
6878 }
6879 
6880 /// Check if 'E', which is an expression that is about to be modified, refers
6881 /// to a constructor parameter that shadows a field.
6882 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6883   // Quickly ignore expressions that can't be shadowing ctor parameters.
6884   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6885     return;
6886   E = E->IgnoreParenImpCasts();
6887   auto *DRE = dyn_cast<DeclRefExpr>(E);
6888   if (!DRE)
6889     return;
6890   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6891   auto I = ShadowingDecls.find(D);
6892   if (I == ShadowingDecls.end())
6893     return;
6894   const NamedDecl *ShadowedDecl = I->second;
6895   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6896   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6897   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6898   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6899 
6900   // Avoid issuing multiple warnings about the same decl.
6901   ShadowingDecls.erase(I);
6902 }
6903 
6904 /// Check for conflict between this global or extern "C" declaration and
6905 /// previous global or extern "C" declarations. This is only used in C++.
6906 template<typename T>
6907 static bool checkGlobalOrExternCConflict(
6908     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6909   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6910   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6911 
6912   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6913     // The common case: this global doesn't conflict with any extern "C"
6914     // declaration.
6915     return false;
6916   }
6917 
6918   if (Prev) {
6919     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6920       // Both the old and new declarations have C language linkage. This is a
6921       // redeclaration.
6922       Previous.clear();
6923       Previous.addDecl(Prev);
6924       return true;
6925     }
6926 
6927     // This is a global, non-extern "C" declaration, and there is a previous
6928     // non-global extern "C" declaration. Diagnose if this is a variable
6929     // declaration.
6930     if (!isa<VarDecl>(ND))
6931       return false;
6932   } else {
6933     // The declaration is extern "C". Check for any declaration in the
6934     // translation unit which might conflict.
6935     if (IsGlobal) {
6936       // We have already performed the lookup into the translation unit.
6937       IsGlobal = false;
6938       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6939            I != E; ++I) {
6940         if (isa<VarDecl>(*I)) {
6941           Prev = *I;
6942           break;
6943         }
6944       }
6945     } else {
6946       DeclContext::lookup_result R =
6947           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6948       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6949            I != E; ++I) {
6950         if (isa<VarDecl>(*I)) {
6951           Prev = *I;
6952           break;
6953         }
6954         // FIXME: If we have any other entity with this name in global scope,
6955         // the declaration is ill-formed, but that is a defect: it breaks the
6956         // 'stat' hack, for instance. Only variables can have mangled name
6957         // clashes with extern "C" declarations, so only they deserve a
6958         // diagnostic.
6959       }
6960     }
6961 
6962     if (!Prev)
6963       return false;
6964   }
6965 
6966   // Use the first declaration's location to ensure we point at something which
6967   // is lexically inside an extern "C" linkage-spec.
6968   assert(Prev && "should have found a previous declaration to diagnose");
6969   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6970     Prev = FD->getFirstDecl();
6971   else
6972     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6973 
6974   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6975     << IsGlobal << ND;
6976   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6977     << IsGlobal;
6978   return false;
6979 }
6980 
6981 /// Apply special rules for handling extern "C" declarations. Returns \c true
6982 /// if we have found that this is a redeclaration of some prior entity.
6983 ///
6984 /// Per C++ [dcl.link]p6:
6985 ///   Two declarations [for a function or variable] with C language linkage
6986 ///   with the same name that appear in different scopes refer to the same
6987 ///   [entity]. An entity with C language linkage shall not be declared with
6988 ///   the same name as an entity in global scope.
6989 template<typename T>
6990 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6991                                                   LookupResult &Previous) {
6992   if (!S.getLangOpts().CPlusPlus) {
6993     // In C, when declaring a global variable, look for a corresponding 'extern'
6994     // variable declared in function scope. We don't need this in C++, because
6995     // we find local extern decls in the surrounding file-scope DeclContext.
6996     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6997       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6998         Previous.clear();
6999         Previous.addDecl(Prev);
7000         return true;
7001       }
7002     }
7003     return false;
7004   }
7005 
7006   // A declaration in the translation unit can conflict with an extern "C"
7007   // declaration.
7008   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7009     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7010 
7011   // An extern "C" declaration can conflict with a declaration in the
7012   // translation unit or can be a redeclaration of an extern "C" declaration
7013   // in another scope.
7014   if (isIncompleteDeclExternC(S,ND))
7015     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7016 
7017   // Neither global nor extern "C": nothing to do.
7018   return false;
7019 }
7020 
7021 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7022   // If the decl is already known invalid, don't check it.
7023   if (NewVD->isInvalidDecl())
7024     return;
7025 
7026   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7027   QualType T = TInfo->getType();
7028 
7029   // Defer checking an 'auto' type until its initializer is attached.
7030   if (T->isUndeducedType())
7031     return;
7032 
7033   if (NewVD->hasAttrs())
7034     CheckAlignasUnderalignment(NewVD);
7035 
7036   if (T->isObjCObjectType()) {
7037     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7038       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7039     T = Context.getObjCObjectPointerType(T);
7040     NewVD->setType(T);
7041   }
7042 
7043   // Emit an error if an address space was applied to decl with local storage.
7044   // This includes arrays of objects with address space qualifiers, but not
7045   // automatic variables that point to other address spaces.
7046   // ISO/IEC TR 18037 S5.1.2
7047   if (!getLangOpts().OpenCL
7048       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7049     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7050     NewVD->setInvalidDecl();
7051     return;
7052   }
7053 
7054   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7055   // scope.
7056   if (getLangOpts().OpenCLVersion == 120 &&
7057       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7058       NewVD->isStaticLocal()) {
7059     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7060     NewVD->setInvalidDecl();
7061     return;
7062   }
7063 
7064   if (getLangOpts().OpenCL) {
7065     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7066     if (NewVD->hasAttr<BlocksAttr>()) {
7067       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7068       return;
7069     }
7070 
7071     if (T->isBlockPointerType()) {
7072       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7073       // can't use 'extern' storage class.
7074       if (!T.isConstQualified()) {
7075         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7076             << 0 /*const*/;
7077         NewVD->setInvalidDecl();
7078         return;
7079       }
7080       if (NewVD->hasExternalStorage()) {
7081         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7082         NewVD->setInvalidDecl();
7083         return;
7084       }
7085     }
7086     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7087     // __constant address space.
7088     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7089     // variables inside a function can also be declared in the global
7090     // address space.
7091     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7092         NewVD->hasExternalStorage()) {
7093       if (!T->isSamplerT() &&
7094           !(T.getAddressSpace() == LangAS::opencl_constant ||
7095             (T.getAddressSpace() == LangAS::opencl_global &&
7096              getLangOpts().OpenCLVersion == 200))) {
7097         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7098         if (getLangOpts().OpenCLVersion == 200)
7099           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7100               << Scope << "global or constant";
7101         else
7102           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7103               << Scope << "constant";
7104         NewVD->setInvalidDecl();
7105         return;
7106       }
7107     } else {
7108       if (T.getAddressSpace() == LangAS::opencl_global) {
7109         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7110             << 1 /*is any function*/ << "global";
7111         NewVD->setInvalidDecl();
7112         return;
7113       }
7114       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7115       // in functions.
7116       if (T.getAddressSpace() == LangAS::opencl_constant ||
7117           T.getAddressSpace() == LangAS::opencl_local) {
7118         FunctionDecl *FD = getCurFunctionDecl();
7119         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7120           if (T.getAddressSpace() == LangAS::opencl_constant)
7121             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7122                 << 0 /*non-kernel only*/ << "constant";
7123           else
7124             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7125                 << 0 /*non-kernel only*/ << "local";
7126           NewVD->setInvalidDecl();
7127           return;
7128         }
7129       }
7130     }
7131   }
7132 
7133   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7134       && !NewVD->hasAttr<BlocksAttr>()) {
7135     if (getLangOpts().getGC() != LangOptions::NonGC)
7136       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7137     else {
7138       assert(!getLangOpts().ObjCAutoRefCount);
7139       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7140     }
7141   }
7142 
7143   bool isVM = T->isVariablyModifiedType();
7144   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7145       NewVD->hasAttr<BlocksAttr>())
7146     getCurFunction()->setHasBranchProtectedScope();
7147 
7148   if ((isVM && NewVD->hasLinkage()) ||
7149       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7150     bool SizeIsNegative;
7151     llvm::APSInt Oversized;
7152     TypeSourceInfo *FixedTInfo =
7153       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7154                                                     SizeIsNegative, Oversized);
7155     if (!FixedTInfo && T->isVariableArrayType()) {
7156       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7157       // FIXME: This won't give the correct result for
7158       // int a[10][n];
7159       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7160 
7161       if (NewVD->isFileVarDecl())
7162         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7163         << SizeRange;
7164       else if (NewVD->isStaticLocal())
7165         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7166         << SizeRange;
7167       else
7168         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7169         << SizeRange;
7170       NewVD->setInvalidDecl();
7171       return;
7172     }
7173 
7174     if (!FixedTInfo) {
7175       if (NewVD->isFileVarDecl())
7176         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7177       else
7178         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7179       NewVD->setInvalidDecl();
7180       return;
7181     }
7182 
7183     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7184     NewVD->setType(FixedTInfo->getType());
7185     NewVD->setTypeSourceInfo(FixedTInfo);
7186   }
7187 
7188   if (T->isVoidType()) {
7189     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7190     //                    of objects and functions.
7191     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7192       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7193         << T;
7194       NewVD->setInvalidDecl();
7195       return;
7196     }
7197   }
7198 
7199   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7200     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7201     NewVD->setInvalidDecl();
7202     return;
7203   }
7204 
7205   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7206     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7207     NewVD->setInvalidDecl();
7208     return;
7209   }
7210 
7211   if (NewVD->isConstexpr() && !T->isDependentType() &&
7212       RequireLiteralType(NewVD->getLocation(), T,
7213                          diag::err_constexpr_var_non_literal)) {
7214     NewVD->setInvalidDecl();
7215     return;
7216   }
7217 }
7218 
7219 /// \brief Perform semantic checking on a newly-created variable
7220 /// declaration.
7221 ///
7222 /// This routine performs all of the type-checking required for a
7223 /// variable declaration once it has been built. It is used both to
7224 /// check variables after they have been parsed and their declarators
7225 /// have been translated into a declaration, and to check variables
7226 /// that have been instantiated from a template.
7227 ///
7228 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7229 ///
7230 /// Returns true if the variable declaration is a redeclaration.
7231 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7232   CheckVariableDeclarationType(NewVD);
7233 
7234   // If the decl is already known invalid, don't check it.
7235   if (NewVD->isInvalidDecl())
7236     return false;
7237 
7238   // If we did not find anything by this name, look for a non-visible
7239   // extern "C" declaration with the same name.
7240   if (Previous.empty() &&
7241       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7242     Previous.setShadowed();
7243 
7244   if (!Previous.empty()) {
7245     MergeVarDecl(NewVD, Previous);
7246     return true;
7247   }
7248   return false;
7249 }
7250 
7251 namespace {
7252 struct FindOverriddenMethod {
7253   Sema *S;
7254   CXXMethodDecl *Method;
7255 
7256   /// Member lookup function that determines whether a given C++
7257   /// method overrides a method in a base class, to be used with
7258   /// CXXRecordDecl::lookupInBases().
7259   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7260     RecordDecl *BaseRecord =
7261         Specifier->getType()->getAs<RecordType>()->getDecl();
7262 
7263     DeclarationName Name = Method->getDeclName();
7264 
7265     // FIXME: Do we care about other names here too?
7266     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7267       // We really want to find the base class destructor here.
7268       QualType T = S->Context.getTypeDeclType(BaseRecord);
7269       CanQualType CT = S->Context.getCanonicalType(T);
7270 
7271       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7272     }
7273 
7274     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7275          Path.Decls = Path.Decls.slice(1)) {
7276       NamedDecl *D = Path.Decls.front();
7277       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7278         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7279           return true;
7280       }
7281     }
7282 
7283     return false;
7284   }
7285 };
7286 
7287 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7288 } // end anonymous namespace
7289 
7290 /// \brief Report an error regarding overriding, along with any relevant
7291 /// overriden methods.
7292 ///
7293 /// \param DiagID the primary error to report.
7294 /// \param MD the overriding method.
7295 /// \param OEK which overrides to include as notes.
7296 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7297                             OverrideErrorKind OEK = OEK_All) {
7298   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7299   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7300                                       E = MD->end_overridden_methods();
7301        I != E; ++I) {
7302     // This check (& the OEK parameter) could be replaced by a predicate, but
7303     // without lambdas that would be overkill. This is still nicer than writing
7304     // out the diag loop 3 times.
7305     if ((OEK == OEK_All) ||
7306         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7307         (OEK == OEK_Deleted && (*I)->isDeleted()))
7308       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7309   }
7310 }
7311 
7312 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7313 /// and if so, check that it's a valid override and remember it.
7314 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7315   // Look for methods in base classes that this method might override.
7316   CXXBasePaths Paths;
7317   FindOverriddenMethod FOM;
7318   FOM.Method = MD;
7319   FOM.S = this;
7320   bool hasDeletedOverridenMethods = false;
7321   bool hasNonDeletedOverridenMethods = false;
7322   bool AddedAny = false;
7323   if (DC->lookupInBases(FOM, Paths)) {
7324     for (auto *I : Paths.found_decls()) {
7325       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7326         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7327         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7328             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7329             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7330             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7331           hasDeletedOverridenMethods |= OldMD->isDeleted();
7332           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7333           AddedAny = true;
7334         }
7335       }
7336     }
7337   }
7338 
7339   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7340     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7341   }
7342   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7343     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7344   }
7345 
7346   return AddedAny;
7347 }
7348 
7349 namespace {
7350   // Struct for holding all of the extra arguments needed by
7351   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7352   struct ActOnFDArgs {
7353     Scope *S;
7354     Declarator &D;
7355     MultiTemplateParamsArg TemplateParamLists;
7356     bool AddToScope;
7357   };
7358 } // end anonymous namespace
7359 
7360 namespace {
7361 
7362 // Callback to only accept typo corrections that have a non-zero edit distance.
7363 // Also only accept corrections that have the same parent decl.
7364 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7365  public:
7366   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7367                             CXXRecordDecl *Parent)
7368       : Context(Context), OriginalFD(TypoFD),
7369         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7370 
7371   bool ValidateCandidate(const TypoCorrection &candidate) override {
7372     if (candidate.getEditDistance() == 0)
7373       return false;
7374 
7375     SmallVector<unsigned, 1> MismatchedParams;
7376     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7377                                           CDeclEnd = candidate.end();
7378          CDecl != CDeclEnd; ++CDecl) {
7379       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7380 
7381       if (FD && !FD->hasBody() &&
7382           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7383         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7384           CXXRecordDecl *Parent = MD->getParent();
7385           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7386             return true;
7387         } else if (!ExpectedParent) {
7388           return true;
7389         }
7390       }
7391     }
7392 
7393     return false;
7394   }
7395 
7396  private:
7397   ASTContext &Context;
7398   FunctionDecl *OriginalFD;
7399   CXXRecordDecl *ExpectedParent;
7400 };
7401 
7402 } // end anonymous namespace
7403 
7404 /// \brief Generate diagnostics for an invalid function redeclaration.
7405 ///
7406 /// This routine handles generating the diagnostic messages for an invalid
7407 /// function redeclaration, including finding possible similar declarations
7408 /// or performing typo correction if there are no previous declarations with
7409 /// the same name.
7410 ///
7411 /// Returns a NamedDecl iff typo correction was performed and substituting in
7412 /// the new declaration name does not cause new errors.
7413 static NamedDecl *DiagnoseInvalidRedeclaration(
7414     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7415     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7416   DeclarationName Name = NewFD->getDeclName();
7417   DeclContext *NewDC = NewFD->getDeclContext();
7418   SmallVector<unsigned, 1> MismatchedParams;
7419   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7420   TypoCorrection Correction;
7421   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7422   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7423                                    : diag::err_member_decl_does_not_match;
7424   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7425                     IsLocalFriend ? Sema::LookupLocalFriendName
7426                                   : Sema::LookupOrdinaryName,
7427                     Sema::ForRedeclaration);
7428 
7429   NewFD->setInvalidDecl();
7430   if (IsLocalFriend)
7431     SemaRef.LookupName(Prev, S);
7432   else
7433     SemaRef.LookupQualifiedName(Prev, NewDC);
7434   assert(!Prev.isAmbiguous() &&
7435          "Cannot have an ambiguity in previous-declaration lookup");
7436   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7437   if (!Prev.empty()) {
7438     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7439          Func != FuncEnd; ++Func) {
7440       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7441       if (FD &&
7442           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7443         // Add 1 to the index so that 0 can mean the mismatch didn't
7444         // involve a parameter
7445         unsigned ParamNum =
7446             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7447         NearMatches.push_back(std::make_pair(FD, ParamNum));
7448       }
7449     }
7450   // If the qualified name lookup yielded nothing, try typo correction
7451   } else if ((Correction = SemaRef.CorrectTypo(
7452                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7453                   &ExtraArgs.D.getCXXScopeSpec(),
7454                   llvm::make_unique<DifferentNameValidatorCCC>(
7455                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7456                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7457     // Set up everything for the call to ActOnFunctionDeclarator
7458     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7459                               ExtraArgs.D.getIdentifierLoc());
7460     Previous.clear();
7461     Previous.setLookupName(Correction.getCorrection());
7462     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7463                                     CDeclEnd = Correction.end();
7464          CDecl != CDeclEnd; ++CDecl) {
7465       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7466       if (FD && !FD->hasBody() &&
7467           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7468         Previous.addDecl(FD);
7469       }
7470     }
7471     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7472 
7473     NamedDecl *Result;
7474     // Retry building the function declaration with the new previous
7475     // declarations, and with errors suppressed.
7476     {
7477       // Trap errors.
7478       Sema::SFINAETrap Trap(SemaRef);
7479 
7480       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7481       // pieces need to verify the typo-corrected C++ declaration and hopefully
7482       // eliminate the need for the parameter pack ExtraArgs.
7483       Result = SemaRef.ActOnFunctionDeclarator(
7484           ExtraArgs.S, ExtraArgs.D,
7485           Correction.getCorrectionDecl()->getDeclContext(),
7486           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7487           ExtraArgs.AddToScope);
7488 
7489       if (Trap.hasErrorOccurred())
7490         Result = nullptr;
7491     }
7492 
7493     if (Result) {
7494       // Determine which correction we picked.
7495       Decl *Canonical = Result->getCanonicalDecl();
7496       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7497            I != E; ++I)
7498         if ((*I)->getCanonicalDecl() == Canonical)
7499           Correction.setCorrectionDecl(*I);
7500 
7501       SemaRef.diagnoseTypo(
7502           Correction,
7503           SemaRef.PDiag(IsLocalFriend
7504                           ? diag::err_no_matching_local_friend_suggest
7505                           : diag::err_member_decl_does_not_match_suggest)
7506             << Name << NewDC << IsDefinition);
7507       return Result;
7508     }
7509 
7510     // Pretend the typo correction never occurred
7511     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7512                               ExtraArgs.D.getIdentifierLoc());
7513     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7514     Previous.clear();
7515     Previous.setLookupName(Name);
7516   }
7517 
7518   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7519       << Name << NewDC << IsDefinition << NewFD->getLocation();
7520 
7521   bool NewFDisConst = false;
7522   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7523     NewFDisConst = NewMD->isConst();
7524 
7525   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7526        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7527        NearMatch != NearMatchEnd; ++NearMatch) {
7528     FunctionDecl *FD = NearMatch->first;
7529     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7530     bool FDisConst = MD && MD->isConst();
7531     bool IsMember = MD || !IsLocalFriend;
7532 
7533     // FIXME: These notes are poorly worded for the local friend case.
7534     if (unsigned Idx = NearMatch->second) {
7535       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7536       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7537       if (Loc.isInvalid()) Loc = FD->getLocation();
7538       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7539                                  : diag::note_local_decl_close_param_match)
7540         << Idx << FDParam->getType()
7541         << NewFD->getParamDecl(Idx - 1)->getType();
7542     } else if (FDisConst != NewFDisConst) {
7543       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7544           << NewFDisConst << FD->getSourceRange().getEnd();
7545     } else
7546       SemaRef.Diag(FD->getLocation(),
7547                    IsMember ? diag::note_member_def_close_match
7548                             : diag::note_local_decl_close_match);
7549   }
7550   return nullptr;
7551 }
7552 
7553 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7554   switch (D.getDeclSpec().getStorageClassSpec()) {
7555   default: llvm_unreachable("Unknown storage class!");
7556   case DeclSpec::SCS_auto:
7557   case DeclSpec::SCS_register:
7558   case DeclSpec::SCS_mutable:
7559     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7560                  diag::err_typecheck_sclass_func);
7561     D.getMutableDeclSpec().ClearStorageClassSpecs();
7562     D.setInvalidType();
7563     break;
7564   case DeclSpec::SCS_unspecified: break;
7565   case DeclSpec::SCS_extern:
7566     if (D.getDeclSpec().isExternInLinkageSpec())
7567       return SC_None;
7568     return SC_Extern;
7569   case DeclSpec::SCS_static: {
7570     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7571       // C99 6.7.1p5:
7572       //   The declaration of an identifier for a function that has
7573       //   block scope shall have no explicit storage-class specifier
7574       //   other than extern
7575       // See also (C++ [dcl.stc]p4).
7576       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7577                    diag::err_static_block_func);
7578       break;
7579     } else
7580       return SC_Static;
7581   }
7582   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7583   }
7584 
7585   // No explicit storage class has already been returned
7586   return SC_None;
7587 }
7588 
7589 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7590                                            DeclContext *DC, QualType &R,
7591                                            TypeSourceInfo *TInfo,
7592                                            StorageClass SC,
7593                                            bool &IsVirtualOkay) {
7594   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7595   DeclarationName Name = NameInfo.getName();
7596 
7597   FunctionDecl *NewFD = nullptr;
7598   bool isInline = D.getDeclSpec().isInlineSpecified();
7599 
7600   if (!SemaRef.getLangOpts().CPlusPlus) {
7601     // Determine whether the function was written with a
7602     // prototype. This true when:
7603     //   - there is a prototype in the declarator, or
7604     //   - the type R of the function is some kind of typedef or other non-
7605     //     attributed reference to a type name (which eventually refers to a
7606     //     function type).
7607     bool HasPrototype =
7608       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7609       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7610 
7611     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7612                                  D.getLocStart(), NameInfo, R,
7613                                  TInfo, SC, isInline,
7614                                  HasPrototype, false);
7615     if (D.isInvalidType())
7616       NewFD->setInvalidDecl();
7617 
7618     return NewFD;
7619   }
7620 
7621   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7622   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7623 
7624   // Check that the return type is not an abstract class type.
7625   // For record types, this is done by the AbstractClassUsageDiagnoser once
7626   // the class has been completely parsed.
7627   if (!DC->isRecord() &&
7628       SemaRef.RequireNonAbstractType(
7629           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7630           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7631     D.setInvalidType();
7632 
7633   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7634     // This is a C++ constructor declaration.
7635     assert(DC->isRecord() &&
7636            "Constructors can only be declared in a member context");
7637 
7638     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7639     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7640                                       D.getLocStart(), NameInfo,
7641                                       R, TInfo, isExplicit, isInline,
7642                                       /*isImplicitlyDeclared=*/false,
7643                                       isConstexpr);
7644 
7645   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7646     // This is a C++ destructor declaration.
7647     if (DC->isRecord()) {
7648       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7649       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7650       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7651                                         SemaRef.Context, Record,
7652                                         D.getLocStart(),
7653                                         NameInfo, R, TInfo, isInline,
7654                                         /*isImplicitlyDeclared=*/false);
7655 
7656       // If the class is complete, then we now create the implicit exception
7657       // specification. If the class is incomplete or dependent, we can't do
7658       // it yet.
7659       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7660           Record->getDefinition() && !Record->isBeingDefined() &&
7661           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7662         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7663       }
7664 
7665       IsVirtualOkay = true;
7666       return NewDD;
7667 
7668     } else {
7669       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7670       D.setInvalidType();
7671 
7672       // Create a FunctionDecl to satisfy the function definition parsing
7673       // code path.
7674       return FunctionDecl::Create(SemaRef.Context, DC,
7675                                   D.getLocStart(),
7676                                   D.getIdentifierLoc(), Name, R, TInfo,
7677                                   SC, isInline,
7678                                   /*hasPrototype=*/true, isConstexpr);
7679     }
7680 
7681   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7682     if (!DC->isRecord()) {
7683       SemaRef.Diag(D.getIdentifierLoc(),
7684            diag::err_conv_function_not_member);
7685       return nullptr;
7686     }
7687 
7688     SemaRef.CheckConversionDeclarator(D, R, SC);
7689     IsVirtualOkay = true;
7690     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7691                                      D.getLocStart(), NameInfo,
7692                                      R, TInfo, isInline, isExplicit,
7693                                      isConstexpr, SourceLocation());
7694 
7695   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7696     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7697 
7698     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7699                                          isExplicit, NameInfo, R, TInfo,
7700                                          D.getLocEnd());
7701   } else if (DC->isRecord()) {
7702     // If the name of the function is the same as the name of the record,
7703     // then this must be an invalid constructor that has a return type.
7704     // (The parser checks for a return type and makes the declarator a
7705     // constructor if it has no return type).
7706     if (Name.getAsIdentifierInfo() &&
7707         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7708       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7709         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7710         << SourceRange(D.getIdentifierLoc());
7711       return nullptr;
7712     }
7713 
7714     // This is a C++ method declaration.
7715     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7716                                                cast<CXXRecordDecl>(DC),
7717                                                D.getLocStart(), NameInfo, R,
7718                                                TInfo, SC, isInline,
7719                                                isConstexpr, SourceLocation());
7720     IsVirtualOkay = !Ret->isStatic();
7721     return Ret;
7722   } else {
7723     bool isFriend =
7724         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7725     if (!isFriend && SemaRef.CurContext->isRecord())
7726       return nullptr;
7727 
7728     // Determine whether the function was written with a
7729     // prototype. This true when:
7730     //   - we're in C++ (where every function has a prototype),
7731     return FunctionDecl::Create(SemaRef.Context, DC,
7732                                 D.getLocStart(),
7733                                 NameInfo, R, TInfo, SC, isInline,
7734                                 true/*HasPrototype*/, isConstexpr);
7735   }
7736 }
7737 
7738 enum OpenCLParamType {
7739   ValidKernelParam,
7740   PtrPtrKernelParam,
7741   PtrKernelParam,
7742   InvalidAddrSpacePtrKernelParam,
7743   InvalidKernelParam,
7744   RecordKernelParam
7745 };
7746 
7747 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7748   if (PT->isPointerType()) {
7749     QualType PointeeType = PT->getPointeeType();
7750     if (PointeeType->isPointerType())
7751       return PtrPtrKernelParam;
7752     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7753         PointeeType.getAddressSpace() == 0)
7754       return InvalidAddrSpacePtrKernelParam;
7755     return PtrKernelParam;
7756   }
7757 
7758   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7759   // be used as builtin types.
7760 
7761   if (PT->isImageType())
7762     return PtrKernelParam;
7763 
7764   if (PT->isBooleanType())
7765     return InvalidKernelParam;
7766 
7767   if (PT->isEventT())
7768     return InvalidKernelParam;
7769 
7770   // OpenCL extension spec v1.2 s9.5:
7771   // This extension adds support for half scalar and vector types as built-in
7772   // types that can be used for arithmetic operations, conversions etc.
7773   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7774     return InvalidKernelParam;
7775 
7776   if (PT->isRecordType())
7777     return RecordKernelParam;
7778 
7779   return ValidKernelParam;
7780 }
7781 
7782 static void checkIsValidOpenCLKernelParameter(
7783   Sema &S,
7784   Declarator &D,
7785   ParmVarDecl *Param,
7786   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7787   QualType PT = Param->getType();
7788 
7789   // Cache the valid types we encounter to avoid rechecking structs that are
7790   // used again
7791   if (ValidTypes.count(PT.getTypePtr()))
7792     return;
7793 
7794   switch (getOpenCLKernelParameterType(S, PT)) {
7795   case PtrPtrKernelParam:
7796     // OpenCL v1.2 s6.9.a:
7797     // A kernel function argument cannot be declared as a
7798     // pointer to a pointer type.
7799     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7800     D.setInvalidType();
7801     return;
7802 
7803   case InvalidAddrSpacePtrKernelParam:
7804     // OpenCL v1.0 s6.5:
7805     // __kernel function arguments declared to be a pointer of a type can point
7806     // to one of the following address spaces only : __global, __local or
7807     // __constant.
7808     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7809     D.setInvalidType();
7810     return;
7811 
7812     // OpenCL v1.2 s6.9.k:
7813     // Arguments to kernel functions in a program cannot be declared with the
7814     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7815     // uintptr_t or a struct and/or union that contain fields declared to be
7816     // one of these built-in scalar types.
7817 
7818   case InvalidKernelParam:
7819     // OpenCL v1.2 s6.8 n:
7820     // A kernel function argument cannot be declared
7821     // of event_t type.
7822     // Do not diagnose half type since it is diagnosed as invalid argument
7823     // type for any function elsewhere.
7824     if (!PT->isHalfType())
7825       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7826     D.setInvalidType();
7827     return;
7828 
7829   case PtrKernelParam:
7830   case ValidKernelParam:
7831     ValidTypes.insert(PT.getTypePtr());
7832     return;
7833 
7834   case RecordKernelParam:
7835     break;
7836   }
7837 
7838   // Track nested structs we will inspect
7839   SmallVector<const Decl *, 4> VisitStack;
7840 
7841   // Track where we are in the nested structs. Items will migrate from
7842   // VisitStack to HistoryStack as we do the DFS for bad field.
7843   SmallVector<const FieldDecl *, 4> HistoryStack;
7844   HistoryStack.push_back(nullptr);
7845 
7846   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7847   VisitStack.push_back(PD);
7848 
7849   assert(VisitStack.back() && "First decl null?");
7850 
7851   do {
7852     const Decl *Next = VisitStack.pop_back_val();
7853     if (!Next) {
7854       assert(!HistoryStack.empty());
7855       // Found a marker, we have gone up a level
7856       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7857         ValidTypes.insert(Hist->getType().getTypePtr());
7858 
7859       continue;
7860     }
7861 
7862     // Adds everything except the original parameter declaration (which is not a
7863     // field itself) to the history stack.
7864     const RecordDecl *RD;
7865     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7866       HistoryStack.push_back(Field);
7867       RD = Field->getType()->castAs<RecordType>()->getDecl();
7868     } else {
7869       RD = cast<RecordDecl>(Next);
7870     }
7871 
7872     // Add a null marker so we know when we've gone back up a level
7873     VisitStack.push_back(nullptr);
7874 
7875     for (const auto *FD : RD->fields()) {
7876       QualType QT = FD->getType();
7877 
7878       if (ValidTypes.count(QT.getTypePtr()))
7879         continue;
7880 
7881       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7882       if (ParamType == ValidKernelParam)
7883         continue;
7884 
7885       if (ParamType == RecordKernelParam) {
7886         VisitStack.push_back(FD);
7887         continue;
7888       }
7889 
7890       // OpenCL v1.2 s6.9.p:
7891       // Arguments to kernel functions that are declared to be a struct or union
7892       // do not allow OpenCL objects to be passed as elements of the struct or
7893       // union.
7894       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7895           ParamType == InvalidAddrSpacePtrKernelParam) {
7896         S.Diag(Param->getLocation(),
7897                diag::err_record_with_pointers_kernel_param)
7898           << PT->isUnionType()
7899           << PT;
7900       } else {
7901         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7902       }
7903 
7904       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7905         << PD->getDeclName();
7906 
7907       // We have an error, now let's go back up through history and show where
7908       // the offending field came from
7909       for (ArrayRef<const FieldDecl *>::const_iterator
7910                I = HistoryStack.begin() + 1,
7911                E = HistoryStack.end();
7912            I != E; ++I) {
7913         const FieldDecl *OuterField = *I;
7914         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7915           << OuterField->getType();
7916       }
7917 
7918       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7919         << QT->isPointerType()
7920         << QT;
7921       D.setInvalidType();
7922       return;
7923     }
7924   } while (!VisitStack.empty());
7925 }
7926 
7927 /// Find the DeclContext in which a tag is implicitly declared if we see an
7928 /// elaborated type specifier in the specified context, and lookup finds
7929 /// nothing.
7930 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7931   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7932     DC = DC->getParent();
7933   return DC;
7934 }
7935 
7936 /// Find the Scope in which a tag is implicitly declared if we see an
7937 /// elaborated type specifier in the specified context, and lookup finds
7938 /// nothing.
7939 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7940   while (S->isClassScope() ||
7941          (LangOpts.CPlusPlus &&
7942           S->isFunctionPrototypeScope()) ||
7943          ((S->getFlags() & Scope::DeclScope) == 0) ||
7944          (S->getEntity() && S->getEntity()->isTransparentContext()))
7945     S = S->getParent();
7946   return S;
7947 }
7948 
7949 NamedDecl*
7950 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7951                               TypeSourceInfo *TInfo, LookupResult &Previous,
7952                               MultiTemplateParamsArg TemplateParamLists,
7953                               bool &AddToScope) {
7954   QualType R = TInfo->getType();
7955 
7956   assert(R.getTypePtr()->isFunctionType());
7957 
7958   // TODO: consider using NameInfo for diagnostic.
7959   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7960   DeclarationName Name = NameInfo.getName();
7961   StorageClass SC = getFunctionStorageClass(*this, D);
7962 
7963   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7964     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7965          diag::err_invalid_thread)
7966       << DeclSpec::getSpecifierName(TSCS);
7967 
7968   if (D.isFirstDeclarationOfMember())
7969     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7970                            D.getIdentifierLoc());
7971 
7972   bool isFriend = false;
7973   FunctionTemplateDecl *FunctionTemplate = nullptr;
7974   bool isMemberSpecialization = false;
7975   bool isFunctionTemplateSpecialization = false;
7976 
7977   bool isDependentClassScopeExplicitSpecialization = false;
7978   bool HasExplicitTemplateArgs = false;
7979   TemplateArgumentListInfo TemplateArgs;
7980 
7981   bool isVirtualOkay = false;
7982 
7983   DeclContext *OriginalDC = DC;
7984   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7985 
7986   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7987                                               isVirtualOkay);
7988   if (!NewFD) return nullptr;
7989 
7990   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7991     NewFD->setTopLevelDeclInObjCContainer();
7992 
7993   // Set the lexical context. If this is a function-scope declaration, or has a
7994   // C++ scope specifier, or is the object of a friend declaration, the lexical
7995   // context will be different from the semantic context.
7996   NewFD->setLexicalDeclContext(CurContext);
7997 
7998   if (IsLocalExternDecl)
7999     NewFD->setLocalExternDecl();
8000 
8001   if (getLangOpts().CPlusPlus) {
8002     bool isInline = D.getDeclSpec().isInlineSpecified();
8003     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8004     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8005     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8006     bool isConcept = D.getDeclSpec().isConceptSpecified();
8007     isFriend = D.getDeclSpec().isFriendSpecified();
8008     if (isFriend && !isInline && D.isFunctionDefinition()) {
8009       // C++ [class.friend]p5
8010       //   A function can be defined in a friend declaration of a
8011       //   class . . . . Such a function is implicitly inline.
8012       NewFD->setImplicitlyInline();
8013     }
8014 
8015     // If this is a method defined in an __interface, and is not a constructor
8016     // or an overloaded operator, then set the pure flag (isVirtual will already
8017     // return true).
8018     if (const CXXRecordDecl *Parent =
8019           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8020       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8021         NewFD->setPure(true);
8022 
8023       // C++ [class.union]p2
8024       //   A union can have member functions, but not virtual functions.
8025       if (isVirtual && Parent->isUnion())
8026         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8027     }
8028 
8029     SetNestedNameSpecifier(NewFD, D);
8030     isMemberSpecialization = false;
8031     isFunctionTemplateSpecialization = false;
8032     if (D.isInvalidType())
8033       NewFD->setInvalidDecl();
8034 
8035     // Match up the template parameter lists with the scope specifier, then
8036     // determine whether we have a template or a template specialization.
8037     bool Invalid = false;
8038     if (TemplateParameterList *TemplateParams =
8039             MatchTemplateParametersToScopeSpecifier(
8040                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8041                 D.getCXXScopeSpec(),
8042                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8043                     ? D.getName().TemplateId
8044                     : nullptr,
8045                 TemplateParamLists, isFriend, isMemberSpecialization,
8046                 Invalid)) {
8047       if (TemplateParams->size() > 0) {
8048         // This is a function template
8049 
8050         // Check that we can declare a template here.
8051         if (CheckTemplateDeclScope(S, TemplateParams))
8052           NewFD->setInvalidDecl();
8053 
8054         // A destructor cannot be a template.
8055         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8056           Diag(NewFD->getLocation(), diag::err_destructor_template);
8057           NewFD->setInvalidDecl();
8058         }
8059 
8060         // If we're adding a template to a dependent context, we may need to
8061         // rebuilding some of the types used within the template parameter list,
8062         // now that we know what the current instantiation is.
8063         if (DC->isDependentContext()) {
8064           ContextRAII SavedContext(*this, DC);
8065           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8066             Invalid = true;
8067         }
8068 
8069         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8070                                                         NewFD->getLocation(),
8071                                                         Name, TemplateParams,
8072                                                         NewFD);
8073         FunctionTemplate->setLexicalDeclContext(CurContext);
8074         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8075 
8076         // For source fidelity, store the other template param lists.
8077         if (TemplateParamLists.size() > 1) {
8078           NewFD->setTemplateParameterListsInfo(Context,
8079                                                TemplateParamLists.drop_back(1));
8080         }
8081       } else {
8082         // This is a function template specialization.
8083         isFunctionTemplateSpecialization = true;
8084         // For source fidelity, store all the template param lists.
8085         if (TemplateParamLists.size() > 0)
8086           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8087 
8088         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8089         if (isFriend) {
8090           // We want to remove the "template<>", found here.
8091           SourceRange RemoveRange = TemplateParams->getSourceRange();
8092 
8093           // If we remove the template<> and the name is not a
8094           // template-id, we're actually silently creating a problem:
8095           // the friend declaration will refer to an untemplated decl,
8096           // and clearly the user wants a template specialization.  So
8097           // we need to insert '<>' after the name.
8098           SourceLocation InsertLoc;
8099           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8100             InsertLoc = D.getName().getSourceRange().getEnd();
8101             InsertLoc = getLocForEndOfToken(InsertLoc);
8102           }
8103 
8104           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8105             << Name << RemoveRange
8106             << FixItHint::CreateRemoval(RemoveRange)
8107             << FixItHint::CreateInsertion(InsertLoc, "<>");
8108         }
8109       }
8110     }
8111     else {
8112       // All template param lists were matched against the scope specifier:
8113       // this is NOT (an explicit specialization of) a template.
8114       if (TemplateParamLists.size() > 0)
8115         // For source fidelity, store all the template param lists.
8116         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8117     }
8118 
8119     if (Invalid) {
8120       NewFD->setInvalidDecl();
8121       if (FunctionTemplate)
8122         FunctionTemplate->setInvalidDecl();
8123     }
8124 
8125     // C++ [dcl.fct.spec]p5:
8126     //   The virtual specifier shall only be used in declarations of
8127     //   nonstatic class member functions that appear within a
8128     //   member-specification of a class declaration; see 10.3.
8129     //
8130     if (isVirtual && !NewFD->isInvalidDecl()) {
8131       if (!isVirtualOkay) {
8132         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8133              diag::err_virtual_non_function);
8134       } else if (!CurContext->isRecord()) {
8135         // 'virtual' was specified outside of the class.
8136         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8137              diag::err_virtual_out_of_class)
8138           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8139       } else if (NewFD->getDescribedFunctionTemplate()) {
8140         // C++ [temp.mem]p3:
8141         //  A member function template shall not be virtual.
8142         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8143              diag::err_virtual_member_function_template)
8144           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8145       } else {
8146         // Okay: Add virtual to the method.
8147         NewFD->setVirtualAsWritten(true);
8148       }
8149 
8150       if (getLangOpts().CPlusPlus14 &&
8151           NewFD->getReturnType()->isUndeducedType())
8152         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8153     }
8154 
8155     if (getLangOpts().CPlusPlus14 &&
8156         (NewFD->isDependentContext() ||
8157          (isFriend && CurContext->isDependentContext())) &&
8158         NewFD->getReturnType()->isUndeducedType()) {
8159       // If the function template is referenced directly (for instance, as a
8160       // member of the current instantiation), pretend it has a dependent type.
8161       // This is not really justified by the standard, but is the only sane
8162       // thing to do.
8163       // FIXME: For a friend function, we have not marked the function as being
8164       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8165       const FunctionProtoType *FPT =
8166           NewFD->getType()->castAs<FunctionProtoType>();
8167       QualType Result =
8168           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8169       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8170                                              FPT->getExtProtoInfo()));
8171     }
8172 
8173     // C++ [dcl.fct.spec]p3:
8174     //  The inline specifier shall not appear on a block scope function
8175     //  declaration.
8176     if (isInline && !NewFD->isInvalidDecl()) {
8177       if (CurContext->isFunctionOrMethod()) {
8178         // 'inline' is not allowed on block scope function declaration.
8179         Diag(D.getDeclSpec().getInlineSpecLoc(),
8180              diag::err_inline_declaration_block_scope) << Name
8181           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8182       }
8183     }
8184 
8185     // C++ [dcl.fct.spec]p6:
8186     //  The explicit specifier shall be used only in the declaration of a
8187     //  constructor or conversion function within its class definition;
8188     //  see 12.3.1 and 12.3.2.
8189     if (isExplicit && !NewFD->isInvalidDecl() &&
8190         !isa<CXXDeductionGuideDecl>(NewFD)) {
8191       if (!CurContext->isRecord()) {
8192         // 'explicit' was specified outside of the class.
8193         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8194              diag::err_explicit_out_of_class)
8195           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8196       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8197                  !isa<CXXConversionDecl>(NewFD)) {
8198         // 'explicit' was specified on a function that wasn't a constructor
8199         // or conversion function.
8200         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8201              diag::err_explicit_non_ctor_or_conv_function)
8202           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8203       }
8204     }
8205 
8206     if (isConstexpr) {
8207       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8208       // are implicitly inline.
8209       NewFD->setImplicitlyInline();
8210 
8211       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8212       // be either constructors or to return a literal type. Therefore,
8213       // destructors cannot be declared constexpr.
8214       if (isa<CXXDestructorDecl>(NewFD))
8215         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8216     }
8217 
8218     if (isConcept) {
8219       // This is a function concept.
8220       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8221         FTD->setConcept();
8222 
8223       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8224       // applied only to the definition of a function template [...]
8225       if (!D.isFunctionDefinition()) {
8226         Diag(D.getDeclSpec().getConceptSpecLoc(),
8227              diag::err_function_concept_not_defined);
8228         NewFD->setInvalidDecl();
8229       }
8230 
8231       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8232       // have no exception-specification and is treated as if it were specified
8233       // with noexcept(true) (15.4). [...]
8234       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8235         if (FPT->hasExceptionSpec()) {
8236           SourceRange Range;
8237           if (D.isFunctionDeclarator())
8238             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8239           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8240               << FixItHint::CreateRemoval(Range);
8241           NewFD->setInvalidDecl();
8242         } else {
8243           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8244         }
8245 
8246         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8247         // following restrictions:
8248         // - The declared return type shall have the type bool.
8249         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8250           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8251           NewFD->setInvalidDecl();
8252         }
8253 
8254         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8255         // following restrictions:
8256         // - The declaration's parameter list shall be equivalent to an empty
8257         //   parameter list.
8258         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8259           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8260       }
8261 
8262       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8263       // implicity defined to be a constexpr declaration (implicitly inline)
8264       NewFD->setImplicitlyInline();
8265 
8266       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8267       // be declared with the thread_local, inline, friend, or constexpr
8268       // specifiers, [...]
8269       if (isInline) {
8270         Diag(D.getDeclSpec().getInlineSpecLoc(),
8271              diag::err_concept_decl_invalid_specifiers)
8272             << 1 << 1;
8273         NewFD->setInvalidDecl(true);
8274       }
8275 
8276       if (isFriend) {
8277         Diag(D.getDeclSpec().getFriendSpecLoc(),
8278              diag::err_concept_decl_invalid_specifiers)
8279             << 1 << 2;
8280         NewFD->setInvalidDecl(true);
8281       }
8282 
8283       if (isConstexpr) {
8284         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8285              diag::err_concept_decl_invalid_specifiers)
8286             << 1 << 3;
8287         NewFD->setInvalidDecl(true);
8288       }
8289 
8290       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8291       // applied only to the definition of a function template or variable
8292       // template, declared in namespace scope.
8293       if (isFunctionTemplateSpecialization) {
8294         Diag(D.getDeclSpec().getConceptSpecLoc(),
8295              diag::err_concept_specified_specialization) << 1;
8296         NewFD->setInvalidDecl(true);
8297         return NewFD;
8298       }
8299     }
8300 
8301     // If __module_private__ was specified, mark the function accordingly.
8302     if (D.getDeclSpec().isModulePrivateSpecified()) {
8303       if (isFunctionTemplateSpecialization) {
8304         SourceLocation ModulePrivateLoc
8305           = D.getDeclSpec().getModulePrivateSpecLoc();
8306         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8307           << 0
8308           << FixItHint::CreateRemoval(ModulePrivateLoc);
8309       } else {
8310         NewFD->setModulePrivate();
8311         if (FunctionTemplate)
8312           FunctionTemplate->setModulePrivate();
8313       }
8314     }
8315 
8316     if (isFriend) {
8317       if (FunctionTemplate) {
8318         FunctionTemplate->setObjectOfFriendDecl();
8319         FunctionTemplate->setAccess(AS_public);
8320       }
8321       NewFD->setObjectOfFriendDecl();
8322       NewFD->setAccess(AS_public);
8323     }
8324 
8325     // If a function is defined as defaulted or deleted, mark it as such now.
8326     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8327     // definition kind to FDK_Definition.
8328     switch (D.getFunctionDefinitionKind()) {
8329       case FDK_Declaration:
8330       case FDK_Definition:
8331         break;
8332 
8333       case FDK_Defaulted:
8334         NewFD->setDefaulted();
8335         break;
8336 
8337       case FDK_Deleted:
8338         NewFD->setDeletedAsWritten();
8339         break;
8340     }
8341 
8342     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8343         D.isFunctionDefinition()) {
8344       // C++ [class.mfct]p2:
8345       //   A member function may be defined (8.4) in its class definition, in
8346       //   which case it is an inline member function (7.1.2)
8347       NewFD->setImplicitlyInline();
8348     }
8349 
8350     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8351         !CurContext->isRecord()) {
8352       // C++ [class.static]p1:
8353       //   A data or function member of a class may be declared static
8354       //   in a class definition, in which case it is a static member of
8355       //   the class.
8356 
8357       // Complain about the 'static' specifier if it's on an out-of-line
8358       // member function definition.
8359       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8360            diag::err_static_out_of_line)
8361         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8362     }
8363 
8364     // C++11 [except.spec]p15:
8365     //   A deallocation function with no exception-specification is treated
8366     //   as if it were specified with noexcept(true).
8367     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8368     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8369          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8370         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8371       NewFD->setType(Context.getFunctionType(
8372           FPT->getReturnType(), FPT->getParamTypes(),
8373           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8374   }
8375 
8376   // Filter out previous declarations that don't match the scope.
8377   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8378                        D.getCXXScopeSpec().isNotEmpty() ||
8379                        isMemberSpecialization ||
8380                        isFunctionTemplateSpecialization);
8381 
8382   // Handle GNU asm-label extension (encoded as an attribute).
8383   if (Expr *E = (Expr*) D.getAsmLabel()) {
8384     // The parser guarantees this is a string.
8385     StringLiteral *SE = cast<StringLiteral>(E);
8386     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8387                                                 SE->getString(), 0));
8388   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8389     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8390       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8391     if (I != ExtnameUndeclaredIdentifiers.end()) {
8392       if (isDeclExternC(NewFD)) {
8393         NewFD->addAttr(I->second);
8394         ExtnameUndeclaredIdentifiers.erase(I);
8395       } else
8396         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8397             << /*Variable*/0 << NewFD;
8398     }
8399   }
8400 
8401   // Copy the parameter declarations from the declarator D to the function
8402   // declaration NewFD, if they are available.  First scavenge them into Params.
8403   SmallVector<ParmVarDecl*, 16> Params;
8404   unsigned FTIIdx;
8405   if (D.isFunctionDeclarator(FTIIdx)) {
8406     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8407 
8408     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8409     // function that takes no arguments, not a function that takes a
8410     // single void argument.
8411     // We let through "const void" here because Sema::GetTypeForDeclarator
8412     // already checks for that case.
8413     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8414       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8415         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8416         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8417         Param->setDeclContext(NewFD);
8418         Params.push_back(Param);
8419 
8420         if (Param->isInvalidDecl())
8421           NewFD->setInvalidDecl();
8422       }
8423     }
8424 
8425     if (!getLangOpts().CPlusPlus) {
8426       // In C, find all the tag declarations from the prototype and move them
8427       // into the function DeclContext. Remove them from the surrounding tag
8428       // injection context of the function, which is typically but not always
8429       // the TU.
8430       DeclContext *PrototypeTagContext =
8431           getTagInjectionContext(NewFD->getLexicalDeclContext());
8432       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8433         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8434 
8435         // We don't want to reparent enumerators. Look at their parent enum
8436         // instead.
8437         if (!TD) {
8438           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8439             TD = cast<EnumDecl>(ECD->getDeclContext());
8440         }
8441         if (!TD)
8442           continue;
8443         DeclContext *TagDC = TD->getLexicalDeclContext();
8444         if (!TagDC->containsDecl(TD))
8445           continue;
8446         TagDC->removeDecl(TD);
8447         TD->setDeclContext(NewFD);
8448         NewFD->addDecl(TD);
8449 
8450         // Preserve the lexical DeclContext if it is not the surrounding tag
8451         // injection context of the FD. In this example, the semantic context of
8452         // E will be f and the lexical context will be S, while both the
8453         // semantic and lexical contexts of S will be f:
8454         //   void f(struct S { enum E { a } f; } s);
8455         if (TagDC != PrototypeTagContext)
8456           TD->setLexicalDeclContext(TagDC);
8457       }
8458     }
8459   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8460     // When we're declaring a function with a typedef, typeof, etc as in the
8461     // following example, we'll need to synthesize (unnamed)
8462     // parameters for use in the declaration.
8463     //
8464     // @code
8465     // typedef void fn(int);
8466     // fn f;
8467     // @endcode
8468 
8469     // Synthesize a parameter for each argument type.
8470     for (const auto &AI : FT->param_types()) {
8471       ParmVarDecl *Param =
8472           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8473       Param->setScopeInfo(0, Params.size());
8474       Params.push_back(Param);
8475     }
8476   } else {
8477     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8478            "Should not need args for typedef of non-prototype fn");
8479   }
8480 
8481   // Finally, we know we have the right number of parameters, install them.
8482   NewFD->setParams(Params);
8483 
8484   if (D.getDeclSpec().isNoreturnSpecified())
8485     NewFD->addAttr(
8486         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8487                                        Context, 0));
8488 
8489   // Functions returning a variably modified type violate C99 6.7.5.2p2
8490   // because all functions have linkage.
8491   if (!NewFD->isInvalidDecl() &&
8492       NewFD->getReturnType()->isVariablyModifiedType()) {
8493     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8494     NewFD->setInvalidDecl();
8495   }
8496 
8497   // Apply an implicit SectionAttr if #pragma code_seg is active.
8498   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8499       !NewFD->hasAttr<SectionAttr>()) {
8500     NewFD->addAttr(
8501         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8502                                     CodeSegStack.CurrentValue->getString(),
8503                                     CodeSegStack.CurrentPragmaLocation));
8504     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8505                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8506                          ASTContext::PSF_Read,
8507                      NewFD))
8508       NewFD->dropAttr<SectionAttr>();
8509   }
8510 
8511   // Handle attributes.
8512   ProcessDeclAttributes(S, NewFD, D);
8513 
8514   if (getLangOpts().OpenCL) {
8515     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8516     // type declaration will generate a compilation error.
8517     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8518     if (AddressSpace == LangAS::opencl_local ||
8519         AddressSpace == LangAS::opencl_global ||
8520         AddressSpace == LangAS::opencl_constant) {
8521       Diag(NewFD->getLocation(),
8522            diag::err_opencl_return_value_with_address_space);
8523       NewFD->setInvalidDecl();
8524     }
8525   }
8526 
8527   if (!getLangOpts().CPlusPlus) {
8528     // Perform semantic checking on the function declaration.
8529     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8530       CheckMain(NewFD, D.getDeclSpec());
8531 
8532     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8533       CheckMSVCRTEntryPoint(NewFD);
8534 
8535     if (!NewFD->isInvalidDecl())
8536       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8537                                                   isMemberSpecialization));
8538     else if (!Previous.empty())
8539       // Recover gracefully from an invalid redeclaration.
8540       D.setRedeclaration(true);
8541     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8542             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8543            "previous declaration set still overloaded");
8544 
8545     // Diagnose no-prototype function declarations with calling conventions that
8546     // don't support variadic calls. Only do this in C and do it after merging
8547     // possibly prototyped redeclarations.
8548     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8549     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8550       CallingConv CC = FT->getExtInfo().getCC();
8551       if (!supportsVariadicCall(CC)) {
8552         // Windows system headers sometimes accidentally use stdcall without
8553         // (void) parameters, so we relax this to a warning.
8554         int DiagID =
8555             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8556         Diag(NewFD->getLocation(), DiagID)
8557             << FunctionType::getNameForCallConv(CC);
8558       }
8559     }
8560   } else {
8561     // C++11 [replacement.functions]p3:
8562     //  The program's definitions shall not be specified as inline.
8563     //
8564     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8565     //
8566     // Suppress the diagnostic if the function is __attribute__((used)), since
8567     // that forces an external definition to be emitted.
8568     if (D.getDeclSpec().isInlineSpecified() &&
8569         NewFD->isReplaceableGlobalAllocationFunction() &&
8570         !NewFD->hasAttr<UsedAttr>())
8571       Diag(D.getDeclSpec().getInlineSpecLoc(),
8572            diag::ext_operator_new_delete_declared_inline)
8573         << NewFD->getDeclName();
8574 
8575     // If the declarator is a template-id, translate the parser's template
8576     // argument list into our AST format.
8577     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8578       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8579       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8580       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8581       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8582                                          TemplateId->NumArgs);
8583       translateTemplateArguments(TemplateArgsPtr,
8584                                  TemplateArgs);
8585 
8586       HasExplicitTemplateArgs = true;
8587 
8588       if (NewFD->isInvalidDecl()) {
8589         HasExplicitTemplateArgs = false;
8590       } else if (FunctionTemplate) {
8591         // Function template with explicit template arguments.
8592         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8593           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8594 
8595         HasExplicitTemplateArgs = false;
8596       } else {
8597         assert((isFunctionTemplateSpecialization ||
8598                 D.getDeclSpec().isFriendSpecified()) &&
8599                "should have a 'template<>' for this decl");
8600         // "friend void foo<>(int);" is an implicit specialization decl.
8601         isFunctionTemplateSpecialization = true;
8602       }
8603     } else if (isFriend && isFunctionTemplateSpecialization) {
8604       // This combination is only possible in a recovery case;  the user
8605       // wrote something like:
8606       //   template <> friend void foo(int);
8607       // which we're recovering from as if the user had written:
8608       //   friend void foo<>(int);
8609       // Go ahead and fake up a template id.
8610       HasExplicitTemplateArgs = true;
8611       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8612       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8613     }
8614 
8615     // We do not add HD attributes to specializations here because
8616     // they may have different constexpr-ness compared to their
8617     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8618     // may end up with different effective targets. Instead, a
8619     // specialization inherits its target attributes from its template
8620     // in the CheckFunctionTemplateSpecialization() call below.
8621     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8622       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8623 
8624     // If it's a friend (and only if it's a friend), it's possible
8625     // that either the specialized function type or the specialized
8626     // template is dependent, and therefore matching will fail.  In
8627     // this case, don't check the specialization yet.
8628     bool InstantiationDependent = false;
8629     if (isFunctionTemplateSpecialization && isFriend &&
8630         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8631          TemplateSpecializationType::anyDependentTemplateArguments(
8632             TemplateArgs,
8633             InstantiationDependent))) {
8634       assert(HasExplicitTemplateArgs &&
8635              "friend function specialization without template args");
8636       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8637                                                        Previous))
8638         NewFD->setInvalidDecl();
8639     } else if (isFunctionTemplateSpecialization) {
8640       if (CurContext->isDependentContext() && CurContext->isRecord()
8641           && !isFriend) {
8642         isDependentClassScopeExplicitSpecialization = true;
8643         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8644           diag::ext_function_specialization_in_class :
8645           diag::err_function_specialization_in_class)
8646           << NewFD->getDeclName();
8647       } else if (CheckFunctionTemplateSpecialization(NewFD,
8648                                   (HasExplicitTemplateArgs ? &TemplateArgs
8649                                                            : nullptr),
8650                                                      Previous))
8651         NewFD->setInvalidDecl();
8652 
8653       // C++ [dcl.stc]p1:
8654       //   A storage-class-specifier shall not be specified in an explicit
8655       //   specialization (14.7.3)
8656       FunctionTemplateSpecializationInfo *Info =
8657           NewFD->getTemplateSpecializationInfo();
8658       if (Info && SC != SC_None) {
8659         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8660           Diag(NewFD->getLocation(),
8661                diag::err_explicit_specialization_inconsistent_storage_class)
8662             << SC
8663             << FixItHint::CreateRemoval(
8664                                       D.getDeclSpec().getStorageClassSpecLoc());
8665 
8666         else
8667           Diag(NewFD->getLocation(),
8668                diag::ext_explicit_specialization_storage_class)
8669             << FixItHint::CreateRemoval(
8670                                       D.getDeclSpec().getStorageClassSpecLoc());
8671       }
8672     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8673       if (CheckMemberSpecialization(NewFD, Previous))
8674           NewFD->setInvalidDecl();
8675     }
8676 
8677     // Perform semantic checking on the function declaration.
8678     if (!isDependentClassScopeExplicitSpecialization) {
8679       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8680         CheckMain(NewFD, D.getDeclSpec());
8681 
8682       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8683         CheckMSVCRTEntryPoint(NewFD);
8684 
8685       if (!NewFD->isInvalidDecl())
8686         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8687                                                     isMemberSpecialization));
8688       else if (!Previous.empty())
8689         // Recover gracefully from an invalid redeclaration.
8690         D.setRedeclaration(true);
8691     }
8692 
8693     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8694             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8695            "previous declaration set still overloaded");
8696 
8697     NamedDecl *PrincipalDecl = (FunctionTemplate
8698                                 ? cast<NamedDecl>(FunctionTemplate)
8699                                 : NewFD);
8700 
8701     if (isFriend && NewFD->getPreviousDecl()) {
8702       AccessSpecifier Access = AS_public;
8703       if (!NewFD->isInvalidDecl())
8704         Access = NewFD->getPreviousDecl()->getAccess();
8705 
8706       NewFD->setAccess(Access);
8707       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8708     }
8709 
8710     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8711         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8712       PrincipalDecl->setNonMemberOperator();
8713 
8714     // If we have a function template, check the template parameter
8715     // list. This will check and merge default template arguments.
8716     if (FunctionTemplate) {
8717       FunctionTemplateDecl *PrevTemplate =
8718                                      FunctionTemplate->getPreviousDecl();
8719       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8720                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8721                                     : nullptr,
8722                             D.getDeclSpec().isFriendSpecified()
8723                               ? (D.isFunctionDefinition()
8724                                    ? TPC_FriendFunctionTemplateDefinition
8725                                    : TPC_FriendFunctionTemplate)
8726                               : (D.getCXXScopeSpec().isSet() &&
8727                                  DC && DC->isRecord() &&
8728                                  DC->isDependentContext())
8729                                   ? TPC_ClassTemplateMember
8730                                   : TPC_FunctionTemplate);
8731     }
8732 
8733     if (NewFD->isInvalidDecl()) {
8734       // Ignore all the rest of this.
8735     } else if (!D.isRedeclaration()) {
8736       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8737                                        AddToScope };
8738       // Fake up an access specifier if it's supposed to be a class member.
8739       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8740         NewFD->setAccess(AS_public);
8741 
8742       // Qualified decls generally require a previous declaration.
8743       if (D.getCXXScopeSpec().isSet()) {
8744         // ...with the major exception of templated-scope or
8745         // dependent-scope friend declarations.
8746 
8747         // TODO: we currently also suppress this check in dependent
8748         // contexts because (1) the parameter depth will be off when
8749         // matching friend templates and (2) we might actually be
8750         // selecting a friend based on a dependent factor.  But there
8751         // are situations where these conditions don't apply and we
8752         // can actually do this check immediately.
8753         if (isFriend &&
8754             (TemplateParamLists.size() ||
8755              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8756              CurContext->isDependentContext())) {
8757           // ignore these
8758         } else {
8759           // The user tried to provide an out-of-line definition for a
8760           // function that is a member of a class or namespace, but there
8761           // was no such member function declared (C++ [class.mfct]p2,
8762           // C++ [namespace.memdef]p2). For example:
8763           //
8764           // class X {
8765           //   void f() const;
8766           // };
8767           //
8768           // void X::f() { } // ill-formed
8769           //
8770           // Complain about this problem, and attempt to suggest close
8771           // matches (e.g., those that differ only in cv-qualifiers and
8772           // whether the parameter types are references).
8773 
8774           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8775                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8776             AddToScope = ExtraArgs.AddToScope;
8777             return Result;
8778           }
8779         }
8780 
8781         // Unqualified local friend declarations are required to resolve
8782         // to something.
8783       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8784         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8785                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8786           AddToScope = ExtraArgs.AddToScope;
8787           return Result;
8788         }
8789       }
8790     } else if (!D.isFunctionDefinition() &&
8791                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8792                !isFriend && !isFunctionTemplateSpecialization &&
8793                !isMemberSpecialization) {
8794       // An out-of-line member function declaration must also be a
8795       // definition (C++ [class.mfct]p2).
8796       // Note that this is not the case for explicit specializations of
8797       // function templates or member functions of class templates, per
8798       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8799       // extension for compatibility with old SWIG code which likes to
8800       // generate them.
8801       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8802         << D.getCXXScopeSpec().getRange();
8803     }
8804   }
8805 
8806   ProcessPragmaWeak(S, NewFD);
8807   checkAttributesAfterMerging(*this, *NewFD);
8808 
8809   AddKnownFunctionAttributes(NewFD);
8810 
8811   if (NewFD->hasAttr<OverloadableAttr>() &&
8812       !NewFD->getType()->getAs<FunctionProtoType>()) {
8813     Diag(NewFD->getLocation(),
8814          diag::err_attribute_overloadable_no_prototype)
8815       << NewFD;
8816 
8817     // Turn this into a variadic function with no parameters.
8818     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8819     FunctionProtoType::ExtProtoInfo EPI(
8820         Context.getDefaultCallingConvention(true, false));
8821     EPI.Variadic = true;
8822     EPI.ExtInfo = FT->getExtInfo();
8823 
8824     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8825     NewFD->setType(R);
8826   }
8827 
8828   // If there's a #pragma GCC visibility in scope, and this isn't a class
8829   // member, set the visibility of this function.
8830   if (!DC->isRecord() && NewFD->isExternallyVisible())
8831     AddPushedVisibilityAttribute(NewFD);
8832 
8833   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8834   // marking the function.
8835   AddCFAuditedAttribute(NewFD);
8836 
8837   // If this is a function definition, check if we have to apply optnone due to
8838   // a pragma.
8839   if(D.isFunctionDefinition())
8840     AddRangeBasedOptnone(NewFD);
8841 
8842   // If this is the first declaration of an extern C variable, update
8843   // the map of such variables.
8844   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8845       isIncompleteDeclExternC(*this, NewFD))
8846     RegisterLocallyScopedExternCDecl(NewFD, S);
8847 
8848   // Set this FunctionDecl's range up to the right paren.
8849   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8850 
8851   if (D.isRedeclaration() && !Previous.empty()) {
8852     checkDLLAttributeRedeclaration(
8853         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8854         isMemberSpecialization || isFunctionTemplateSpecialization,
8855         D.isFunctionDefinition());
8856   }
8857 
8858   if (getLangOpts().CUDA) {
8859     IdentifierInfo *II = NewFD->getIdentifier();
8860     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8861         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8862       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8863         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8864 
8865       Context.setcudaConfigureCallDecl(NewFD);
8866     }
8867 
8868     // Variadic functions, other than a *declaration* of printf, are not allowed
8869     // in device-side CUDA code, unless someone passed
8870     // -fcuda-allow-variadic-functions.
8871     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8872         (NewFD->hasAttr<CUDADeviceAttr>() ||
8873          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8874         !(II && II->isStr("printf") && NewFD->isExternC() &&
8875           !D.isFunctionDefinition())) {
8876       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8877     }
8878   }
8879 
8880   if (getLangOpts().CPlusPlus) {
8881     if (FunctionTemplate) {
8882       if (NewFD->isInvalidDecl())
8883         FunctionTemplate->setInvalidDecl();
8884       return FunctionTemplate;
8885     }
8886   }
8887 
8888   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8889     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8890     if ((getLangOpts().OpenCLVersion >= 120)
8891         && (SC == SC_Static)) {
8892       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8893       D.setInvalidType();
8894     }
8895 
8896     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8897     if (!NewFD->getReturnType()->isVoidType()) {
8898       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8899       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8900           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8901                                 : FixItHint());
8902       D.setInvalidType();
8903     }
8904 
8905     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8906     for (auto Param : NewFD->parameters())
8907       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8908   }
8909   for (const ParmVarDecl *Param : NewFD->parameters()) {
8910     QualType PT = Param->getType();
8911 
8912     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8913     // types.
8914     if (getLangOpts().OpenCLVersion >= 200) {
8915       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8916         QualType ElemTy = PipeTy->getElementType();
8917           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8918             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8919             D.setInvalidType();
8920           }
8921       }
8922     }
8923   }
8924 
8925   MarkUnusedFileScopedDecl(NewFD);
8926 
8927   // Here we have an function template explicit specialization at class scope.
8928   // The actually specialization will be postponed to template instatiation
8929   // time via the ClassScopeFunctionSpecializationDecl node.
8930   if (isDependentClassScopeExplicitSpecialization) {
8931     ClassScopeFunctionSpecializationDecl *NewSpec =
8932                          ClassScopeFunctionSpecializationDecl::Create(
8933                                 Context, CurContext, SourceLocation(),
8934                                 cast<CXXMethodDecl>(NewFD),
8935                                 HasExplicitTemplateArgs, TemplateArgs);
8936     CurContext->addDecl(NewSpec);
8937     AddToScope = false;
8938   }
8939 
8940   return NewFD;
8941 }
8942 
8943 /// \brief Checks if the new declaration declared in dependent context must be
8944 /// put in the same redeclaration chain as the specified declaration.
8945 ///
8946 /// \param D Declaration that is checked.
8947 /// \param PrevDecl Previous declaration found with proper lookup method for the
8948 ///                 same declaration name.
8949 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8950 ///          belongs to.
8951 ///
8952 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8953   // Any declarations should be put into redeclaration chains except for
8954   // friend declaration in a dependent context that names a function in
8955   // namespace scope.
8956   //
8957   // This allows to compile code like:
8958   //
8959   //       void func();
8960   //       template<typename T> class C1 { friend void func() { } };
8961   //       template<typename T> class C2 { friend void func() { } };
8962   //
8963   // This code snippet is a valid code unless both templates are instantiated.
8964   return !(D->getLexicalDeclContext()->isDependentContext() &&
8965            D->getDeclContext()->isFileContext() &&
8966            D->getFriendObjectKind() != Decl::FOK_None);
8967 }
8968 
8969 /// \brief Perform semantic checking of a new function declaration.
8970 ///
8971 /// Performs semantic analysis of the new function declaration
8972 /// NewFD. This routine performs all semantic checking that does not
8973 /// require the actual declarator involved in the declaration, and is
8974 /// used both for the declaration of functions as they are parsed
8975 /// (called via ActOnDeclarator) and for the declaration of functions
8976 /// that have been instantiated via C++ template instantiation (called
8977 /// via InstantiateDecl).
8978 ///
8979 /// \param IsMemberSpecialization whether this new function declaration is
8980 /// a member specialization (that replaces any definition provided by the
8981 /// previous declaration).
8982 ///
8983 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8984 ///
8985 /// \returns true if the function declaration is a redeclaration.
8986 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8987                                     LookupResult &Previous,
8988                                     bool IsMemberSpecialization) {
8989   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8990          "Variably modified return types are not handled here");
8991 
8992   // Determine whether the type of this function should be merged with
8993   // a previous visible declaration. This never happens for functions in C++,
8994   // and always happens in C if the previous declaration was visible.
8995   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8996                                !Previous.isShadowed();
8997 
8998   bool Redeclaration = false;
8999   NamedDecl *OldDecl = nullptr;
9000 
9001   // Merge or overload the declaration with an existing declaration of
9002   // the same name, if appropriate.
9003   if (!Previous.empty()) {
9004     // Determine whether NewFD is an overload of PrevDecl or
9005     // a declaration that requires merging. If it's an overload,
9006     // there's no more work to do here; we'll just add the new
9007     // function to the scope.
9008     if (!AllowOverloadingOfFunction(Previous, Context)) {
9009       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9010       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9011         Redeclaration = true;
9012         OldDecl = Candidate;
9013       }
9014     } else {
9015       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9016                             /*NewIsUsingDecl*/ false)) {
9017       case Ovl_Match:
9018         Redeclaration = true;
9019         break;
9020 
9021       case Ovl_NonFunction:
9022         Redeclaration = true;
9023         break;
9024 
9025       case Ovl_Overload:
9026         Redeclaration = false;
9027         break;
9028       }
9029 
9030       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9031         // If a function name is overloadable in C, then every function
9032         // with that name must be marked "overloadable".
9033         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9034           << Redeclaration << NewFD;
9035         NamedDecl *OverloadedDecl = nullptr;
9036         if (Redeclaration)
9037           OverloadedDecl = OldDecl;
9038         else if (!Previous.empty())
9039           OverloadedDecl = Previous.getRepresentativeDecl();
9040         if (OverloadedDecl)
9041           Diag(OverloadedDecl->getLocation(),
9042                diag::note_attribute_overloadable_prev_overload);
9043         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9044       }
9045     }
9046   }
9047 
9048   // Check for a previous extern "C" declaration with this name.
9049   if (!Redeclaration &&
9050       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9051     if (!Previous.empty()) {
9052       // This is an extern "C" declaration with the same name as a previous
9053       // declaration, and thus redeclares that entity...
9054       Redeclaration = true;
9055       OldDecl = Previous.getFoundDecl();
9056       MergeTypeWithPrevious = false;
9057 
9058       // ... except in the presence of __attribute__((overloadable)).
9059       if (OldDecl->hasAttr<OverloadableAttr>()) {
9060         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9061           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9062             << Redeclaration << NewFD;
9063           Diag(Previous.getFoundDecl()->getLocation(),
9064                diag::note_attribute_overloadable_prev_overload);
9065           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9066         }
9067         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9068           Redeclaration = false;
9069           OldDecl = nullptr;
9070         }
9071       }
9072     }
9073   }
9074 
9075   // C++11 [dcl.constexpr]p8:
9076   //   A constexpr specifier for a non-static member function that is not
9077   //   a constructor declares that member function to be const.
9078   //
9079   // This needs to be delayed until we know whether this is an out-of-line
9080   // definition of a static member function.
9081   //
9082   // This rule is not present in C++1y, so we produce a backwards
9083   // compatibility warning whenever it happens in C++11.
9084   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9085   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9086       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9087       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9088     CXXMethodDecl *OldMD = nullptr;
9089     if (OldDecl)
9090       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9091     if (!OldMD || !OldMD->isStatic()) {
9092       const FunctionProtoType *FPT =
9093         MD->getType()->castAs<FunctionProtoType>();
9094       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9095       EPI.TypeQuals |= Qualifiers::Const;
9096       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9097                                           FPT->getParamTypes(), EPI));
9098 
9099       // Warn that we did this, if we're not performing template instantiation.
9100       // In that case, we'll have warned already when the template was defined.
9101       if (!inTemplateInstantiation()) {
9102         SourceLocation AddConstLoc;
9103         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9104                 .IgnoreParens().getAs<FunctionTypeLoc>())
9105           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9106 
9107         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9108           << FixItHint::CreateInsertion(AddConstLoc, " const");
9109       }
9110     }
9111   }
9112 
9113   if (Redeclaration) {
9114     // NewFD and OldDecl represent declarations that need to be
9115     // merged.
9116     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9117       NewFD->setInvalidDecl();
9118       return Redeclaration;
9119     }
9120 
9121     Previous.clear();
9122     Previous.addDecl(OldDecl);
9123 
9124     if (FunctionTemplateDecl *OldTemplateDecl
9125                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9126       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9127       FunctionTemplateDecl *NewTemplateDecl
9128         = NewFD->getDescribedFunctionTemplate();
9129       assert(NewTemplateDecl && "Template/non-template mismatch");
9130       if (CXXMethodDecl *Method
9131             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9132         Method->setAccess(OldTemplateDecl->getAccess());
9133         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9134       }
9135 
9136       // If this is an explicit specialization of a member that is a function
9137       // template, mark it as a member specialization.
9138       if (IsMemberSpecialization &&
9139           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9140         NewTemplateDecl->setMemberSpecialization();
9141         assert(OldTemplateDecl->isMemberSpecialization());
9142         // Explicit specializations of a member template do not inherit deleted
9143         // status from the parent member template that they are specializing.
9144         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9145           FunctionDecl *const OldTemplatedDecl =
9146               OldTemplateDecl->getTemplatedDecl();
9147           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9148           OldTemplatedDecl->setDeletedAsWritten(false);
9149         }
9150       }
9151 
9152     } else {
9153       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9154         // This needs to happen first so that 'inline' propagates.
9155         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9156         if (isa<CXXMethodDecl>(NewFD))
9157           NewFD->setAccess(OldDecl->getAccess());
9158       }
9159     }
9160   }
9161 
9162   // Semantic checking for this function declaration (in isolation).
9163 
9164   if (getLangOpts().CPlusPlus) {
9165     // C++-specific checks.
9166     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9167       CheckConstructor(Constructor);
9168     } else if (CXXDestructorDecl *Destructor =
9169                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9170       CXXRecordDecl *Record = Destructor->getParent();
9171       QualType ClassType = Context.getTypeDeclType(Record);
9172 
9173       // FIXME: Shouldn't we be able to perform this check even when the class
9174       // type is dependent? Both gcc and edg can handle that.
9175       if (!ClassType->isDependentType()) {
9176         DeclarationName Name
9177           = Context.DeclarationNames.getCXXDestructorName(
9178                                         Context.getCanonicalType(ClassType));
9179         if (NewFD->getDeclName() != Name) {
9180           Diag(NewFD->getLocation(), diag::err_destructor_name);
9181           NewFD->setInvalidDecl();
9182           return Redeclaration;
9183         }
9184       }
9185     } else if (CXXConversionDecl *Conversion
9186                = dyn_cast<CXXConversionDecl>(NewFD)) {
9187       ActOnConversionDeclarator(Conversion);
9188     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9189       if (auto *TD = Guide->getDescribedFunctionTemplate())
9190         CheckDeductionGuideTemplate(TD);
9191 
9192       // A deduction guide is not on the list of entities that can be
9193       // explicitly specialized.
9194       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9195         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9196             << /*explicit specialization*/ 1;
9197     }
9198 
9199     // Find any virtual functions that this function overrides.
9200     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9201       if (!Method->isFunctionTemplateSpecialization() &&
9202           !Method->getDescribedFunctionTemplate() &&
9203           Method->isCanonicalDecl()) {
9204         if (AddOverriddenMethods(Method->getParent(), Method)) {
9205           // If the function was marked as "static", we have a problem.
9206           if (NewFD->getStorageClass() == SC_Static) {
9207             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9208           }
9209         }
9210       }
9211 
9212       if (Method->isStatic())
9213         checkThisInStaticMemberFunctionType(Method);
9214     }
9215 
9216     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9217     if (NewFD->isOverloadedOperator() &&
9218         CheckOverloadedOperatorDeclaration(NewFD)) {
9219       NewFD->setInvalidDecl();
9220       return Redeclaration;
9221     }
9222 
9223     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9224     if (NewFD->getLiteralIdentifier() &&
9225         CheckLiteralOperatorDeclaration(NewFD)) {
9226       NewFD->setInvalidDecl();
9227       return Redeclaration;
9228     }
9229 
9230     // In C++, check default arguments now that we have merged decls. Unless
9231     // the lexical context is the class, because in this case this is done
9232     // during delayed parsing anyway.
9233     if (!CurContext->isRecord())
9234       CheckCXXDefaultArguments(NewFD);
9235 
9236     // If this function declares a builtin function, check the type of this
9237     // declaration against the expected type for the builtin.
9238     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9239       ASTContext::GetBuiltinTypeError Error;
9240       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9241       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9242       // If the type of the builtin differs only in its exception
9243       // specification, that's OK.
9244       // FIXME: If the types do differ in this way, it would be better to
9245       // retain the 'noexcept' form of the type.
9246       if (!T.isNull() &&
9247           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9248                                                             NewFD->getType()))
9249         // The type of this function differs from the type of the builtin,
9250         // so forget about the builtin entirely.
9251         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9252     }
9253 
9254     // If this function is declared as being extern "C", then check to see if
9255     // the function returns a UDT (class, struct, or union type) that is not C
9256     // compatible, and if it does, warn the user.
9257     // But, issue any diagnostic on the first declaration only.
9258     if (Previous.empty() && NewFD->isExternC()) {
9259       QualType R = NewFD->getReturnType();
9260       if (R->isIncompleteType() && !R->isVoidType())
9261         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9262             << NewFD << R;
9263       else if (!R.isPODType(Context) && !R->isVoidType() &&
9264                !R->isObjCObjectPointerType())
9265         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9266     }
9267 
9268     // C++1z [dcl.fct]p6:
9269     //   [...] whether the function has a non-throwing exception-specification
9270     //   [is] part of the function type
9271     //
9272     // This results in an ABI break between C++14 and C++17 for functions whose
9273     // declared type includes an exception-specification in a parameter or
9274     // return type. (Exception specifications on the function itself are OK in
9275     // most cases, and exception specifications are not permitted in most other
9276     // contexts where they could make it into a mangling.)
9277     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9278       auto HasNoexcept = [&](QualType T) -> bool {
9279         // Strip off declarator chunks that could be between us and a function
9280         // type. We don't need to look far, exception specifications are very
9281         // restricted prior to C++17.
9282         if (auto *RT = T->getAs<ReferenceType>())
9283           T = RT->getPointeeType();
9284         else if (T->isAnyPointerType())
9285           T = T->getPointeeType();
9286         else if (auto *MPT = T->getAs<MemberPointerType>())
9287           T = MPT->getPointeeType();
9288         if (auto *FPT = T->getAs<FunctionProtoType>())
9289           if (FPT->isNothrow(Context))
9290             return true;
9291         return false;
9292       };
9293 
9294       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9295       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9296       for (QualType T : FPT->param_types())
9297         AnyNoexcept |= HasNoexcept(T);
9298       if (AnyNoexcept)
9299         Diag(NewFD->getLocation(),
9300              diag::warn_cxx1z_compat_exception_spec_in_signature)
9301             << NewFD;
9302     }
9303 
9304     if (!Redeclaration && LangOpts.CUDA)
9305       checkCUDATargetOverload(NewFD, Previous);
9306   }
9307   return Redeclaration;
9308 }
9309 
9310 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9311   // C++11 [basic.start.main]p3:
9312   //   A program that [...] declares main to be inline, static or
9313   //   constexpr is ill-formed.
9314   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9315   //   appear in a declaration of main.
9316   // static main is not an error under C99, but we should warn about it.
9317   // We accept _Noreturn main as an extension.
9318   if (FD->getStorageClass() == SC_Static)
9319     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9320          ? diag::err_static_main : diag::warn_static_main)
9321       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9322   if (FD->isInlineSpecified())
9323     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9324       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9325   if (DS.isNoreturnSpecified()) {
9326     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9327     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9328     Diag(NoreturnLoc, diag::ext_noreturn_main);
9329     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9330       << FixItHint::CreateRemoval(NoreturnRange);
9331   }
9332   if (FD->isConstexpr()) {
9333     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9334       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9335     FD->setConstexpr(false);
9336   }
9337 
9338   if (getLangOpts().OpenCL) {
9339     Diag(FD->getLocation(), diag::err_opencl_no_main)
9340         << FD->hasAttr<OpenCLKernelAttr>();
9341     FD->setInvalidDecl();
9342     return;
9343   }
9344 
9345   QualType T = FD->getType();
9346   assert(T->isFunctionType() && "function decl is not of function type");
9347   const FunctionType* FT = T->castAs<FunctionType>();
9348 
9349   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9350     // In C with GNU extensions we allow main() to have non-integer return
9351     // type, but we should warn about the extension, and we disable the
9352     // implicit-return-zero rule.
9353 
9354     // GCC in C mode accepts qualified 'int'.
9355     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9356       FD->setHasImplicitReturnZero(true);
9357     else {
9358       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9359       SourceRange RTRange = FD->getReturnTypeSourceRange();
9360       if (RTRange.isValid())
9361         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9362             << FixItHint::CreateReplacement(RTRange, "int");
9363     }
9364   } else {
9365     // In C and C++, main magically returns 0 if you fall off the end;
9366     // set the flag which tells us that.
9367     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9368 
9369     // All the standards say that main() should return 'int'.
9370     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9371       FD->setHasImplicitReturnZero(true);
9372     else {
9373       // Otherwise, this is just a flat-out error.
9374       SourceRange RTRange = FD->getReturnTypeSourceRange();
9375       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9376           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9377                                 : FixItHint());
9378       FD->setInvalidDecl(true);
9379     }
9380   }
9381 
9382   // Treat protoless main() as nullary.
9383   if (isa<FunctionNoProtoType>(FT)) return;
9384 
9385   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9386   unsigned nparams = FTP->getNumParams();
9387   assert(FD->getNumParams() == nparams);
9388 
9389   bool HasExtraParameters = (nparams > 3);
9390 
9391   if (FTP->isVariadic()) {
9392     Diag(FD->getLocation(), diag::ext_variadic_main);
9393     // FIXME: if we had information about the location of the ellipsis, we
9394     // could add a FixIt hint to remove it as a parameter.
9395   }
9396 
9397   // Darwin passes an undocumented fourth argument of type char**.  If
9398   // other platforms start sprouting these, the logic below will start
9399   // getting shifty.
9400   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9401     HasExtraParameters = false;
9402 
9403   if (HasExtraParameters) {
9404     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9405     FD->setInvalidDecl(true);
9406     nparams = 3;
9407   }
9408 
9409   // FIXME: a lot of the following diagnostics would be improved
9410   // if we had some location information about types.
9411 
9412   QualType CharPP =
9413     Context.getPointerType(Context.getPointerType(Context.CharTy));
9414   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9415 
9416   for (unsigned i = 0; i < nparams; ++i) {
9417     QualType AT = FTP->getParamType(i);
9418 
9419     bool mismatch = true;
9420 
9421     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9422       mismatch = false;
9423     else if (Expected[i] == CharPP) {
9424       // As an extension, the following forms are okay:
9425       //   char const **
9426       //   char const * const *
9427       //   char * const *
9428 
9429       QualifierCollector qs;
9430       const PointerType* PT;
9431       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9432           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9433           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9434                               Context.CharTy)) {
9435         qs.removeConst();
9436         mismatch = !qs.empty();
9437       }
9438     }
9439 
9440     if (mismatch) {
9441       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9442       // TODO: suggest replacing given type with expected type
9443       FD->setInvalidDecl(true);
9444     }
9445   }
9446 
9447   if (nparams == 1 && !FD->isInvalidDecl()) {
9448     Diag(FD->getLocation(), diag::warn_main_one_arg);
9449   }
9450 
9451   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9452     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9453     FD->setInvalidDecl();
9454   }
9455 }
9456 
9457 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9458   QualType T = FD->getType();
9459   assert(T->isFunctionType() && "function decl is not of function type");
9460   const FunctionType *FT = T->castAs<FunctionType>();
9461 
9462   // Set an implicit return of 'zero' if the function can return some integral,
9463   // enumeration, pointer or nullptr type.
9464   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9465       FT->getReturnType()->isAnyPointerType() ||
9466       FT->getReturnType()->isNullPtrType())
9467     // DllMain is exempt because a return value of zero means it failed.
9468     if (FD->getName() != "DllMain")
9469       FD->setHasImplicitReturnZero(true);
9470 
9471   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9472     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9473     FD->setInvalidDecl();
9474   }
9475 }
9476 
9477 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9478   // FIXME: Need strict checking.  In C89, we need to check for
9479   // any assignment, increment, decrement, function-calls, or
9480   // commas outside of a sizeof.  In C99, it's the same list,
9481   // except that the aforementioned are allowed in unevaluated
9482   // expressions.  Everything else falls under the
9483   // "may accept other forms of constant expressions" exception.
9484   // (We never end up here for C++, so the constant expression
9485   // rules there don't matter.)
9486   const Expr *Culprit;
9487   if (Init->isConstantInitializer(Context, false, &Culprit))
9488     return false;
9489   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9490     << Culprit->getSourceRange();
9491   return true;
9492 }
9493 
9494 namespace {
9495   // Visits an initialization expression to see if OrigDecl is evaluated in
9496   // its own initialization and throws a warning if it does.
9497   class SelfReferenceChecker
9498       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9499     Sema &S;
9500     Decl *OrigDecl;
9501     bool isRecordType;
9502     bool isPODType;
9503     bool isReferenceType;
9504 
9505     bool isInitList;
9506     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9507 
9508   public:
9509     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9510 
9511     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9512                                                     S(S), OrigDecl(OrigDecl) {
9513       isPODType = false;
9514       isRecordType = false;
9515       isReferenceType = false;
9516       isInitList = false;
9517       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9518         isPODType = VD->getType().isPODType(S.Context);
9519         isRecordType = VD->getType()->isRecordType();
9520         isReferenceType = VD->getType()->isReferenceType();
9521       }
9522     }
9523 
9524     // For most expressions, just call the visitor.  For initializer lists,
9525     // track the index of the field being initialized since fields are
9526     // initialized in order allowing use of previously initialized fields.
9527     void CheckExpr(Expr *E) {
9528       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9529       if (!InitList) {
9530         Visit(E);
9531         return;
9532       }
9533 
9534       // Track and increment the index here.
9535       isInitList = true;
9536       InitFieldIndex.push_back(0);
9537       for (auto Child : InitList->children()) {
9538         CheckExpr(cast<Expr>(Child));
9539         ++InitFieldIndex.back();
9540       }
9541       InitFieldIndex.pop_back();
9542     }
9543 
9544     // Returns true if MemberExpr is checked and no further checking is needed.
9545     // Returns false if additional checking is required.
9546     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9547       llvm::SmallVector<FieldDecl*, 4> Fields;
9548       Expr *Base = E;
9549       bool ReferenceField = false;
9550 
9551       // Get the field memebers used.
9552       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9553         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9554         if (!FD)
9555           return false;
9556         Fields.push_back(FD);
9557         if (FD->getType()->isReferenceType())
9558           ReferenceField = true;
9559         Base = ME->getBase()->IgnoreParenImpCasts();
9560       }
9561 
9562       // Keep checking only if the base Decl is the same.
9563       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9564       if (!DRE || DRE->getDecl() != OrigDecl)
9565         return false;
9566 
9567       // A reference field can be bound to an unininitialized field.
9568       if (CheckReference && !ReferenceField)
9569         return true;
9570 
9571       // Convert FieldDecls to their index number.
9572       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9573       for (const FieldDecl *I : llvm::reverse(Fields))
9574         UsedFieldIndex.push_back(I->getFieldIndex());
9575 
9576       // See if a warning is needed by checking the first difference in index
9577       // numbers.  If field being used has index less than the field being
9578       // initialized, then the use is safe.
9579       for (auto UsedIter = UsedFieldIndex.begin(),
9580                 UsedEnd = UsedFieldIndex.end(),
9581                 OrigIter = InitFieldIndex.begin(),
9582                 OrigEnd = InitFieldIndex.end();
9583            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9584         if (*UsedIter < *OrigIter)
9585           return true;
9586         if (*UsedIter > *OrigIter)
9587           break;
9588       }
9589 
9590       // TODO: Add a different warning which will print the field names.
9591       HandleDeclRefExpr(DRE);
9592       return true;
9593     }
9594 
9595     // For most expressions, the cast is directly above the DeclRefExpr.
9596     // For conditional operators, the cast can be outside the conditional
9597     // operator if both expressions are DeclRefExpr's.
9598     void HandleValue(Expr *E) {
9599       E = E->IgnoreParens();
9600       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9601         HandleDeclRefExpr(DRE);
9602         return;
9603       }
9604 
9605       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9606         Visit(CO->getCond());
9607         HandleValue(CO->getTrueExpr());
9608         HandleValue(CO->getFalseExpr());
9609         return;
9610       }
9611 
9612       if (BinaryConditionalOperator *BCO =
9613               dyn_cast<BinaryConditionalOperator>(E)) {
9614         Visit(BCO->getCond());
9615         HandleValue(BCO->getFalseExpr());
9616         return;
9617       }
9618 
9619       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9620         HandleValue(OVE->getSourceExpr());
9621         return;
9622       }
9623 
9624       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9625         if (BO->getOpcode() == BO_Comma) {
9626           Visit(BO->getLHS());
9627           HandleValue(BO->getRHS());
9628           return;
9629         }
9630       }
9631 
9632       if (isa<MemberExpr>(E)) {
9633         if (isInitList) {
9634           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9635                                       false /*CheckReference*/))
9636             return;
9637         }
9638 
9639         Expr *Base = E->IgnoreParenImpCasts();
9640         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9641           // Check for static member variables and don't warn on them.
9642           if (!isa<FieldDecl>(ME->getMemberDecl()))
9643             return;
9644           Base = ME->getBase()->IgnoreParenImpCasts();
9645         }
9646         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9647           HandleDeclRefExpr(DRE);
9648         return;
9649       }
9650 
9651       Visit(E);
9652     }
9653 
9654     // Reference types not handled in HandleValue are handled here since all
9655     // uses of references are bad, not just r-value uses.
9656     void VisitDeclRefExpr(DeclRefExpr *E) {
9657       if (isReferenceType)
9658         HandleDeclRefExpr(E);
9659     }
9660 
9661     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9662       if (E->getCastKind() == CK_LValueToRValue) {
9663         HandleValue(E->getSubExpr());
9664         return;
9665       }
9666 
9667       Inherited::VisitImplicitCastExpr(E);
9668     }
9669 
9670     void VisitMemberExpr(MemberExpr *E) {
9671       if (isInitList) {
9672         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9673           return;
9674       }
9675 
9676       // Don't warn on arrays since they can be treated as pointers.
9677       if (E->getType()->canDecayToPointerType()) return;
9678 
9679       // Warn when a non-static method call is followed by non-static member
9680       // field accesses, which is followed by a DeclRefExpr.
9681       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9682       bool Warn = (MD && !MD->isStatic());
9683       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9684       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9685         if (!isa<FieldDecl>(ME->getMemberDecl()))
9686           Warn = false;
9687         Base = ME->getBase()->IgnoreParenImpCasts();
9688       }
9689 
9690       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9691         if (Warn)
9692           HandleDeclRefExpr(DRE);
9693         return;
9694       }
9695 
9696       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9697       // Visit that expression.
9698       Visit(Base);
9699     }
9700 
9701     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9702       Expr *Callee = E->getCallee();
9703 
9704       if (isa<UnresolvedLookupExpr>(Callee))
9705         return Inherited::VisitCXXOperatorCallExpr(E);
9706 
9707       Visit(Callee);
9708       for (auto Arg: E->arguments())
9709         HandleValue(Arg->IgnoreParenImpCasts());
9710     }
9711 
9712     void VisitUnaryOperator(UnaryOperator *E) {
9713       // For POD record types, addresses of its own members are well-defined.
9714       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9715           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9716         if (!isPODType)
9717           HandleValue(E->getSubExpr());
9718         return;
9719       }
9720 
9721       if (E->isIncrementDecrementOp()) {
9722         HandleValue(E->getSubExpr());
9723         return;
9724       }
9725 
9726       Inherited::VisitUnaryOperator(E);
9727     }
9728 
9729     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9730 
9731     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9732       if (E->getConstructor()->isCopyConstructor()) {
9733         Expr *ArgExpr = E->getArg(0);
9734         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9735           if (ILE->getNumInits() == 1)
9736             ArgExpr = ILE->getInit(0);
9737         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9738           if (ICE->getCastKind() == CK_NoOp)
9739             ArgExpr = ICE->getSubExpr();
9740         HandleValue(ArgExpr);
9741         return;
9742       }
9743       Inherited::VisitCXXConstructExpr(E);
9744     }
9745 
9746     void VisitCallExpr(CallExpr *E) {
9747       // Treat std::move as a use.
9748       if (E->getNumArgs() == 1) {
9749         if (FunctionDecl *FD = E->getDirectCallee()) {
9750           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9751               FD->getIdentifier()->isStr("move")) {
9752             HandleValue(E->getArg(0));
9753             return;
9754           }
9755         }
9756       }
9757 
9758       Inherited::VisitCallExpr(E);
9759     }
9760 
9761     void VisitBinaryOperator(BinaryOperator *E) {
9762       if (E->isCompoundAssignmentOp()) {
9763         HandleValue(E->getLHS());
9764         Visit(E->getRHS());
9765         return;
9766       }
9767 
9768       Inherited::VisitBinaryOperator(E);
9769     }
9770 
9771     // A custom visitor for BinaryConditionalOperator is needed because the
9772     // regular visitor would check the condition and true expression separately
9773     // but both point to the same place giving duplicate diagnostics.
9774     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9775       Visit(E->getCond());
9776       Visit(E->getFalseExpr());
9777     }
9778 
9779     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9780       Decl* ReferenceDecl = DRE->getDecl();
9781       if (OrigDecl != ReferenceDecl) return;
9782       unsigned diag;
9783       if (isReferenceType) {
9784         diag = diag::warn_uninit_self_reference_in_reference_init;
9785       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9786         diag = diag::warn_static_self_reference_in_init;
9787       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9788                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9789                  DRE->getDecl()->getType()->isRecordType()) {
9790         diag = diag::warn_uninit_self_reference_in_init;
9791       } else {
9792         // Local variables will be handled by the CFG analysis.
9793         return;
9794       }
9795 
9796       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9797                             S.PDiag(diag)
9798                               << DRE->getNameInfo().getName()
9799                               << OrigDecl->getLocation()
9800                               << DRE->getSourceRange());
9801     }
9802   };
9803 
9804   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9805   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9806                                  bool DirectInit) {
9807     // Parameters arguments are occassionially constructed with itself,
9808     // for instance, in recursive functions.  Skip them.
9809     if (isa<ParmVarDecl>(OrigDecl))
9810       return;
9811 
9812     E = E->IgnoreParens();
9813 
9814     // Skip checking T a = a where T is not a record or reference type.
9815     // Doing so is a way to silence uninitialized warnings.
9816     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9817       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9818         if (ICE->getCastKind() == CK_LValueToRValue)
9819           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9820             if (DRE->getDecl() == OrigDecl)
9821               return;
9822 
9823     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9824   }
9825 } // end anonymous namespace
9826 
9827 namespace {
9828   // Simple wrapper to add the name of a variable or (if no variable is
9829   // available) a DeclarationName into a diagnostic.
9830   struct VarDeclOrName {
9831     VarDecl *VDecl;
9832     DeclarationName Name;
9833 
9834     friend const Sema::SemaDiagnosticBuilder &
9835     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9836       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9837     }
9838   };
9839 } // end anonymous namespace
9840 
9841 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9842                                             DeclarationName Name, QualType Type,
9843                                             TypeSourceInfo *TSI,
9844                                             SourceRange Range, bool DirectInit,
9845                                             Expr *Init) {
9846   bool IsInitCapture = !VDecl;
9847   assert((!VDecl || !VDecl->isInitCapture()) &&
9848          "init captures are expected to be deduced prior to initialization");
9849 
9850   VarDeclOrName VN{VDecl, Name};
9851 
9852   DeducedType *Deduced = Type->getContainedDeducedType();
9853   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9854 
9855   // C++11 [dcl.spec.auto]p3
9856   if (!Init) {
9857     assert(VDecl && "no init for init capture deduction?");
9858     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9859       << VDecl->getDeclName() << Type;
9860     return QualType();
9861   }
9862 
9863   ArrayRef<Expr*> DeduceInits = Init;
9864   if (DirectInit) {
9865     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9866       DeduceInits = PL->exprs();
9867   }
9868 
9869   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9870     assert(VDecl && "non-auto type for init capture deduction?");
9871     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9872     InitializationKind Kind = InitializationKind::CreateForInit(
9873         VDecl->getLocation(), DirectInit, Init);
9874     // FIXME: Initialization should not be taking a mutable list of inits.
9875     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9876     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9877                                                        InitsCopy);
9878   }
9879 
9880   if (DirectInit) {
9881     if (auto *IL = dyn_cast<InitListExpr>(Init))
9882       DeduceInits = IL->inits();
9883   }
9884 
9885   // Deduction only works if we have exactly one source expression.
9886   if (DeduceInits.empty()) {
9887     // It isn't possible to write this directly, but it is possible to
9888     // end up in this situation with "auto x(some_pack...);"
9889     Diag(Init->getLocStart(), IsInitCapture
9890                                   ? diag::err_init_capture_no_expression
9891                                   : diag::err_auto_var_init_no_expression)
9892         << VN << Type << Range;
9893     return QualType();
9894   }
9895 
9896   if (DeduceInits.size() > 1) {
9897     Diag(DeduceInits[1]->getLocStart(),
9898          IsInitCapture ? diag::err_init_capture_multiple_expressions
9899                        : diag::err_auto_var_init_multiple_expressions)
9900         << VN << Type << Range;
9901     return QualType();
9902   }
9903 
9904   Expr *DeduceInit = DeduceInits[0];
9905   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9906     Diag(Init->getLocStart(), IsInitCapture
9907                                   ? diag::err_init_capture_paren_braces
9908                                   : diag::err_auto_var_init_paren_braces)
9909         << isa<InitListExpr>(Init) << VN << Type << Range;
9910     return QualType();
9911   }
9912 
9913   // Expressions default to 'id' when we're in a debugger.
9914   bool DefaultedAnyToId = false;
9915   if (getLangOpts().DebuggerCastResultToId &&
9916       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9917     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9918     if (Result.isInvalid()) {
9919       return QualType();
9920     }
9921     Init = Result.get();
9922     DefaultedAnyToId = true;
9923   }
9924 
9925   // C++ [dcl.decomp]p1:
9926   //   If the assignment-expression [...] has array type A and no ref-qualifier
9927   //   is present, e has type cv A
9928   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9929       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9930       DeduceInit->getType()->isConstantArrayType())
9931     return Context.getQualifiedType(DeduceInit->getType(),
9932                                     Type.getQualifiers());
9933 
9934   QualType DeducedType;
9935   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9936     if (!IsInitCapture)
9937       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9938     else if (isa<InitListExpr>(Init))
9939       Diag(Range.getBegin(),
9940            diag::err_init_capture_deduction_failure_from_init_list)
9941           << VN
9942           << (DeduceInit->getType().isNull() ? TSI->getType()
9943                                              : DeduceInit->getType())
9944           << DeduceInit->getSourceRange();
9945     else
9946       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9947           << VN << TSI->getType()
9948           << (DeduceInit->getType().isNull() ? TSI->getType()
9949                                              : DeduceInit->getType())
9950           << DeduceInit->getSourceRange();
9951   }
9952 
9953   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9954   // 'id' instead of a specific object type prevents most of our usual
9955   // checks.
9956   // We only want to warn outside of template instantiations, though:
9957   // inside a template, the 'id' could have come from a parameter.
9958   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
9959       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9960     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9961     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9962   }
9963 
9964   return DeducedType;
9965 }
9966 
9967 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9968                                          Expr *Init) {
9969   QualType DeducedType = deduceVarTypeFromInitializer(
9970       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9971       VDecl->getSourceRange(), DirectInit, Init);
9972   if (DeducedType.isNull()) {
9973     VDecl->setInvalidDecl();
9974     return true;
9975   }
9976 
9977   VDecl->setType(DeducedType);
9978   assert(VDecl->isLinkageValid());
9979 
9980   // In ARC, infer lifetime.
9981   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9982     VDecl->setInvalidDecl();
9983 
9984   // If this is a redeclaration, check that the type we just deduced matches
9985   // the previously declared type.
9986   if (VarDecl *Old = VDecl->getPreviousDecl()) {
9987     // We never need to merge the type, because we cannot form an incomplete
9988     // array of auto, nor deduce such a type.
9989     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9990   }
9991 
9992   // Check the deduced type is valid for a variable declaration.
9993   CheckVariableDeclarationType(VDecl);
9994   return VDecl->isInvalidDecl();
9995 }
9996 
9997 /// AddInitializerToDecl - Adds the initializer Init to the
9998 /// declaration dcl. If DirectInit is true, this is C++ direct
9999 /// initialization rather than copy initialization.
10000 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10001   // If there is no declaration, there was an error parsing it.  Just ignore
10002   // the initializer.
10003   if (!RealDecl || RealDecl->isInvalidDecl()) {
10004     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10005     return;
10006   }
10007 
10008   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10009     // Pure-specifiers are handled in ActOnPureSpecifier.
10010     Diag(Method->getLocation(), diag::err_member_function_initialization)
10011       << Method->getDeclName() << Init->getSourceRange();
10012     Method->setInvalidDecl();
10013     return;
10014   }
10015 
10016   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10017   if (!VDecl) {
10018     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10019     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10020     RealDecl->setInvalidDecl();
10021     return;
10022   }
10023 
10024   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10025   if (VDecl->getType()->isUndeducedType()) {
10026     // Attempt typo correction early so that the type of the init expression can
10027     // be deduced based on the chosen correction if the original init contains a
10028     // TypoExpr.
10029     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10030     if (!Res.isUsable()) {
10031       RealDecl->setInvalidDecl();
10032       return;
10033     }
10034     Init = Res.get();
10035 
10036     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10037       return;
10038   }
10039 
10040   // dllimport cannot be used on variable definitions.
10041   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10042     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10043     VDecl->setInvalidDecl();
10044     return;
10045   }
10046 
10047   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10048     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10049     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10050     VDecl->setInvalidDecl();
10051     return;
10052   }
10053 
10054   if (!VDecl->getType()->isDependentType()) {
10055     // A definition must end up with a complete type, which means it must be
10056     // complete with the restriction that an array type might be completed by
10057     // the initializer; note that later code assumes this restriction.
10058     QualType BaseDeclType = VDecl->getType();
10059     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10060       BaseDeclType = Array->getElementType();
10061     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10062                             diag::err_typecheck_decl_incomplete_type)) {
10063       RealDecl->setInvalidDecl();
10064       return;
10065     }
10066 
10067     // The variable can not have an abstract class type.
10068     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10069                                diag::err_abstract_type_in_decl,
10070                                AbstractVariableType))
10071       VDecl->setInvalidDecl();
10072   }
10073 
10074   // If adding the initializer will turn this declaration into a definition,
10075   // and we already have a definition for this variable, diagnose or otherwise
10076   // handle the situation.
10077   VarDecl *Def;
10078   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10079       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10080       !VDecl->isThisDeclarationADemotedDefinition() &&
10081       checkVarDeclRedefinition(Def, VDecl))
10082     return;
10083 
10084   if (getLangOpts().CPlusPlus) {
10085     // C++ [class.static.data]p4
10086     //   If a static data member is of const integral or const
10087     //   enumeration type, its declaration in the class definition can
10088     //   specify a constant-initializer which shall be an integral
10089     //   constant expression (5.19). In that case, the member can appear
10090     //   in integral constant expressions. The member shall still be
10091     //   defined in a namespace scope if it is used in the program and the
10092     //   namespace scope definition shall not contain an initializer.
10093     //
10094     // We already performed a redefinition check above, but for static
10095     // data members we also need to check whether there was an in-class
10096     // declaration with an initializer.
10097     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10098       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10099           << VDecl->getDeclName();
10100       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10101            diag::note_previous_initializer)
10102           << 0;
10103       return;
10104     }
10105 
10106     if (VDecl->hasLocalStorage())
10107       getCurFunction()->setHasBranchProtectedScope();
10108 
10109     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10110       VDecl->setInvalidDecl();
10111       return;
10112     }
10113   }
10114 
10115   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10116   // a kernel function cannot be initialized."
10117   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10118     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10119     VDecl->setInvalidDecl();
10120     return;
10121   }
10122 
10123   // Get the decls type and save a reference for later, since
10124   // CheckInitializerTypes may change it.
10125   QualType DclT = VDecl->getType(), SavT = DclT;
10126 
10127   // Expressions default to 'id' when we're in a debugger
10128   // and we are assigning it to a variable of Objective-C pointer type.
10129   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10130       Init->getType() == Context.UnknownAnyTy) {
10131     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10132     if (Result.isInvalid()) {
10133       VDecl->setInvalidDecl();
10134       return;
10135     }
10136     Init = Result.get();
10137   }
10138 
10139   // Perform the initialization.
10140   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10141   if (!VDecl->isInvalidDecl()) {
10142     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10143     InitializationKind Kind = InitializationKind::CreateForInit(
10144         VDecl->getLocation(), DirectInit, Init);
10145 
10146     MultiExprArg Args = Init;
10147     if (CXXDirectInit)
10148       Args = MultiExprArg(CXXDirectInit->getExprs(),
10149                           CXXDirectInit->getNumExprs());
10150 
10151     // Try to correct any TypoExprs in the initialization arguments.
10152     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10153       ExprResult Res = CorrectDelayedTyposInExpr(
10154           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10155             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10156             return Init.Failed() ? ExprError() : E;
10157           });
10158       if (Res.isInvalid()) {
10159         VDecl->setInvalidDecl();
10160       } else if (Res.get() != Args[Idx]) {
10161         Args[Idx] = Res.get();
10162       }
10163     }
10164     if (VDecl->isInvalidDecl())
10165       return;
10166 
10167     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10168                                    /*TopLevelOfInitList=*/false,
10169                                    /*TreatUnavailableAsInvalid=*/false);
10170     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10171     if (Result.isInvalid()) {
10172       VDecl->setInvalidDecl();
10173       return;
10174     }
10175 
10176     Init = Result.getAs<Expr>();
10177   }
10178 
10179   // Check for self-references within variable initializers.
10180   // Variables declared within a function/method body (except for references)
10181   // are handled by a dataflow analysis.
10182   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10183       VDecl->getType()->isReferenceType()) {
10184     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10185   }
10186 
10187   // If the type changed, it means we had an incomplete type that was
10188   // completed by the initializer. For example:
10189   //   int ary[] = { 1, 3, 5 };
10190   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10191   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10192     VDecl->setType(DclT);
10193 
10194   if (!VDecl->isInvalidDecl()) {
10195     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10196 
10197     if (VDecl->hasAttr<BlocksAttr>())
10198       checkRetainCycles(VDecl, Init);
10199 
10200     // It is safe to assign a weak reference into a strong variable.
10201     // Although this code can still have problems:
10202     //   id x = self.weakProp;
10203     //   id y = self.weakProp;
10204     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10205     // paths through the function. This should be revisited if
10206     // -Wrepeated-use-of-weak is made flow-sensitive.
10207     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10208          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10209         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10210                          Init->getLocStart()))
10211       getCurFunction()->markSafeWeakUse(Init);
10212   }
10213 
10214   // The initialization is usually a full-expression.
10215   //
10216   // FIXME: If this is a braced initialization of an aggregate, it is not
10217   // an expression, and each individual field initializer is a separate
10218   // full-expression. For instance, in:
10219   //
10220   //   struct Temp { ~Temp(); };
10221   //   struct S { S(Temp); };
10222   //   struct T { S a, b; } t = { Temp(), Temp() }
10223   //
10224   // we should destroy the first Temp before constructing the second.
10225   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10226                                           false,
10227                                           VDecl->isConstexpr());
10228   if (Result.isInvalid()) {
10229     VDecl->setInvalidDecl();
10230     return;
10231   }
10232   Init = Result.get();
10233 
10234   // Attach the initializer to the decl.
10235   VDecl->setInit(Init);
10236 
10237   if (VDecl->isLocalVarDecl()) {
10238     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10239     // static storage duration shall be constant expressions or string literals.
10240     // C++ does not have this restriction.
10241     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10242       const Expr *Culprit;
10243       if (VDecl->getStorageClass() == SC_Static)
10244         CheckForConstantInitializer(Init, DclT);
10245       // C89 is stricter than C99 for non-static aggregate types.
10246       // C89 6.5.7p3: All the expressions [...] in an initializer list
10247       // for an object that has aggregate or union type shall be
10248       // constant expressions.
10249       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10250                isa<InitListExpr>(Init) &&
10251                !Init->isConstantInitializer(Context, false, &Culprit))
10252         Diag(Culprit->getExprLoc(),
10253              diag::ext_aggregate_init_not_constant)
10254           << Culprit->getSourceRange();
10255     }
10256   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10257              VDecl->getLexicalDeclContext()->isRecord()) {
10258     // This is an in-class initialization for a static data member, e.g.,
10259     //
10260     // struct S {
10261     //   static const int value = 17;
10262     // };
10263 
10264     // C++ [class.mem]p4:
10265     //   A member-declarator can contain a constant-initializer only
10266     //   if it declares a static member (9.4) of const integral or
10267     //   const enumeration type, see 9.4.2.
10268     //
10269     // C++11 [class.static.data]p3:
10270     //   If a non-volatile non-inline const static data member is of integral
10271     //   or enumeration type, its declaration in the class definition can
10272     //   specify a brace-or-equal-initializer in which every initializer-clause
10273     //   that is an assignment-expression is a constant expression. A static
10274     //   data member of literal type can be declared in the class definition
10275     //   with the constexpr specifier; if so, its declaration shall specify a
10276     //   brace-or-equal-initializer in which every initializer-clause that is
10277     //   an assignment-expression is a constant expression.
10278 
10279     // Do nothing on dependent types.
10280     if (DclT->isDependentType()) {
10281 
10282     // Allow any 'static constexpr' members, whether or not they are of literal
10283     // type. We separately check that every constexpr variable is of literal
10284     // type.
10285     } else if (VDecl->isConstexpr()) {
10286 
10287     // Require constness.
10288     } else if (!DclT.isConstQualified()) {
10289       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10290         << Init->getSourceRange();
10291       VDecl->setInvalidDecl();
10292 
10293     // We allow integer constant expressions in all cases.
10294     } else if (DclT->isIntegralOrEnumerationType()) {
10295       // Check whether the expression is a constant expression.
10296       SourceLocation Loc;
10297       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10298         // In C++11, a non-constexpr const static data member with an
10299         // in-class initializer cannot be volatile.
10300         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10301       else if (Init->isValueDependent())
10302         ; // Nothing to check.
10303       else if (Init->isIntegerConstantExpr(Context, &Loc))
10304         ; // Ok, it's an ICE!
10305       else if (Init->isEvaluatable(Context)) {
10306         // If we can constant fold the initializer through heroics, accept it,
10307         // but report this as a use of an extension for -pedantic.
10308         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10309           << Init->getSourceRange();
10310       } else {
10311         // Otherwise, this is some crazy unknown case.  Report the issue at the
10312         // location provided by the isIntegerConstantExpr failed check.
10313         Diag(Loc, diag::err_in_class_initializer_non_constant)
10314           << Init->getSourceRange();
10315         VDecl->setInvalidDecl();
10316       }
10317 
10318     // We allow foldable floating-point constants as an extension.
10319     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10320       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10321       // it anyway and provide a fixit to add the 'constexpr'.
10322       if (getLangOpts().CPlusPlus11) {
10323         Diag(VDecl->getLocation(),
10324              diag::ext_in_class_initializer_float_type_cxx11)
10325             << DclT << Init->getSourceRange();
10326         Diag(VDecl->getLocStart(),
10327              diag::note_in_class_initializer_float_type_cxx11)
10328             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10329       } else {
10330         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10331           << DclT << Init->getSourceRange();
10332 
10333         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10334           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10335             << Init->getSourceRange();
10336           VDecl->setInvalidDecl();
10337         }
10338       }
10339 
10340     // Suggest adding 'constexpr' in C++11 for literal types.
10341     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10342       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10343         << DclT << Init->getSourceRange()
10344         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10345       VDecl->setConstexpr(true);
10346 
10347     } else {
10348       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10349         << DclT << Init->getSourceRange();
10350       VDecl->setInvalidDecl();
10351     }
10352   } else if (VDecl->isFileVarDecl()) {
10353     // In C, extern is typically used to avoid tentative definitions when
10354     // declaring variables in headers, but adding an intializer makes it a
10355     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10356     // In C++, extern is often used to give implictly static const variables
10357     // external linkage, so don't warn in that case. If selectany is present,
10358     // this might be header code intended for C and C++ inclusion, so apply the
10359     // C++ rules.
10360     if (VDecl->getStorageClass() == SC_Extern &&
10361         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10362          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10363         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10364         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10365       Diag(VDecl->getLocation(), diag::warn_extern_init);
10366 
10367     // C99 6.7.8p4. All file scoped initializers need to be constant.
10368     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10369       CheckForConstantInitializer(Init, DclT);
10370   }
10371 
10372   // We will represent direct-initialization similarly to copy-initialization:
10373   //    int x(1);  -as-> int x = 1;
10374   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10375   //
10376   // Clients that want to distinguish between the two forms, can check for
10377   // direct initializer using VarDecl::getInitStyle().
10378   // A major benefit is that clients that don't particularly care about which
10379   // exactly form was it (like the CodeGen) can handle both cases without
10380   // special case code.
10381 
10382   // C++ 8.5p11:
10383   // The form of initialization (using parentheses or '=') is generally
10384   // insignificant, but does matter when the entity being initialized has a
10385   // class type.
10386   if (CXXDirectInit) {
10387     assert(DirectInit && "Call-style initializer must be direct init.");
10388     VDecl->setInitStyle(VarDecl::CallInit);
10389   } else if (DirectInit) {
10390     // This must be list-initialization. No other way is direct-initialization.
10391     VDecl->setInitStyle(VarDecl::ListInit);
10392   }
10393 
10394   CheckCompleteVariableDeclaration(VDecl);
10395 }
10396 
10397 /// ActOnInitializerError - Given that there was an error parsing an
10398 /// initializer for the given declaration, try to return to some form
10399 /// of sanity.
10400 void Sema::ActOnInitializerError(Decl *D) {
10401   // Our main concern here is re-establishing invariants like "a
10402   // variable's type is either dependent or complete".
10403   if (!D || D->isInvalidDecl()) return;
10404 
10405   VarDecl *VD = dyn_cast<VarDecl>(D);
10406   if (!VD) return;
10407 
10408   // Bindings are not usable if we can't make sense of the initializer.
10409   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10410     for (auto *BD : DD->bindings())
10411       BD->setInvalidDecl();
10412 
10413   // Auto types are meaningless if we can't make sense of the initializer.
10414   if (ParsingInitForAutoVars.count(D)) {
10415     D->setInvalidDecl();
10416     return;
10417   }
10418 
10419   QualType Ty = VD->getType();
10420   if (Ty->isDependentType()) return;
10421 
10422   // Require a complete type.
10423   if (RequireCompleteType(VD->getLocation(),
10424                           Context.getBaseElementType(Ty),
10425                           diag::err_typecheck_decl_incomplete_type)) {
10426     VD->setInvalidDecl();
10427     return;
10428   }
10429 
10430   // Require a non-abstract type.
10431   if (RequireNonAbstractType(VD->getLocation(), Ty,
10432                              diag::err_abstract_type_in_decl,
10433                              AbstractVariableType)) {
10434     VD->setInvalidDecl();
10435     return;
10436   }
10437 
10438   // Don't bother complaining about constructors or destructors,
10439   // though.
10440 }
10441 
10442 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10443   // If there is no declaration, there was an error parsing it. Just ignore it.
10444   if (!RealDecl)
10445     return;
10446 
10447   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10448     QualType Type = Var->getType();
10449 
10450     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10451     if (isa<DecompositionDecl>(RealDecl)) {
10452       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10453       Var->setInvalidDecl();
10454       return;
10455     }
10456 
10457     if (Type->isUndeducedType() &&
10458         DeduceVariableDeclarationType(Var, false, nullptr))
10459       return;
10460 
10461     // C++11 [class.static.data]p3: A static data member can be declared with
10462     // the constexpr specifier; if so, its declaration shall specify
10463     // a brace-or-equal-initializer.
10464     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10465     // the definition of a variable [...] or the declaration of a static data
10466     // member.
10467     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10468         !Var->isThisDeclarationADemotedDefinition()) {
10469       if (Var->isStaticDataMember()) {
10470         // C++1z removes the relevant rule; the in-class declaration is always
10471         // a definition there.
10472         if (!getLangOpts().CPlusPlus1z) {
10473           Diag(Var->getLocation(),
10474                diag::err_constexpr_static_mem_var_requires_init)
10475             << Var->getDeclName();
10476           Var->setInvalidDecl();
10477           return;
10478         }
10479       } else {
10480         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10481         Var->setInvalidDecl();
10482         return;
10483       }
10484     }
10485 
10486     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10487     // definition having the concept specifier is called a variable concept. A
10488     // concept definition refers to [...] a variable concept and its initializer.
10489     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10490       if (VTD->isConcept()) {
10491         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10492         Var->setInvalidDecl();
10493         return;
10494       }
10495     }
10496 
10497     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10498     // be initialized.
10499     if (!Var->isInvalidDecl() &&
10500         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10501         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10502       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10503       Var->setInvalidDecl();
10504       return;
10505     }
10506 
10507     switch (Var->isThisDeclarationADefinition()) {
10508     case VarDecl::Definition:
10509       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10510         break;
10511 
10512       // We have an out-of-line definition of a static data member
10513       // that has an in-class initializer, so we type-check this like
10514       // a declaration.
10515       //
10516       // Fall through
10517 
10518     case VarDecl::DeclarationOnly:
10519       // It's only a declaration.
10520 
10521       // Block scope. C99 6.7p7: If an identifier for an object is
10522       // declared with no linkage (C99 6.2.2p6), the type for the
10523       // object shall be complete.
10524       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10525           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10526           RequireCompleteType(Var->getLocation(), Type,
10527                               diag::err_typecheck_decl_incomplete_type))
10528         Var->setInvalidDecl();
10529 
10530       // Make sure that the type is not abstract.
10531       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10532           RequireNonAbstractType(Var->getLocation(), Type,
10533                                  diag::err_abstract_type_in_decl,
10534                                  AbstractVariableType))
10535         Var->setInvalidDecl();
10536       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10537           Var->getStorageClass() == SC_PrivateExtern) {
10538         Diag(Var->getLocation(), diag::warn_private_extern);
10539         Diag(Var->getLocation(), diag::note_private_extern);
10540       }
10541 
10542       return;
10543 
10544     case VarDecl::TentativeDefinition:
10545       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10546       // object that has file scope without an initializer, and without a
10547       // storage-class specifier or with the storage-class specifier "static",
10548       // constitutes a tentative definition. Note: A tentative definition with
10549       // external linkage is valid (C99 6.2.2p5).
10550       if (!Var->isInvalidDecl()) {
10551         if (const IncompleteArrayType *ArrayT
10552                                     = Context.getAsIncompleteArrayType(Type)) {
10553           if (RequireCompleteType(Var->getLocation(),
10554                                   ArrayT->getElementType(),
10555                                   diag::err_illegal_decl_array_incomplete_type))
10556             Var->setInvalidDecl();
10557         } else if (Var->getStorageClass() == SC_Static) {
10558           // C99 6.9.2p3: If the declaration of an identifier for an object is
10559           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10560           // declared type shall not be an incomplete type.
10561           // NOTE: code such as the following
10562           //     static struct s;
10563           //     struct s { int a; };
10564           // is accepted by gcc. Hence here we issue a warning instead of
10565           // an error and we do not invalidate the static declaration.
10566           // NOTE: to avoid multiple warnings, only check the first declaration.
10567           if (Var->isFirstDecl())
10568             RequireCompleteType(Var->getLocation(), Type,
10569                                 diag::ext_typecheck_decl_incomplete_type);
10570         }
10571       }
10572 
10573       // Record the tentative definition; we're done.
10574       if (!Var->isInvalidDecl())
10575         TentativeDefinitions.push_back(Var);
10576       return;
10577     }
10578 
10579     // Provide a specific diagnostic for uninitialized variable
10580     // definitions with incomplete array type.
10581     if (Type->isIncompleteArrayType()) {
10582       Diag(Var->getLocation(),
10583            diag::err_typecheck_incomplete_array_needs_initializer);
10584       Var->setInvalidDecl();
10585       return;
10586     }
10587 
10588     // Provide a specific diagnostic for uninitialized variable
10589     // definitions with reference type.
10590     if (Type->isReferenceType()) {
10591       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10592         << Var->getDeclName()
10593         << SourceRange(Var->getLocation(), Var->getLocation());
10594       Var->setInvalidDecl();
10595       return;
10596     }
10597 
10598     // Do not attempt to type-check the default initializer for a
10599     // variable with dependent type.
10600     if (Type->isDependentType())
10601       return;
10602 
10603     if (Var->isInvalidDecl())
10604       return;
10605 
10606     if (!Var->hasAttr<AliasAttr>()) {
10607       if (RequireCompleteType(Var->getLocation(),
10608                               Context.getBaseElementType(Type),
10609                               diag::err_typecheck_decl_incomplete_type)) {
10610         Var->setInvalidDecl();
10611         return;
10612       }
10613     } else {
10614       return;
10615     }
10616 
10617     // The variable can not have an abstract class type.
10618     if (RequireNonAbstractType(Var->getLocation(), Type,
10619                                diag::err_abstract_type_in_decl,
10620                                AbstractVariableType)) {
10621       Var->setInvalidDecl();
10622       return;
10623     }
10624 
10625     // Check for jumps past the implicit initializer.  C++0x
10626     // clarifies that this applies to a "variable with automatic
10627     // storage duration", not a "local variable".
10628     // C++11 [stmt.dcl]p3
10629     //   A program that jumps from a point where a variable with automatic
10630     //   storage duration is not in scope to a point where it is in scope is
10631     //   ill-formed unless the variable has scalar type, class type with a
10632     //   trivial default constructor and a trivial destructor, a cv-qualified
10633     //   version of one of these types, or an array of one of the preceding
10634     //   types and is declared without an initializer.
10635     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10636       if (const RecordType *Record
10637             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10638         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10639         // Mark the function for further checking even if the looser rules of
10640         // C++11 do not require such checks, so that we can diagnose
10641         // incompatibilities with C++98.
10642         if (!CXXRecord->isPOD())
10643           getCurFunction()->setHasBranchProtectedScope();
10644       }
10645     }
10646 
10647     // C++03 [dcl.init]p9:
10648     //   If no initializer is specified for an object, and the
10649     //   object is of (possibly cv-qualified) non-POD class type (or
10650     //   array thereof), the object shall be default-initialized; if
10651     //   the object is of const-qualified type, the underlying class
10652     //   type shall have a user-declared default
10653     //   constructor. Otherwise, if no initializer is specified for
10654     //   a non- static object, the object and its subobjects, if
10655     //   any, have an indeterminate initial value); if the object
10656     //   or any of its subobjects are of const-qualified type, the
10657     //   program is ill-formed.
10658     // C++0x [dcl.init]p11:
10659     //   If no initializer is specified for an object, the object is
10660     //   default-initialized; [...].
10661     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10662     InitializationKind Kind
10663       = InitializationKind::CreateDefault(Var->getLocation());
10664 
10665     InitializationSequence InitSeq(*this, Entity, Kind, None);
10666     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10667     if (Init.isInvalid())
10668       Var->setInvalidDecl();
10669     else if (Init.get()) {
10670       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10671       // This is important for template substitution.
10672       Var->setInitStyle(VarDecl::CallInit);
10673     }
10674 
10675     CheckCompleteVariableDeclaration(Var);
10676   }
10677 }
10678 
10679 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10680   // If there is no declaration, there was an error parsing it. Ignore it.
10681   if (!D)
10682     return;
10683 
10684   VarDecl *VD = dyn_cast<VarDecl>(D);
10685   if (!VD) {
10686     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10687     D->setInvalidDecl();
10688     return;
10689   }
10690 
10691   VD->setCXXForRangeDecl(true);
10692 
10693   // for-range-declaration cannot be given a storage class specifier.
10694   int Error = -1;
10695   switch (VD->getStorageClass()) {
10696   case SC_None:
10697     break;
10698   case SC_Extern:
10699     Error = 0;
10700     break;
10701   case SC_Static:
10702     Error = 1;
10703     break;
10704   case SC_PrivateExtern:
10705     Error = 2;
10706     break;
10707   case SC_Auto:
10708     Error = 3;
10709     break;
10710   case SC_Register:
10711     Error = 4;
10712     break;
10713   }
10714   if (Error != -1) {
10715     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10716       << VD->getDeclName() << Error;
10717     D->setInvalidDecl();
10718   }
10719 }
10720 
10721 StmtResult
10722 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10723                                  IdentifierInfo *Ident,
10724                                  ParsedAttributes &Attrs,
10725                                  SourceLocation AttrEnd) {
10726   // C++1y [stmt.iter]p1:
10727   //   A range-based for statement of the form
10728   //      for ( for-range-identifier : for-range-initializer ) statement
10729   //   is equivalent to
10730   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10731   DeclSpec DS(Attrs.getPool().getFactory());
10732 
10733   const char *PrevSpec;
10734   unsigned DiagID;
10735   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10736                      getPrintingPolicy());
10737 
10738   Declarator D(DS, Declarator::ForContext);
10739   D.SetIdentifier(Ident, IdentLoc);
10740   D.takeAttributes(Attrs, AttrEnd);
10741 
10742   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10743   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10744                 EmptyAttrs, IdentLoc);
10745   Decl *Var = ActOnDeclarator(S, D);
10746   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10747   FinalizeDeclaration(Var);
10748   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10749                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10750 }
10751 
10752 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10753   if (var->isInvalidDecl()) return;
10754 
10755   if (getLangOpts().OpenCL) {
10756     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10757     // initialiser
10758     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10759         !var->hasInit()) {
10760       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10761           << 1 /*Init*/;
10762       var->setInvalidDecl();
10763       return;
10764     }
10765   }
10766 
10767   // In Objective-C, don't allow jumps past the implicit initialization of a
10768   // local retaining variable.
10769   if (getLangOpts().ObjC1 &&
10770       var->hasLocalStorage()) {
10771     switch (var->getType().getObjCLifetime()) {
10772     case Qualifiers::OCL_None:
10773     case Qualifiers::OCL_ExplicitNone:
10774     case Qualifiers::OCL_Autoreleasing:
10775       break;
10776 
10777     case Qualifiers::OCL_Weak:
10778     case Qualifiers::OCL_Strong:
10779       getCurFunction()->setHasBranchProtectedScope();
10780       break;
10781     }
10782   }
10783 
10784   // Warn about externally-visible variables being defined without a
10785   // prior declaration.  We only want to do this for global
10786   // declarations, but we also specifically need to avoid doing it for
10787   // class members because the linkage of an anonymous class can
10788   // change if it's later given a typedef name.
10789   if (var->isThisDeclarationADefinition() &&
10790       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10791       var->isExternallyVisible() && var->hasLinkage() &&
10792       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10793                                   var->getLocation())) {
10794     // Find a previous declaration that's not a definition.
10795     VarDecl *prev = var->getPreviousDecl();
10796     while (prev && prev->isThisDeclarationADefinition())
10797       prev = prev->getPreviousDecl();
10798 
10799     if (!prev)
10800       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10801   }
10802 
10803   // Cache the result of checking for constant initialization.
10804   Optional<bool> CacheHasConstInit;
10805   const Expr *CacheCulprit;
10806   auto checkConstInit = [&]() mutable {
10807     if (!CacheHasConstInit)
10808       CacheHasConstInit = var->getInit()->isConstantInitializer(
10809             Context, var->getType()->isReferenceType(), &CacheCulprit);
10810     return *CacheHasConstInit;
10811   };
10812 
10813   if (var->getTLSKind() == VarDecl::TLS_Static) {
10814     if (var->getType().isDestructedType()) {
10815       // GNU C++98 edits for __thread, [basic.start.term]p3:
10816       //   The type of an object with thread storage duration shall not
10817       //   have a non-trivial destructor.
10818       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10819       if (getLangOpts().CPlusPlus11)
10820         Diag(var->getLocation(), diag::note_use_thread_local);
10821     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10822       if (!checkConstInit()) {
10823         // GNU C++98 edits for __thread, [basic.start.init]p4:
10824         //   An object of thread storage duration shall not require dynamic
10825         //   initialization.
10826         // FIXME: Need strict checking here.
10827         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10828           << CacheCulprit->getSourceRange();
10829         if (getLangOpts().CPlusPlus11)
10830           Diag(var->getLocation(), diag::note_use_thread_local);
10831       }
10832     }
10833   }
10834 
10835   // Apply section attributes and pragmas to global variables.
10836   bool GlobalStorage = var->hasGlobalStorage();
10837   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10838       !inTemplateInstantiation()) {
10839     PragmaStack<StringLiteral *> *Stack = nullptr;
10840     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10841     if (var->getType().isConstQualified())
10842       Stack = &ConstSegStack;
10843     else if (!var->getInit()) {
10844       Stack = &BSSSegStack;
10845       SectionFlags |= ASTContext::PSF_Write;
10846     } else {
10847       Stack = &DataSegStack;
10848       SectionFlags |= ASTContext::PSF_Write;
10849     }
10850     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10851       var->addAttr(SectionAttr::CreateImplicit(
10852           Context, SectionAttr::Declspec_allocate,
10853           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10854     }
10855     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10856       if (UnifySection(SA->getName(), SectionFlags, var))
10857         var->dropAttr<SectionAttr>();
10858 
10859     // Apply the init_seg attribute if this has an initializer.  If the
10860     // initializer turns out to not be dynamic, we'll end up ignoring this
10861     // attribute.
10862     if (CurInitSeg && var->getInit())
10863       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10864                                                CurInitSegLoc));
10865   }
10866 
10867   // All the following checks are C++ only.
10868   if (!getLangOpts().CPlusPlus) {
10869       // If this variable must be emitted, add it as an initializer for the
10870       // current module.
10871      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10872        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10873      return;
10874   }
10875 
10876   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10877     CheckCompleteDecompositionDeclaration(DD);
10878 
10879   QualType type = var->getType();
10880   if (type->isDependentType()) return;
10881 
10882   // __block variables might require us to capture a copy-initializer.
10883   if (var->hasAttr<BlocksAttr>()) {
10884     // It's currently invalid to ever have a __block variable with an
10885     // array type; should we diagnose that here?
10886 
10887     // Regardless, we don't want to ignore array nesting when
10888     // constructing this copy.
10889     if (type->isStructureOrClassType()) {
10890       EnterExpressionEvaluationContext scope(
10891           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
10892       SourceLocation poi = var->getLocation();
10893       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10894       ExprResult result
10895         = PerformMoveOrCopyInitialization(
10896             InitializedEntity::InitializeBlock(poi, type, false),
10897             var, var->getType(), varRef, /*AllowNRVO=*/true);
10898       if (!result.isInvalid()) {
10899         result = MaybeCreateExprWithCleanups(result);
10900         Expr *init = result.getAs<Expr>();
10901         Context.setBlockVarCopyInits(var, init);
10902       }
10903     }
10904   }
10905 
10906   Expr *Init = var->getInit();
10907   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10908   QualType baseType = Context.getBaseElementType(type);
10909 
10910   if (!var->getDeclContext()->isDependentContext() &&
10911       Init && !Init->isValueDependent()) {
10912 
10913     if (var->isConstexpr()) {
10914       SmallVector<PartialDiagnosticAt, 8> Notes;
10915       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10916         SourceLocation DiagLoc = var->getLocation();
10917         // If the note doesn't add any useful information other than a source
10918         // location, fold it into the primary diagnostic.
10919         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10920               diag::note_invalid_subexpr_in_const_expr) {
10921           DiagLoc = Notes[0].first;
10922           Notes.clear();
10923         }
10924         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10925           << var << Init->getSourceRange();
10926         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10927           Diag(Notes[I].first, Notes[I].second);
10928       }
10929     } else if (var->isUsableInConstantExpressions(Context)) {
10930       // Check whether the initializer of a const variable of integral or
10931       // enumeration type is an ICE now, since we can't tell whether it was
10932       // initialized by a constant expression if we check later.
10933       var->checkInitIsICE();
10934     }
10935 
10936     // Don't emit further diagnostics about constexpr globals since they
10937     // were just diagnosed.
10938     if (!var->isConstexpr() && GlobalStorage &&
10939             var->hasAttr<RequireConstantInitAttr>()) {
10940       // FIXME: Need strict checking in C++03 here.
10941       bool DiagErr = getLangOpts().CPlusPlus11
10942           ? !var->checkInitIsICE() : !checkConstInit();
10943       if (DiagErr) {
10944         auto attr = var->getAttr<RequireConstantInitAttr>();
10945         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10946           << Init->getSourceRange();
10947         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10948           << attr->getRange();
10949       }
10950     }
10951     else if (!var->isConstexpr() && IsGlobal &&
10952              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10953                                     var->getLocation())) {
10954       // Warn about globals which don't have a constant initializer.  Don't
10955       // warn about globals with a non-trivial destructor because we already
10956       // warned about them.
10957       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10958       if (!(RD && !RD->hasTrivialDestructor())) {
10959         if (!checkConstInit())
10960           Diag(var->getLocation(), diag::warn_global_constructor)
10961             << Init->getSourceRange();
10962       }
10963     }
10964   }
10965 
10966   // Require the destructor.
10967   if (const RecordType *recordType = baseType->getAs<RecordType>())
10968     FinalizeVarWithDestructor(var, recordType);
10969 
10970   // If this variable must be emitted, add it as an initializer for the current
10971   // module.
10972   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10973     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10974 }
10975 
10976 /// \brief Determines if a variable's alignment is dependent.
10977 static bool hasDependentAlignment(VarDecl *VD) {
10978   if (VD->getType()->isDependentType())
10979     return true;
10980   for (auto *I : VD->specific_attrs<AlignedAttr>())
10981     if (I->isAlignmentDependent())
10982       return true;
10983   return false;
10984 }
10985 
10986 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10987 /// any semantic actions necessary after any initializer has been attached.
10988 void
10989 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10990   // Note that we are no longer parsing the initializer for this declaration.
10991   ParsingInitForAutoVars.erase(ThisDecl);
10992 
10993   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10994   if (!VD)
10995     return;
10996 
10997   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10998     for (auto *BD : DD->bindings()) {
10999       FinalizeDeclaration(BD);
11000     }
11001   }
11002 
11003   checkAttributesAfterMerging(*this, *VD);
11004 
11005   // Perform TLS alignment check here after attributes attached to the variable
11006   // which may affect the alignment have been processed. Only perform the check
11007   // if the target has a maximum TLS alignment (zero means no constraints).
11008   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11009     // Protect the check so that it's not performed on dependent types and
11010     // dependent alignments (we can't determine the alignment in that case).
11011     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11012         !VD->isInvalidDecl()) {
11013       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11014       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11015         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11016           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11017           << (unsigned)MaxAlignChars.getQuantity();
11018       }
11019     }
11020   }
11021 
11022   if (VD->isStaticLocal()) {
11023     if (FunctionDecl *FD =
11024             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11025       // Static locals inherit dll attributes from their function.
11026       if (Attr *A = getDLLAttr(FD)) {
11027         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11028         NewAttr->setInherited(true);
11029         VD->addAttr(NewAttr);
11030       }
11031       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11032       // function, only __shared__ variables may be declared with
11033       // static storage class.
11034       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11035           CUDADiagIfDeviceCode(VD->getLocation(),
11036                                diag::err_device_static_local_var)
11037               << CurrentCUDATarget())
11038         VD->setInvalidDecl();
11039     }
11040   }
11041 
11042   // Perform check for initializers of device-side global variables.
11043   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11044   // 7.5). We must also apply the same checks to all __shared__
11045   // variables whether they are local or not. CUDA also allows
11046   // constant initializers for __constant__ and __device__ variables.
11047   if (getLangOpts().CUDA) {
11048     const Expr *Init = VD->getInit();
11049     if (Init && VD->hasGlobalStorage()) {
11050       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11051           VD->hasAttr<CUDASharedAttr>()) {
11052         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11053         bool AllowedInit = false;
11054         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11055           AllowedInit =
11056               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11057         // We'll allow constant initializers even if it's a non-empty
11058         // constructor according to CUDA rules. This deviates from NVCC,
11059         // but allows us to handle things like constexpr constructors.
11060         if (!AllowedInit &&
11061             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11062           AllowedInit = VD->getInit()->isConstantInitializer(
11063               Context, VD->getType()->isReferenceType());
11064 
11065         // Also make sure that destructor, if there is one, is empty.
11066         if (AllowedInit)
11067           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11068             AllowedInit =
11069                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11070 
11071         if (!AllowedInit) {
11072           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11073                                       ? diag::err_shared_var_init
11074                                       : diag::err_dynamic_var_init)
11075               << Init->getSourceRange();
11076           VD->setInvalidDecl();
11077         }
11078       } else {
11079         // This is a host-side global variable.  Check that the initializer is
11080         // callable from the host side.
11081         const FunctionDecl *InitFn = nullptr;
11082         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11083           InitFn = CE->getConstructor();
11084         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11085           InitFn = CE->getDirectCallee();
11086         }
11087         if (InitFn) {
11088           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11089           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11090             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11091                 << InitFnTarget << InitFn;
11092             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11093             VD->setInvalidDecl();
11094           }
11095         }
11096       }
11097     }
11098   }
11099 
11100   // Grab the dllimport or dllexport attribute off of the VarDecl.
11101   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11102 
11103   // Imported static data members cannot be defined out-of-line.
11104   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11105     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11106         VD->isThisDeclarationADefinition()) {
11107       // We allow definitions of dllimport class template static data members
11108       // with a warning.
11109       CXXRecordDecl *Context =
11110         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11111       bool IsClassTemplateMember =
11112           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11113           Context->getDescribedClassTemplate();
11114 
11115       Diag(VD->getLocation(),
11116            IsClassTemplateMember
11117                ? diag::warn_attribute_dllimport_static_field_definition
11118                : diag::err_attribute_dllimport_static_field_definition);
11119       Diag(IA->getLocation(), diag::note_attribute);
11120       if (!IsClassTemplateMember)
11121         VD->setInvalidDecl();
11122     }
11123   }
11124 
11125   // dllimport/dllexport variables cannot be thread local, their TLS index
11126   // isn't exported with the variable.
11127   if (DLLAttr && VD->getTLSKind()) {
11128     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11129     if (F && getDLLAttr(F)) {
11130       assert(VD->isStaticLocal());
11131       // But if this is a static local in a dlimport/dllexport function, the
11132       // function will never be inlined, which means the var would never be
11133       // imported, so having it marked import/export is safe.
11134     } else {
11135       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11136                                                                     << DLLAttr;
11137       VD->setInvalidDecl();
11138     }
11139   }
11140 
11141   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11142     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11143       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11144       VD->dropAttr<UsedAttr>();
11145     }
11146   }
11147 
11148   const DeclContext *DC = VD->getDeclContext();
11149   // If there's a #pragma GCC visibility in scope, and this isn't a class
11150   // member, set the visibility of this variable.
11151   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11152     AddPushedVisibilityAttribute(VD);
11153 
11154   // FIXME: Warn on unused templates.
11155   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11156       !isa<VarTemplatePartialSpecializationDecl>(VD))
11157     MarkUnusedFileScopedDecl(VD);
11158 
11159   // Now we have parsed the initializer and can update the table of magic
11160   // tag values.
11161   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11162       !VD->getType()->isIntegralOrEnumerationType())
11163     return;
11164 
11165   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11166     const Expr *MagicValueExpr = VD->getInit();
11167     if (!MagicValueExpr) {
11168       continue;
11169     }
11170     llvm::APSInt MagicValueInt;
11171     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11172       Diag(I->getRange().getBegin(),
11173            diag::err_type_tag_for_datatype_not_ice)
11174         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11175       continue;
11176     }
11177     if (MagicValueInt.getActiveBits() > 64) {
11178       Diag(I->getRange().getBegin(),
11179            diag::err_type_tag_for_datatype_too_large)
11180         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11181       continue;
11182     }
11183     uint64_t MagicValue = MagicValueInt.getZExtValue();
11184     RegisterTypeTagForDatatype(I->getArgumentKind(),
11185                                MagicValue,
11186                                I->getMatchingCType(),
11187                                I->getLayoutCompatible(),
11188                                I->getMustBeNull());
11189   }
11190 }
11191 
11192 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11193   auto *VD = dyn_cast<VarDecl>(DD);
11194   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11195 }
11196 
11197 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11198                                                    ArrayRef<Decl *> Group) {
11199   SmallVector<Decl*, 8> Decls;
11200 
11201   if (DS.isTypeSpecOwned())
11202     Decls.push_back(DS.getRepAsDecl());
11203 
11204   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11205   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11206   bool DiagnosedMultipleDecomps = false;
11207   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11208   bool DiagnosedNonDeducedAuto = false;
11209 
11210   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11211     if (Decl *D = Group[i]) {
11212       // For declarators, there are some additional syntactic-ish checks we need
11213       // to perform.
11214       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11215         if (!FirstDeclaratorInGroup)
11216           FirstDeclaratorInGroup = DD;
11217         if (!FirstDecompDeclaratorInGroup)
11218           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11219         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11220             !hasDeducedAuto(DD))
11221           FirstNonDeducedAutoInGroup = DD;
11222 
11223         if (FirstDeclaratorInGroup != DD) {
11224           // A decomposition declaration cannot be combined with any other
11225           // declaration in the same group.
11226           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11227             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11228                  diag::err_decomp_decl_not_alone)
11229                 << FirstDeclaratorInGroup->getSourceRange()
11230                 << DD->getSourceRange();
11231             DiagnosedMultipleDecomps = true;
11232           }
11233 
11234           // A declarator that uses 'auto' in any way other than to declare a
11235           // variable with a deduced type cannot be combined with any other
11236           // declarator in the same group.
11237           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11238             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11239                  diag::err_auto_non_deduced_not_alone)
11240                 << FirstNonDeducedAutoInGroup->getType()
11241                        ->hasAutoForTrailingReturnType()
11242                 << FirstDeclaratorInGroup->getSourceRange()
11243                 << DD->getSourceRange();
11244             DiagnosedNonDeducedAuto = true;
11245           }
11246         }
11247       }
11248 
11249       Decls.push_back(D);
11250     }
11251   }
11252 
11253   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11254     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11255       handleTagNumbering(Tag, S);
11256       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11257           getLangOpts().CPlusPlus)
11258         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11259     }
11260   }
11261 
11262   return BuildDeclaratorGroup(Decls);
11263 }
11264 
11265 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11266 /// group, performing any necessary semantic checking.
11267 Sema::DeclGroupPtrTy
11268 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11269   // C++14 [dcl.spec.auto]p7: (DR1347)
11270   //   If the type that replaces the placeholder type is not the same in each
11271   //   deduction, the program is ill-formed.
11272   if (Group.size() > 1) {
11273     QualType Deduced;
11274     VarDecl *DeducedDecl = nullptr;
11275     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11276       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11277       if (!D || D->isInvalidDecl())
11278         break;
11279       DeducedType *DT = D->getType()->getContainedDeducedType();
11280       if (!DT || DT->getDeducedType().isNull())
11281         continue;
11282       if (Deduced.isNull()) {
11283         Deduced = DT->getDeducedType();
11284         DeducedDecl = D;
11285       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11286         auto *AT = dyn_cast<AutoType>(DT);
11287         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11288              diag::err_auto_different_deductions)
11289           << (AT ? (unsigned)AT->getKeyword() : 3)
11290           << Deduced << DeducedDecl->getDeclName()
11291           << DT->getDeducedType() << D->getDeclName()
11292           << DeducedDecl->getInit()->getSourceRange()
11293           << D->getInit()->getSourceRange();
11294         D->setInvalidDecl();
11295         break;
11296       }
11297     }
11298   }
11299 
11300   ActOnDocumentableDecls(Group);
11301 
11302   return DeclGroupPtrTy::make(
11303       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11304 }
11305 
11306 void Sema::ActOnDocumentableDecl(Decl *D) {
11307   ActOnDocumentableDecls(D);
11308 }
11309 
11310 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11311   // Don't parse the comment if Doxygen diagnostics are ignored.
11312   if (Group.empty() || !Group[0])
11313     return;
11314 
11315   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11316                       Group[0]->getLocation()) &&
11317       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11318                       Group[0]->getLocation()))
11319     return;
11320 
11321   if (Group.size() >= 2) {
11322     // This is a decl group.  Normally it will contain only declarations
11323     // produced from declarator list.  But in case we have any definitions or
11324     // additional declaration references:
11325     //   'typedef struct S {} S;'
11326     //   'typedef struct S *S;'
11327     //   'struct S *pS;'
11328     // FinalizeDeclaratorGroup adds these as separate declarations.
11329     Decl *MaybeTagDecl = Group[0];
11330     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11331       Group = Group.slice(1);
11332     }
11333   }
11334 
11335   // See if there are any new comments that are not attached to a decl.
11336   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11337   if (!Comments.empty() &&
11338       !Comments.back()->isAttached()) {
11339     // There is at least one comment that not attached to a decl.
11340     // Maybe it should be attached to one of these decls?
11341     //
11342     // Note that this way we pick up not only comments that precede the
11343     // declaration, but also comments that *follow* the declaration -- thanks to
11344     // the lookahead in the lexer: we've consumed the semicolon and looked
11345     // ahead through comments.
11346     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11347       Context.getCommentForDecl(Group[i], &PP);
11348   }
11349 }
11350 
11351 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11352 /// to introduce parameters into function prototype scope.
11353 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11354   const DeclSpec &DS = D.getDeclSpec();
11355 
11356   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11357 
11358   // C++03 [dcl.stc]p2 also permits 'auto'.
11359   StorageClass SC = SC_None;
11360   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11361     SC = SC_Register;
11362   } else if (getLangOpts().CPlusPlus &&
11363              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11364     SC = SC_Auto;
11365   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11366     Diag(DS.getStorageClassSpecLoc(),
11367          diag::err_invalid_storage_class_in_func_decl);
11368     D.getMutableDeclSpec().ClearStorageClassSpecs();
11369   }
11370 
11371   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11372     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11373       << DeclSpec::getSpecifierName(TSCS);
11374   if (DS.isInlineSpecified())
11375     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11376         << getLangOpts().CPlusPlus1z;
11377   if (DS.isConstexprSpecified())
11378     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11379       << 0;
11380   if (DS.isConceptSpecified())
11381     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11382 
11383   DiagnoseFunctionSpecifiers(DS);
11384 
11385   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11386   QualType parmDeclType = TInfo->getType();
11387 
11388   if (getLangOpts().CPlusPlus) {
11389     // Check that there are no default arguments inside the type of this
11390     // parameter.
11391     CheckExtraCXXDefaultArguments(D);
11392 
11393     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11394     if (D.getCXXScopeSpec().isSet()) {
11395       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11396         << D.getCXXScopeSpec().getRange();
11397       D.getCXXScopeSpec().clear();
11398     }
11399   }
11400 
11401   // Ensure we have a valid name
11402   IdentifierInfo *II = nullptr;
11403   if (D.hasName()) {
11404     II = D.getIdentifier();
11405     if (!II) {
11406       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11407         << GetNameForDeclarator(D).getName();
11408       D.setInvalidType(true);
11409     }
11410   }
11411 
11412   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11413   if (II) {
11414     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11415                    ForRedeclaration);
11416     LookupName(R, S);
11417     if (R.isSingleResult()) {
11418       NamedDecl *PrevDecl = R.getFoundDecl();
11419       if (PrevDecl->isTemplateParameter()) {
11420         // Maybe we will complain about the shadowed template parameter.
11421         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11422         // Just pretend that we didn't see the previous declaration.
11423         PrevDecl = nullptr;
11424       } else if (S->isDeclScope(PrevDecl)) {
11425         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11426         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11427 
11428         // Recover by removing the name
11429         II = nullptr;
11430         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11431         D.setInvalidType(true);
11432       }
11433     }
11434   }
11435 
11436   // Temporarily put parameter variables in the translation unit, not
11437   // the enclosing context.  This prevents them from accidentally
11438   // looking like class members in C++.
11439   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11440                                     D.getLocStart(),
11441                                     D.getIdentifierLoc(), II,
11442                                     parmDeclType, TInfo,
11443                                     SC);
11444 
11445   if (D.isInvalidType())
11446     New->setInvalidDecl();
11447 
11448   assert(S->isFunctionPrototypeScope());
11449   assert(S->getFunctionPrototypeDepth() >= 1);
11450   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11451                     S->getNextFunctionPrototypeIndex());
11452 
11453   // Add the parameter declaration into this scope.
11454   S->AddDecl(New);
11455   if (II)
11456     IdResolver.AddDecl(New);
11457 
11458   ProcessDeclAttributes(S, New, D);
11459 
11460   if (D.getDeclSpec().isModulePrivateSpecified())
11461     Diag(New->getLocation(), diag::err_module_private_local)
11462       << 1 << New->getDeclName()
11463       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11464       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11465 
11466   if (New->hasAttr<BlocksAttr>()) {
11467     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11468   }
11469   return New;
11470 }
11471 
11472 /// \brief Synthesizes a variable for a parameter arising from a
11473 /// typedef.
11474 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11475                                               SourceLocation Loc,
11476                                               QualType T) {
11477   /* FIXME: setting StartLoc == Loc.
11478      Would it be worth to modify callers so as to provide proper source
11479      location for the unnamed parameters, embedding the parameter's type? */
11480   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11481                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11482                                            SC_None, nullptr);
11483   Param->setImplicit();
11484   return Param;
11485 }
11486 
11487 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11488   // Don't diagnose unused-parameter errors in template instantiations; we
11489   // will already have done so in the template itself.
11490   if (inTemplateInstantiation())
11491     return;
11492 
11493   for (const ParmVarDecl *Parameter : Parameters) {
11494     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11495         !Parameter->hasAttr<UnusedAttr>()) {
11496       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11497         << Parameter->getDeclName();
11498     }
11499   }
11500 }
11501 
11502 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11503     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11504   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11505     return;
11506 
11507   // Warn if the return value is pass-by-value and larger than the specified
11508   // threshold.
11509   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11510     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11511     if (Size > LangOpts.NumLargeByValueCopy)
11512       Diag(D->getLocation(), diag::warn_return_value_size)
11513           << D->getDeclName() << Size;
11514   }
11515 
11516   // Warn if any parameter is pass-by-value and larger than the specified
11517   // threshold.
11518   for (const ParmVarDecl *Parameter : Parameters) {
11519     QualType T = Parameter->getType();
11520     if (T->isDependentType() || !T.isPODType(Context))
11521       continue;
11522     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11523     if (Size > LangOpts.NumLargeByValueCopy)
11524       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11525           << Parameter->getDeclName() << Size;
11526   }
11527 }
11528 
11529 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11530                                   SourceLocation NameLoc, IdentifierInfo *Name,
11531                                   QualType T, TypeSourceInfo *TSInfo,
11532                                   StorageClass SC) {
11533   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11534   if (getLangOpts().ObjCAutoRefCount &&
11535       T.getObjCLifetime() == Qualifiers::OCL_None &&
11536       T->isObjCLifetimeType()) {
11537 
11538     Qualifiers::ObjCLifetime lifetime;
11539 
11540     // Special cases for arrays:
11541     //   - if it's const, use __unsafe_unretained
11542     //   - otherwise, it's an error
11543     if (T->isArrayType()) {
11544       if (!T.isConstQualified()) {
11545         DelayedDiagnostics.add(
11546             sema::DelayedDiagnostic::makeForbiddenType(
11547             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11548       }
11549       lifetime = Qualifiers::OCL_ExplicitNone;
11550     } else {
11551       lifetime = T->getObjCARCImplicitLifetime();
11552     }
11553     T = Context.getLifetimeQualifiedType(T, lifetime);
11554   }
11555 
11556   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11557                                          Context.getAdjustedParameterType(T),
11558                                          TSInfo, SC, nullptr);
11559 
11560   // Parameters can not be abstract class types.
11561   // For record types, this is done by the AbstractClassUsageDiagnoser once
11562   // the class has been completely parsed.
11563   if (!CurContext->isRecord() &&
11564       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11565                              AbstractParamType))
11566     New->setInvalidDecl();
11567 
11568   // Parameter declarators cannot be interface types. All ObjC objects are
11569   // passed by reference.
11570   if (T->isObjCObjectType()) {
11571     SourceLocation TypeEndLoc =
11572         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11573     Diag(NameLoc,
11574          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11575       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11576     T = Context.getObjCObjectPointerType(T);
11577     New->setType(T);
11578   }
11579 
11580   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11581   // duration shall not be qualified by an address-space qualifier."
11582   // Since all parameters have automatic store duration, they can not have
11583   // an address space.
11584   if (T.getAddressSpace() != 0) {
11585     // OpenCL allows function arguments declared to be an array of a type
11586     // to be qualified with an address space.
11587     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11588       Diag(NameLoc, diag::err_arg_with_address_space);
11589       New->setInvalidDecl();
11590     }
11591   }
11592 
11593   return New;
11594 }
11595 
11596 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11597                                            SourceLocation LocAfterDecls) {
11598   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11599 
11600   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11601   // for a K&R function.
11602   if (!FTI.hasPrototype) {
11603     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11604       --i;
11605       if (FTI.Params[i].Param == nullptr) {
11606         SmallString<256> Code;
11607         llvm::raw_svector_ostream(Code)
11608             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11609         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11610             << FTI.Params[i].Ident
11611             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11612 
11613         // Implicitly declare the argument as type 'int' for lack of a better
11614         // type.
11615         AttributeFactory attrs;
11616         DeclSpec DS(attrs);
11617         const char* PrevSpec; // unused
11618         unsigned DiagID; // unused
11619         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11620                            DiagID, Context.getPrintingPolicy());
11621         // Use the identifier location for the type source range.
11622         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11623         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11624         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11625         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11626         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11627       }
11628     }
11629   }
11630 }
11631 
11632 Decl *
11633 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11634                               MultiTemplateParamsArg TemplateParameterLists,
11635                               SkipBodyInfo *SkipBody) {
11636   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11637   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11638   Scope *ParentScope = FnBodyScope->getParent();
11639 
11640   D.setFunctionDefinitionKind(FDK_Definition);
11641   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11642   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11643 }
11644 
11645 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11646   Consumer.HandleInlineFunctionDefinition(D);
11647 }
11648 
11649 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11650                              const FunctionDecl*& PossibleZeroParamPrototype) {
11651   // Don't warn about invalid declarations.
11652   if (FD->isInvalidDecl())
11653     return false;
11654 
11655   // Or declarations that aren't global.
11656   if (!FD->isGlobal())
11657     return false;
11658 
11659   // Don't warn about C++ member functions.
11660   if (isa<CXXMethodDecl>(FD))
11661     return false;
11662 
11663   // Don't warn about 'main'.
11664   if (FD->isMain())
11665     return false;
11666 
11667   // Don't warn about inline functions.
11668   if (FD->isInlined())
11669     return false;
11670 
11671   // Don't warn about function templates.
11672   if (FD->getDescribedFunctionTemplate())
11673     return false;
11674 
11675   // Don't warn about function template specializations.
11676   if (FD->isFunctionTemplateSpecialization())
11677     return false;
11678 
11679   // Don't warn for OpenCL kernels.
11680   if (FD->hasAttr<OpenCLKernelAttr>())
11681     return false;
11682 
11683   // Don't warn on explicitly deleted functions.
11684   if (FD->isDeleted())
11685     return false;
11686 
11687   bool MissingPrototype = true;
11688   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11689        Prev; Prev = Prev->getPreviousDecl()) {
11690     // Ignore any declarations that occur in function or method
11691     // scope, because they aren't visible from the header.
11692     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11693       continue;
11694 
11695     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11696     if (FD->getNumParams() == 0)
11697       PossibleZeroParamPrototype = Prev;
11698     break;
11699   }
11700 
11701   return MissingPrototype;
11702 }
11703 
11704 void
11705 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11706                                    const FunctionDecl *EffectiveDefinition,
11707                                    SkipBodyInfo *SkipBody) {
11708   const FunctionDecl *Definition = EffectiveDefinition;
11709   if (!Definition)
11710     if (!FD->isDefined(Definition))
11711       return;
11712 
11713   if (canRedefineFunction(Definition, getLangOpts()))
11714     return;
11715 
11716   // If we don't have a visible definition of the function, and it's inline or
11717   // a template, skip the new definition.
11718   if (SkipBody && !hasVisibleDefinition(Definition) &&
11719       (Definition->getFormalLinkage() == InternalLinkage ||
11720        Definition->isInlined() ||
11721        Definition->getDescribedFunctionTemplate() ||
11722        Definition->getNumTemplateParameterLists())) {
11723     SkipBody->ShouldSkip = true;
11724     if (auto *TD = Definition->getDescribedFunctionTemplate())
11725       makeMergedDefinitionVisible(TD, FD->getLocation());
11726     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11727                                 FD->getLocation());
11728     return;
11729   }
11730 
11731   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11732       Definition->getStorageClass() == SC_Extern)
11733     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11734         << FD->getDeclName() << getLangOpts().CPlusPlus;
11735   else
11736     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11737 
11738   Diag(Definition->getLocation(), diag::note_previous_definition);
11739   FD->setInvalidDecl();
11740 }
11741 
11742 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11743                                    Sema &S) {
11744   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11745 
11746   LambdaScopeInfo *LSI = S.PushLambdaScope();
11747   LSI->CallOperator = CallOperator;
11748   LSI->Lambda = LambdaClass;
11749   LSI->ReturnType = CallOperator->getReturnType();
11750   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11751 
11752   if (LCD == LCD_None)
11753     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11754   else if (LCD == LCD_ByCopy)
11755     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11756   else if (LCD == LCD_ByRef)
11757     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11758   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11759 
11760   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11761   LSI->Mutable = !CallOperator->isConst();
11762 
11763   // Add the captures to the LSI so they can be noted as already
11764   // captured within tryCaptureVar.
11765   auto I = LambdaClass->field_begin();
11766   for (const auto &C : LambdaClass->captures()) {
11767     if (C.capturesVariable()) {
11768       VarDecl *VD = C.getCapturedVar();
11769       if (VD->isInitCapture())
11770         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11771       QualType CaptureType = VD->getType();
11772       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11773       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11774           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11775           /*EllipsisLoc*/C.isPackExpansion()
11776                          ? C.getEllipsisLoc() : SourceLocation(),
11777           CaptureType, /*Expr*/ nullptr);
11778 
11779     } else if (C.capturesThis()) {
11780       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11781                               /*Expr*/ nullptr,
11782                               C.getCaptureKind() == LCK_StarThis);
11783     } else {
11784       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11785     }
11786     ++I;
11787   }
11788 }
11789 
11790 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11791                                     SkipBodyInfo *SkipBody) {
11792   if (!D)
11793     return D;
11794   FunctionDecl *FD = nullptr;
11795 
11796   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11797     FD = FunTmpl->getTemplatedDecl();
11798   else
11799     FD = cast<FunctionDecl>(D);
11800 
11801   // Check for defining attributes before the check for redefinition.
11802   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11803     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11804     FD->dropAttr<AliasAttr>();
11805     FD->setInvalidDecl();
11806   }
11807   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11808     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11809     FD->dropAttr<IFuncAttr>();
11810     FD->setInvalidDecl();
11811   }
11812 
11813   // See if this is a redefinition.
11814   if (!FD->isLateTemplateParsed()) {
11815     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11816 
11817     // If we're skipping the body, we're done. Don't enter the scope.
11818     if (SkipBody && SkipBody->ShouldSkip)
11819       return D;
11820   }
11821 
11822   // Mark this function as "will have a body eventually".  This lets users to
11823   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11824   // this function.
11825   FD->setWillHaveBody();
11826 
11827   // If we are instantiating a generic lambda call operator, push
11828   // a LambdaScopeInfo onto the function stack.  But use the information
11829   // that's already been calculated (ActOnLambdaExpr) to prime the current
11830   // LambdaScopeInfo.
11831   // When the template operator is being specialized, the LambdaScopeInfo,
11832   // has to be properly restored so that tryCaptureVariable doesn't try
11833   // and capture any new variables. In addition when calculating potential
11834   // captures during transformation of nested lambdas, it is necessary to
11835   // have the LSI properly restored.
11836   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11837     assert(inTemplateInstantiation() &&
11838            "There should be an active template instantiation on the stack "
11839            "when instantiating a generic lambda!");
11840     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11841   } else {
11842     // Enter a new function scope
11843     PushFunctionScope();
11844   }
11845 
11846   // Builtin functions cannot be defined.
11847   if (unsigned BuiltinID = FD->getBuiltinID()) {
11848     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11849         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11850       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11851       FD->setInvalidDecl();
11852     }
11853   }
11854 
11855   // The return type of a function definition must be complete
11856   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11857   QualType ResultType = FD->getReturnType();
11858   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11859       !FD->isInvalidDecl() &&
11860       RequireCompleteType(FD->getLocation(), ResultType,
11861                           diag::err_func_def_incomplete_result))
11862     FD->setInvalidDecl();
11863 
11864   if (FnBodyScope)
11865     PushDeclContext(FnBodyScope, FD);
11866 
11867   // Check the validity of our function parameters
11868   CheckParmsForFunctionDef(FD->parameters(),
11869                            /*CheckParameterNames=*/true);
11870 
11871   // Add non-parameter declarations already in the function to the current
11872   // scope.
11873   if (FnBodyScope) {
11874     for (Decl *NPD : FD->decls()) {
11875       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11876       if (!NonParmDecl)
11877         continue;
11878       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11879              "parameters should not be in newly created FD yet");
11880 
11881       // If the decl has a name, make it accessible in the current scope.
11882       if (NonParmDecl->getDeclName())
11883         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11884 
11885       // Similarly, dive into enums and fish their constants out, making them
11886       // accessible in this scope.
11887       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11888         for (auto *EI : ED->enumerators())
11889           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11890       }
11891     }
11892   }
11893 
11894   // Introduce our parameters into the function scope
11895   for (auto Param : FD->parameters()) {
11896     Param->setOwningFunction(FD);
11897 
11898     // If this has an identifier, add it to the scope stack.
11899     if (Param->getIdentifier() && FnBodyScope) {
11900       CheckShadow(FnBodyScope, Param);
11901 
11902       PushOnScopeChains(Param, FnBodyScope);
11903     }
11904   }
11905 
11906   // Ensure that the function's exception specification is instantiated.
11907   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11908     ResolveExceptionSpec(D->getLocation(), FPT);
11909 
11910   // dllimport cannot be applied to non-inline function definitions.
11911   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11912       !FD->isTemplateInstantiation()) {
11913     assert(!FD->hasAttr<DLLExportAttr>());
11914     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11915     FD->setInvalidDecl();
11916     return D;
11917   }
11918   // We want to attach documentation to original Decl (which might be
11919   // a function template).
11920   ActOnDocumentableDecl(D);
11921   if (getCurLexicalContext()->isObjCContainer() &&
11922       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11923       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11924     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11925 
11926   return D;
11927 }
11928 
11929 /// \brief Given the set of return statements within a function body,
11930 /// compute the variables that are subject to the named return value
11931 /// optimization.
11932 ///
11933 /// Each of the variables that is subject to the named return value
11934 /// optimization will be marked as NRVO variables in the AST, and any
11935 /// return statement that has a marked NRVO variable as its NRVO candidate can
11936 /// use the named return value optimization.
11937 ///
11938 /// This function applies a very simplistic algorithm for NRVO: if every return
11939 /// statement in the scope of a variable has the same NRVO candidate, that
11940 /// candidate is an NRVO variable.
11941 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11942   ReturnStmt **Returns = Scope->Returns.data();
11943 
11944   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11945     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11946       if (!NRVOCandidate->isNRVOVariable())
11947         Returns[I]->setNRVOCandidate(nullptr);
11948     }
11949   }
11950 }
11951 
11952 bool Sema::canDelayFunctionBody(const Declarator &D) {
11953   // We can't delay parsing the body of a constexpr function template (yet).
11954   if (D.getDeclSpec().isConstexprSpecified())
11955     return false;
11956 
11957   // We can't delay parsing the body of a function template with a deduced
11958   // return type (yet).
11959   if (D.getDeclSpec().hasAutoTypeSpec()) {
11960     // If the placeholder introduces a non-deduced trailing return type,
11961     // we can still delay parsing it.
11962     if (D.getNumTypeObjects()) {
11963       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11964       if (Outer.Kind == DeclaratorChunk::Function &&
11965           Outer.Fun.hasTrailingReturnType()) {
11966         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11967         return Ty.isNull() || !Ty->isUndeducedType();
11968       }
11969     }
11970     return false;
11971   }
11972 
11973   return true;
11974 }
11975 
11976 bool Sema::canSkipFunctionBody(Decl *D) {
11977   // We cannot skip the body of a function (or function template) which is
11978   // constexpr, since we may need to evaluate its body in order to parse the
11979   // rest of the file.
11980   // We cannot skip the body of a function with an undeduced return type,
11981   // because any callers of that function need to know the type.
11982   if (const FunctionDecl *FD = D->getAsFunction())
11983     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11984       return false;
11985   return Consumer.shouldSkipFunctionBody(D);
11986 }
11987 
11988 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11989   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11990     FD->setHasSkippedBody();
11991   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11992     MD->setHasSkippedBody();
11993   return Decl;
11994 }
11995 
11996 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11997   return ActOnFinishFunctionBody(D, BodyArg, false);
11998 }
11999 
12000 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12001                                     bool IsInstantiation) {
12002   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12003 
12004   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12005   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12006 
12007   if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise)
12008     CheckCompletedCoroutineBody(FD, Body);
12009 
12010   if (FD) {
12011     FD->setBody(Body);
12012 
12013     if (getLangOpts().CPlusPlus14) {
12014       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12015           FD->getReturnType()->isUndeducedType()) {
12016         // If the function has a deduced result type but contains no 'return'
12017         // statements, the result type as written must be exactly 'auto', and
12018         // the deduced result type is 'void'.
12019         if (!FD->getReturnType()->getAs<AutoType>()) {
12020           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12021               << FD->getReturnType();
12022           FD->setInvalidDecl();
12023         } else {
12024           // Substitute 'void' for the 'auto' in the type.
12025           TypeLoc ResultType = getReturnTypeLoc(FD);
12026           Context.adjustDeducedFunctionResultType(
12027               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12028         }
12029       }
12030     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12031       // In C++11, we don't use 'auto' deduction rules for lambda call
12032       // operators because we don't support return type deduction.
12033       auto *LSI = getCurLambda();
12034       if (LSI->HasImplicitReturnType) {
12035         deduceClosureReturnType(*LSI);
12036 
12037         // C++11 [expr.prim.lambda]p4:
12038         //   [...] if there are no return statements in the compound-statement
12039         //   [the deduced type is] the type void
12040         QualType RetType =
12041             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12042 
12043         // Update the return type to the deduced type.
12044         const FunctionProtoType *Proto =
12045             FD->getType()->getAs<FunctionProtoType>();
12046         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12047                                             Proto->getExtProtoInfo()));
12048       }
12049     }
12050 
12051     // The only way to be included in UndefinedButUsed is if there is an
12052     // ODR use before the definition. Avoid the expensive map lookup if this
12053     // is the first declaration.
12054     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12055       if (!FD->isExternallyVisible())
12056         UndefinedButUsed.erase(FD);
12057       else if (FD->isInlined() &&
12058                !LangOpts.GNUInline &&
12059                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12060         UndefinedButUsed.erase(FD);
12061     }
12062 
12063     // If the function implicitly returns zero (like 'main') or is naked,
12064     // don't complain about missing return statements.
12065     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12066       WP.disableCheckFallThrough();
12067 
12068     // MSVC permits the use of pure specifier (=0) on function definition,
12069     // defined at class scope, warn about this non-standard construct.
12070     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12071       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12072 
12073     if (!FD->isInvalidDecl()) {
12074       // Don't diagnose unused parameters of defaulted or deleted functions.
12075       if (!FD->isDeleted() && !FD->isDefaulted())
12076         DiagnoseUnusedParameters(FD->parameters());
12077       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12078                                              FD->getReturnType(), FD);
12079 
12080       // If this is a structor, we need a vtable.
12081       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12082         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12083       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12084         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12085 
12086       // Try to apply the named return value optimization. We have to check
12087       // if we can do this here because lambdas keep return statements around
12088       // to deduce an implicit return type.
12089       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12090           !FD->isDependentContext())
12091         computeNRVO(Body, getCurFunction());
12092     }
12093 
12094     // GNU warning -Wmissing-prototypes:
12095     //   Warn if a global function is defined without a previous
12096     //   prototype declaration. This warning is issued even if the
12097     //   definition itself provides a prototype. The aim is to detect
12098     //   global functions that fail to be declared in header files.
12099     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12100     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12101       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12102 
12103       if (PossibleZeroParamPrototype) {
12104         // We found a declaration that is not a prototype,
12105         // but that could be a zero-parameter prototype
12106         if (TypeSourceInfo *TI =
12107                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12108           TypeLoc TL = TI->getTypeLoc();
12109           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12110             Diag(PossibleZeroParamPrototype->getLocation(),
12111                  diag::note_declaration_not_a_prototype)
12112                 << PossibleZeroParamPrototype
12113                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12114         }
12115       }
12116 
12117       // GNU warning -Wstrict-prototypes
12118       //   Warn if K&R function is defined without a previous declaration.
12119       //   This warning is issued only if the definition itself does not provide
12120       //   a prototype. Only K&R definitions do not provide a prototype.
12121       //   An empty list in a function declarator that is part of a definition
12122       //   of that function specifies that the function has no parameters
12123       //   (C99 6.7.5.3p14)
12124       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12125           !LangOpts.CPlusPlus) {
12126         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12127         TypeLoc TL = TI->getTypeLoc();
12128         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12129         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12130       }
12131     }
12132 
12133     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12134       const CXXMethodDecl *KeyFunction;
12135       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12136           MD->isVirtual() &&
12137           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12138           MD == KeyFunction->getCanonicalDecl()) {
12139         // Update the key-function state if necessary for this ABI.
12140         if (FD->isInlined() &&
12141             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12142           Context.setNonKeyFunction(MD);
12143 
12144           // If the newly-chosen key function is already defined, then we
12145           // need to mark the vtable as used retroactively.
12146           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12147           const FunctionDecl *Definition;
12148           if (KeyFunction && KeyFunction->isDefined(Definition))
12149             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12150         } else {
12151           // We just defined they key function; mark the vtable as used.
12152           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12153         }
12154       }
12155     }
12156 
12157     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12158            "Function parsing confused");
12159   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12160     assert(MD == getCurMethodDecl() && "Method parsing confused");
12161     MD->setBody(Body);
12162     if (!MD->isInvalidDecl()) {
12163       DiagnoseUnusedParameters(MD->parameters());
12164       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12165                                              MD->getReturnType(), MD);
12166 
12167       if (Body)
12168         computeNRVO(Body, getCurFunction());
12169     }
12170     if (getCurFunction()->ObjCShouldCallSuper) {
12171       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12172         << MD->getSelector().getAsString();
12173       getCurFunction()->ObjCShouldCallSuper = false;
12174     }
12175     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12176       const ObjCMethodDecl *InitMethod = nullptr;
12177       bool isDesignated =
12178           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12179       assert(isDesignated && InitMethod);
12180       (void)isDesignated;
12181 
12182       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12183         auto IFace = MD->getClassInterface();
12184         if (!IFace)
12185           return false;
12186         auto SuperD = IFace->getSuperClass();
12187         if (!SuperD)
12188           return false;
12189         return SuperD->getIdentifier() ==
12190             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12191       };
12192       // Don't issue this warning for unavailable inits or direct subclasses
12193       // of NSObject.
12194       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12195         Diag(MD->getLocation(),
12196              diag::warn_objc_designated_init_missing_super_call);
12197         Diag(InitMethod->getLocation(),
12198              diag::note_objc_designated_init_marked_here);
12199       }
12200       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12201     }
12202     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12203       // Don't issue this warning for unavaialable inits.
12204       if (!MD->isUnavailable())
12205         Diag(MD->getLocation(),
12206              diag::warn_objc_secondary_init_missing_init_call);
12207       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12208     }
12209   } else {
12210     return nullptr;
12211   }
12212 
12213   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12214     DiagnoseUnguardedAvailabilityViolations(dcl);
12215 
12216   assert(!getCurFunction()->ObjCShouldCallSuper &&
12217          "This should only be set for ObjC methods, which should have been "
12218          "handled in the block above.");
12219 
12220   // Verify and clean out per-function state.
12221   if (Body && (!FD || !FD->isDefaulted())) {
12222     // C++ constructors that have function-try-blocks can't have return
12223     // statements in the handlers of that block. (C++ [except.handle]p14)
12224     // Verify this.
12225     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12226       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12227 
12228     // Verify that gotos and switch cases don't jump into scopes illegally.
12229     if (getCurFunction()->NeedsScopeChecking() &&
12230         !PP.isCodeCompletionEnabled())
12231       DiagnoseInvalidJumps(Body);
12232 
12233     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12234       if (!Destructor->getParent()->isDependentType())
12235         CheckDestructor(Destructor);
12236 
12237       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12238                                              Destructor->getParent());
12239     }
12240 
12241     // If any errors have occurred, clear out any temporaries that may have
12242     // been leftover. This ensures that these temporaries won't be picked up for
12243     // deletion in some later function.
12244     if (getDiagnostics().hasErrorOccurred() ||
12245         getDiagnostics().getSuppressAllDiagnostics()) {
12246       DiscardCleanupsInEvaluationContext();
12247     }
12248     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12249         !isa<FunctionTemplateDecl>(dcl)) {
12250       // Since the body is valid, issue any analysis-based warnings that are
12251       // enabled.
12252       ActivePolicy = &WP;
12253     }
12254 
12255     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12256         (!CheckConstexprFunctionDecl(FD) ||
12257          !CheckConstexprFunctionBody(FD, Body)))
12258       FD->setInvalidDecl();
12259 
12260     if (FD && FD->hasAttr<NakedAttr>()) {
12261       for (const Stmt *S : Body->children()) {
12262         // Allow local register variables without initializer as they don't
12263         // require prologue.
12264         bool RegisterVariables = false;
12265         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12266           for (const auto *Decl : DS->decls()) {
12267             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12268               RegisterVariables =
12269                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12270               if (!RegisterVariables)
12271                 break;
12272             }
12273           }
12274         }
12275         if (RegisterVariables)
12276           continue;
12277         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12278           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12279           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12280           FD->setInvalidDecl();
12281           break;
12282         }
12283       }
12284     }
12285 
12286     assert(ExprCleanupObjects.size() ==
12287                ExprEvalContexts.back().NumCleanupObjects &&
12288            "Leftover temporaries in function");
12289     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12290     assert(MaybeODRUseExprs.empty() &&
12291            "Leftover expressions for odr-use checking");
12292   }
12293 
12294   if (!IsInstantiation)
12295     PopDeclContext();
12296 
12297   PopFunctionScopeInfo(ActivePolicy, dcl);
12298   // If any errors have occurred, clear out any temporaries that may have
12299   // been leftover. This ensures that these temporaries won't be picked up for
12300   // deletion in some later function.
12301   if (getDiagnostics().hasErrorOccurred()) {
12302     DiscardCleanupsInEvaluationContext();
12303   }
12304 
12305   return dcl;
12306 }
12307 
12308 /// When we finish delayed parsing of an attribute, we must attach it to the
12309 /// relevant Decl.
12310 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12311                                        ParsedAttributes &Attrs) {
12312   // Always attach attributes to the underlying decl.
12313   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12314     D = TD->getTemplatedDecl();
12315   ProcessDeclAttributeList(S, D, Attrs.getList());
12316 
12317   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12318     if (Method->isStatic())
12319       checkThisInStaticMemberFunctionAttributes(Method);
12320 }
12321 
12322 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12323 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12324 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12325                                           IdentifierInfo &II, Scope *S) {
12326   // Before we produce a declaration for an implicitly defined
12327   // function, see whether there was a locally-scoped declaration of
12328   // this name as a function or variable. If so, use that
12329   // (non-visible) declaration, and complain about it.
12330   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12331     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12332     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12333     return ExternCPrev;
12334   }
12335 
12336   // Extension in C99.  Legal in C90, but warn about it.
12337   unsigned diag_id;
12338   if (II.getName().startswith("__builtin_"))
12339     diag_id = diag::warn_builtin_unknown;
12340   else if (getLangOpts().C99)
12341     diag_id = diag::ext_implicit_function_decl;
12342   else
12343     diag_id = diag::warn_implicit_function_decl;
12344   Diag(Loc, diag_id) << &II;
12345 
12346   // Because typo correction is expensive, only do it if the implicit
12347   // function declaration is going to be treated as an error.
12348   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12349     TypoCorrection Corrected;
12350     if (S &&
12351         (Corrected = CorrectTypo(
12352              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12353              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12354       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12355                    /*ErrorRecovery*/false);
12356   }
12357 
12358   // Set a Declarator for the implicit definition: int foo();
12359   const char *Dummy;
12360   AttributeFactory attrFactory;
12361   DeclSpec DS(attrFactory);
12362   unsigned DiagID;
12363   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12364                                   Context.getPrintingPolicy());
12365   (void)Error; // Silence warning.
12366   assert(!Error && "Error setting up implicit decl!");
12367   SourceLocation NoLoc;
12368   Declarator D(DS, Declarator::BlockContext);
12369   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12370                                              /*IsAmbiguous=*/false,
12371                                              /*LParenLoc=*/NoLoc,
12372                                              /*Params=*/nullptr,
12373                                              /*NumParams=*/0,
12374                                              /*EllipsisLoc=*/NoLoc,
12375                                              /*RParenLoc=*/NoLoc,
12376                                              /*TypeQuals=*/0,
12377                                              /*RefQualifierIsLvalueRef=*/true,
12378                                              /*RefQualifierLoc=*/NoLoc,
12379                                              /*ConstQualifierLoc=*/NoLoc,
12380                                              /*VolatileQualifierLoc=*/NoLoc,
12381                                              /*RestrictQualifierLoc=*/NoLoc,
12382                                              /*MutableLoc=*/NoLoc,
12383                                              EST_None,
12384                                              /*ESpecRange=*/SourceRange(),
12385                                              /*Exceptions=*/nullptr,
12386                                              /*ExceptionRanges=*/nullptr,
12387                                              /*NumExceptions=*/0,
12388                                              /*NoexceptExpr=*/nullptr,
12389                                              /*ExceptionSpecTokens=*/nullptr,
12390                                              /*DeclsInPrototype=*/None,
12391                                              Loc, Loc, D),
12392                 DS.getAttributes(),
12393                 SourceLocation());
12394   D.SetIdentifier(&II, Loc);
12395 
12396   // Insert this function into translation-unit scope.
12397 
12398   DeclContext *PrevDC = CurContext;
12399   CurContext = Context.getTranslationUnitDecl();
12400 
12401   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12402   FD->setImplicit();
12403 
12404   CurContext = PrevDC;
12405 
12406   AddKnownFunctionAttributes(FD);
12407 
12408   return FD;
12409 }
12410 
12411 /// \brief Adds any function attributes that we know a priori based on
12412 /// the declaration of this function.
12413 ///
12414 /// These attributes can apply both to implicitly-declared builtins
12415 /// (like __builtin___printf_chk) or to library-declared functions
12416 /// like NSLog or printf.
12417 ///
12418 /// We need to check for duplicate attributes both here and where user-written
12419 /// attributes are applied to declarations.
12420 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12421   if (FD->isInvalidDecl())
12422     return;
12423 
12424   // If this is a built-in function, map its builtin attributes to
12425   // actual attributes.
12426   if (unsigned BuiltinID = FD->getBuiltinID()) {
12427     // Handle printf-formatting attributes.
12428     unsigned FormatIdx;
12429     bool HasVAListArg;
12430     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12431       if (!FD->hasAttr<FormatAttr>()) {
12432         const char *fmt = "printf";
12433         unsigned int NumParams = FD->getNumParams();
12434         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12435             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12436           fmt = "NSString";
12437         FD->addAttr(FormatAttr::CreateImplicit(Context,
12438                                                &Context.Idents.get(fmt),
12439                                                FormatIdx+1,
12440                                                HasVAListArg ? 0 : FormatIdx+2,
12441                                                FD->getLocation()));
12442       }
12443     }
12444     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12445                                              HasVAListArg)) {
12446      if (!FD->hasAttr<FormatAttr>())
12447        FD->addAttr(FormatAttr::CreateImplicit(Context,
12448                                               &Context.Idents.get("scanf"),
12449                                               FormatIdx+1,
12450                                               HasVAListArg ? 0 : FormatIdx+2,
12451                                               FD->getLocation()));
12452     }
12453 
12454     // Mark const if we don't care about errno and that is the only
12455     // thing preventing the function from being const. This allows
12456     // IRgen to use LLVM intrinsics for such functions.
12457     if (!getLangOpts().MathErrno &&
12458         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12459       if (!FD->hasAttr<ConstAttr>())
12460         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12461     }
12462 
12463     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12464         !FD->hasAttr<ReturnsTwiceAttr>())
12465       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12466                                          FD->getLocation()));
12467     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12468       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12469     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12470       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12471     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12472       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12473     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12474         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12475       // Add the appropriate attribute, depending on the CUDA compilation mode
12476       // and which target the builtin belongs to. For example, during host
12477       // compilation, aux builtins are __device__, while the rest are __host__.
12478       if (getLangOpts().CUDAIsDevice !=
12479           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12480         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12481       else
12482         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12483     }
12484   }
12485 
12486   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12487   // throw, add an implicit nothrow attribute to any extern "C" function we come
12488   // across.
12489   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12490       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12491     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12492     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12493       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12494   }
12495 
12496   IdentifierInfo *Name = FD->getIdentifier();
12497   if (!Name)
12498     return;
12499   if ((!getLangOpts().CPlusPlus &&
12500        FD->getDeclContext()->isTranslationUnit()) ||
12501       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12502        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12503        LinkageSpecDecl::lang_c)) {
12504     // Okay: this could be a libc/libm/Objective-C function we know
12505     // about.
12506   } else
12507     return;
12508 
12509   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12510     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12511     // target-specific builtins, perhaps?
12512     if (!FD->hasAttr<FormatAttr>())
12513       FD->addAttr(FormatAttr::CreateImplicit(Context,
12514                                              &Context.Idents.get("printf"), 2,
12515                                              Name->isStr("vasprintf") ? 0 : 3,
12516                                              FD->getLocation()));
12517   }
12518 
12519   if (Name->isStr("__CFStringMakeConstantString")) {
12520     // We already have a __builtin___CFStringMakeConstantString,
12521     // but builds that use -fno-constant-cfstrings don't go through that.
12522     if (!FD->hasAttr<FormatArgAttr>())
12523       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12524                                                 FD->getLocation()));
12525   }
12526 }
12527 
12528 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12529                                     TypeSourceInfo *TInfo) {
12530   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12531   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12532 
12533   if (!TInfo) {
12534     assert(D.isInvalidType() && "no declarator info for valid type");
12535     TInfo = Context.getTrivialTypeSourceInfo(T);
12536   }
12537 
12538   // Scope manipulation handled by caller.
12539   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12540                                            D.getLocStart(),
12541                                            D.getIdentifierLoc(),
12542                                            D.getIdentifier(),
12543                                            TInfo);
12544 
12545   // Bail out immediately if we have an invalid declaration.
12546   if (D.isInvalidType()) {
12547     NewTD->setInvalidDecl();
12548     return NewTD;
12549   }
12550 
12551   if (D.getDeclSpec().isModulePrivateSpecified()) {
12552     if (CurContext->isFunctionOrMethod())
12553       Diag(NewTD->getLocation(), diag::err_module_private_local)
12554         << 2 << NewTD->getDeclName()
12555         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12556         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12557     else
12558       NewTD->setModulePrivate();
12559   }
12560 
12561   // C++ [dcl.typedef]p8:
12562   //   If the typedef declaration defines an unnamed class (or
12563   //   enum), the first typedef-name declared by the declaration
12564   //   to be that class type (or enum type) is used to denote the
12565   //   class type (or enum type) for linkage purposes only.
12566   // We need to check whether the type was declared in the declaration.
12567   switch (D.getDeclSpec().getTypeSpecType()) {
12568   case TST_enum:
12569   case TST_struct:
12570   case TST_interface:
12571   case TST_union:
12572   case TST_class: {
12573     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12574     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12575     break;
12576   }
12577 
12578   default:
12579     break;
12580   }
12581 
12582   return NewTD;
12583 }
12584 
12585 /// \brief Check that this is a valid underlying type for an enum declaration.
12586 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12587   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12588   QualType T = TI->getType();
12589 
12590   if (T->isDependentType())
12591     return false;
12592 
12593   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12594     if (BT->isInteger())
12595       return false;
12596 
12597   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12598   return true;
12599 }
12600 
12601 /// Check whether this is a valid redeclaration of a previous enumeration.
12602 /// \return true if the redeclaration was invalid.
12603 bool Sema::CheckEnumRedeclaration(
12604     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12605     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12606   bool IsFixed = !EnumUnderlyingTy.isNull();
12607 
12608   if (IsScoped != Prev->isScoped()) {
12609     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12610       << Prev->isScoped();
12611     Diag(Prev->getLocation(), diag::note_previous_declaration);
12612     return true;
12613   }
12614 
12615   if (IsFixed && Prev->isFixed()) {
12616     if (!EnumUnderlyingTy->isDependentType() &&
12617         !Prev->getIntegerType()->isDependentType() &&
12618         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12619                                         Prev->getIntegerType())) {
12620       // TODO: Highlight the underlying type of the redeclaration.
12621       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12622         << EnumUnderlyingTy << Prev->getIntegerType();
12623       Diag(Prev->getLocation(), diag::note_previous_declaration)
12624           << Prev->getIntegerTypeRange();
12625       return true;
12626     }
12627   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12628     ;
12629   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12630     ;
12631   } else if (IsFixed != Prev->isFixed()) {
12632     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12633       << Prev->isFixed();
12634     Diag(Prev->getLocation(), diag::note_previous_declaration);
12635     return true;
12636   }
12637 
12638   return false;
12639 }
12640 
12641 /// \brief Get diagnostic %select index for tag kind for
12642 /// redeclaration diagnostic message.
12643 /// WARNING: Indexes apply to particular diagnostics only!
12644 ///
12645 /// \returns diagnostic %select index.
12646 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12647   switch (Tag) {
12648   case TTK_Struct: return 0;
12649   case TTK_Interface: return 1;
12650   case TTK_Class:  return 2;
12651   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12652   }
12653 }
12654 
12655 /// \brief Determine if tag kind is a class-key compatible with
12656 /// class for redeclaration (class, struct, or __interface).
12657 ///
12658 /// \returns true iff the tag kind is compatible.
12659 static bool isClassCompatTagKind(TagTypeKind Tag)
12660 {
12661   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12662 }
12663 
12664 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12665                                              TagTypeKind TTK) {
12666   if (isa<TypedefDecl>(PrevDecl))
12667     return NTK_Typedef;
12668   else if (isa<TypeAliasDecl>(PrevDecl))
12669     return NTK_TypeAlias;
12670   else if (isa<ClassTemplateDecl>(PrevDecl))
12671     return NTK_Template;
12672   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12673     return NTK_TypeAliasTemplate;
12674   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12675     return NTK_TemplateTemplateArgument;
12676   switch (TTK) {
12677   case TTK_Struct:
12678   case TTK_Interface:
12679   case TTK_Class:
12680     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12681   case TTK_Union:
12682     return NTK_NonUnion;
12683   case TTK_Enum:
12684     return NTK_NonEnum;
12685   }
12686   llvm_unreachable("invalid TTK");
12687 }
12688 
12689 /// \brief Determine whether a tag with a given kind is acceptable
12690 /// as a redeclaration of the given tag declaration.
12691 ///
12692 /// \returns true if the new tag kind is acceptable, false otherwise.
12693 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12694                                         TagTypeKind NewTag, bool isDefinition,
12695                                         SourceLocation NewTagLoc,
12696                                         const IdentifierInfo *Name) {
12697   // C++ [dcl.type.elab]p3:
12698   //   The class-key or enum keyword present in the
12699   //   elaborated-type-specifier shall agree in kind with the
12700   //   declaration to which the name in the elaborated-type-specifier
12701   //   refers. This rule also applies to the form of
12702   //   elaborated-type-specifier that declares a class-name or
12703   //   friend class since it can be construed as referring to the
12704   //   definition of the class. Thus, in any
12705   //   elaborated-type-specifier, the enum keyword shall be used to
12706   //   refer to an enumeration (7.2), the union class-key shall be
12707   //   used to refer to a union (clause 9), and either the class or
12708   //   struct class-key shall be used to refer to a class (clause 9)
12709   //   declared using the class or struct class-key.
12710   TagTypeKind OldTag = Previous->getTagKind();
12711   if (!isDefinition || !isClassCompatTagKind(NewTag))
12712     if (OldTag == NewTag)
12713       return true;
12714 
12715   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12716     // Warn about the struct/class tag mismatch.
12717     bool isTemplate = false;
12718     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12719       isTemplate = Record->getDescribedClassTemplate();
12720 
12721     if (inTemplateInstantiation()) {
12722       // In a template instantiation, do not offer fix-its for tag mismatches
12723       // since they usually mess up the template instead of fixing the problem.
12724       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12725         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12726         << getRedeclDiagFromTagKind(OldTag);
12727       return true;
12728     }
12729 
12730     if (isDefinition) {
12731       // On definitions, check previous tags and issue a fix-it for each
12732       // one that doesn't match the current tag.
12733       if (Previous->getDefinition()) {
12734         // Don't suggest fix-its for redefinitions.
12735         return true;
12736       }
12737 
12738       bool previousMismatch = false;
12739       for (auto I : Previous->redecls()) {
12740         if (I->getTagKind() != NewTag) {
12741           if (!previousMismatch) {
12742             previousMismatch = true;
12743             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12744               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12745               << getRedeclDiagFromTagKind(I->getTagKind());
12746           }
12747           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12748             << getRedeclDiagFromTagKind(NewTag)
12749             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12750                  TypeWithKeyword::getTagTypeKindName(NewTag));
12751         }
12752       }
12753       return true;
12754     }
12755 
12756     // Check for a previous definition.  If current tag and definition
12757     // are same type, do nothing.  If no definition, but disagree with
12758     // with previous tag type, give a warning, but no fix-it.
12759     const TagDecl *Redecl = Previous->getDefinition() ?
12760                             Previous->getDefinition() : Previous;
12761     if (Redecl->getTagKind() == NewTag) {
12762       return true;
12763     }
12764 
12765     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12766       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12767       << getRedeclDiagFromTagKind(OldTag);
12768     Diag(Redecl->getLocation(), diag::note_previous_use);
12769 
12770     // If there is a previous definition, suggest a fix-it.
12771     if (Previous->getDefinition()) {
12772         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12773           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12774           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12775                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12776     }
12777 
12778     return true;
12779   }
12780   return false;
12781 }
12782 
12783 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12784 /// from an outer enclosing namespace or file scope inside a friend declaration.
12785 /// This should provide the commented out code in the following snippet:
12786 ///   namespace N {
12787 ///     struct X;
12788 ///     namespace M {
12789 ///       struct Y { friend struct /*N::*/ X; };
12790 ///     }
12791 ///   }
12792 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12793                                          SourceLocation NameLoc) {
12794   // While the decl is in a namespace, do repeated lookup of that name and see
12795   // if we get the same namespace back.  If we do not, continue until
12796   // translation unit scope, at which point we have a fully qualified NNS.
12797   SmallVector<IdentifierInfo *, 4> Namespaces;
12798   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12799   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12800     // This tag should be declared in a namespace, which can only be enclosed by
12801     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12802     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12803     if (!Namespace || Namespace->isAnonymousNamespace())
12804       return FixItHint();
12805     IdentifierInfo *II = Namespace->getIdentifier();
12806     Namespaces.push_back(II);
12807     NamedDecl *Lookup = SemaRef.LookupSingleName(
12808         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12809     if (Lookup == Namespace)
12810       break;
12811   }
12812 
12813   // Once we have all the namespaces, reverse them to go outermost first, and
12814   // build an NNS.
12815   SmallString<64> Insertion;
12816   llvm::raw_svector_ostream OS(Insertion);
12817   if (DC->isTranslationUnit())
12818     OS << "::";
12819   std::reverse(Namespaces.begin(), Namespaces.end());
12820   for (auto *II : Namespaces)
12821     OS << II->getName() << "::";
12822   return FixItHint::CreateInsertion(NameLoc, Insertion);
12823 }
12824 
12825 /// \brief Determine whether a tag originally declared in context \p OldDC can
12826 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12827 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12828 /// using-declaration).
12829 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12830                                          DeclContext *NewDC) {
12831   OldDC = OldDC->getRedeclContext();
12832   NewDC = NewDC->getRedeclContext();
12833 
12834   if (OldDC->Equals(NewDC))
12835     return true;
12836 
12837   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12838   // encloses the other).
12839   if (S.getLangOpts().MSVCCompat &&
12840       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12841     return true;
12842 
12843   return false;
12844 }
12845 
12846 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12847 /// former case, Name will be non-null.  In the later case, Name will be null.
12848 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12849 /// reference/declaration/definition of a tag.
12850 ///
12851 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12852 /// trailing-type-specifier) other than one in an alias-declaration.
12853 ///
12854 /// \param SkipBody If non-null, will be set to indicate if the caller should
12855 /// skip the definition of this tag and treat it as if it were a declaration.
12856 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12857                      SourceLocation KWLoc, CXXScopeSpec &SS,
12858                      IdentifierInfo *Name, SourceLocation NameLoc,
12859                      AttributeList *Attr, AccessSpecifier AS,
12860                      SourceLocation ModulePrivateLoc,
12861                      MultiTemplateParamsArg TemplateParameterLists,
12862                      bool &OwnedDecl, bool &IsDependent,
12863                      SourceLocation ScopedEnumKWLoc,
12864                      bool ScopedEnumUsesClassTag,
12865                      TypeResult UnderlyingType,
12866                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12867   // If this is not a definition, it must have a name.
12868   IdentifierInfo *OrigName = Name;
12869   assert((Name != nullptr || TUK == TUK_Definition) &&
12870          "Nameless record must be a definition!");
12871   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12872 
12873   OwnedDecl = false;
12874   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12875   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12876 
12877   // FIXME: Check member specializations more carefully.
12878   bool isMemberSpecialization = false;
12879   bool Invalid = false;
12880 
12881   // We only need to do this matching if we have template parameters
12882   // or a scope specifier, which also conveniently avoids this work
12883   // for non-C++ cases.
12884   if (TemplateParameterLists.size() > 0 ||
12885       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12886     if (TemplateParameterList *TemplateParams =
12887             MatchTemplateParametersToScopeSpecifier(
12888                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12889                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12890       if (Kind == TTK_Enum) {
12891         Diag(KWLoc, diag::err_enum_template);
12892         return nullptr;
12893       }
12894 
12895       if (TemplateParams->size() > 0) {
12896         // This is a declaration or definition of a class template (which may
12897         // be a member of another template).
12898 
12899         if (Invalid)
12900           return nullptr;
12901 
12902         OwnedDecl = false;
12903         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12904                                                SS, Name, NameLoc, Attr,
12905                                                TemplateParams, AS,
12906                                                ModulePrivateLoc,
12907                                                /*FriendLoc*/SourceLocation(),
12908                                                TemplateParameterLists.size()-1,
12909                                                TemplateParameterLists.data(),
12910                                                SkipBody);
12911         return Result.get();
12912       } else {
12913         // The "template<>" header is extraneous.
12914         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12915           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12916         isMemberSpecialization = true;
12917       }
12918     }
12919   }
12920 
12921   // Figure out the underlying type if this a enum declaration. We need to do
12922   // this early, because it's needed to detect if this is an incompatible
12923   // redeclaration.
12924   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12925   bool EnumUnderlyingIsImplicit = false;
12926 
12927   if (Kind == TTK_Enum) {
12928     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12929       // No underlying type explicitly specified, or we failed to parse the
12930       // type, default to int.
12931       EnumUnderlying = Context.IntTy.getTypePtr();
12932     else if (UnderlyingType.get()) {
12933       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12934       // integral type; any cv-qualification is ignored.
12935       TypeSourceInfo *TI = nullptr;
12936       GetTypeFromParser(UnderlyingType.get(), &TI);
12937       EnumUnderlying = TI;
12938 
12939       if (CheckEnumUnderlyingType(TI))
12940         // Recover by falling back to int.
12941         EnumUnderlying = Context.IntTy.getTypePtr();
12942 
12943       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12944                                           UPPC_FixedUnderlyingType))
12945         EnumUnderlying = Context.IntTy.getTypePtr();
12946 
12947     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12948       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12949         // Microsoft enums are always of int type.
12950         EnumUnderlying = Context.IntTy.getTypePtr();
12951         EnumUnderlyingIsImplicit = true;
12952       }
12953     }
12954   }
12955 
12956   DeclContext *SearchDC = CurContext;
12957   DeclContext *DC = CurContext;
12958   bool isStdBadAlloc = false;
12959   bool isStdAlignValT = false;
12960 
12961   RedeclarationKind Redecl = ForRedeclaration;
12962   if (TUK == TUK_Friend || TUK == TUK_Reference)
12963     Redecl = NotForRedeclaration;
12964 
12965   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12966   if (Name && SS.isNotEmpty()) {
12967     // We have a nested-name tag ('struct foo::bar').
12968 
12969     // Check for invalid 'foo::'.
12970     if (SS.isInvalid()) {
12971       Name = nullptr;
12972       goto CreateNewDecl;
12973     }
12974 
12975     // If this is a friend or a reference to a class in a dependent
12976     // context, don't try to make a decl for it.
12977     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12978       DC = computeDeclContext(SS, false);
12979       if (!DC) {
12980         IsDependent = true;
12981         return nullptr;
12982       }
12983     } else {
12984       DC = computeDeclContext(SS, true);
12985       if (!DC) {
12986         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12987           << SS.getRange();
12988         return nullptr;
12989       }
12990     }
12991 
12992     if (RequireCompleteDeclContext(SS, DC))
12993       return nullptr;
12994 
12995     SearchDC = DC;
12996     // Look-up name inside 'foo::'.
12997     LookupQualifiedName(Previous, DC);
12998 
12999     if (Previous.isAmbiguous())
13000       return nullptr;
13001 
13002     if (Previous.empty()) {
13003       // Name lookup did not find anything. However, if the
13004       // nested-name-specifier refers to the current instantiation,
13005       // and that current instantiation has any dependent base
13006       // classes, we might find something at instantiation time: treat
13007       // this as a dependent elaborated-type-specifier.
13008       // But this only makes any sense for reference-like lookups.
13009       if (Previous.wasNotFoundInCurrentInstantiation() &&
13010           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13011         IsDependent = true;
13012         return nullptr;
13013       }
13014 
13015       // A tag 'foo::bar' must already exist.
13016       Diag(NameLoc, diag::err_not_tag_in_scope)
13017         << Kind << Name << DC << SS.getRange();
13018       Name = nullptr;
13019       Invalid = true;
13020       goto CreateNewDecl;
13021     }
13022   } else if (Name) {
13023     // C++14 [class.mem]p14:
13024     //   If T is the name of a class, then each of the following shall have a
13025     //   name different from T:
13026     //    -- every member of class T that is itself a type
13027     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13028         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13029       return nullptr;
13030 
13031     // If this is a named struct, check to see if there was a previous forward
13032     // declaration or definition.
13033     // FIXME: We're looking into outer scopes here, even when we
13034     // shouldn't be. Doing so can result in ambiguities that we
13035     // shouldn't be diagnosing.
13036     LookupName(Previous, S);
13037 
13038     // When declaring or defining a tag, ignore ambiguities introduced
13039     // by types using'ed into this scope.
13040     if (Previous.isAmbiguous() &&
13041         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13042       LookupResult::Filter F = Previous.makeFilter();
13043       while (F.hasNext()) {
13044         NamedDecl *ND = F.next();
13045         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13046                 SearchDC->getRedeclContext()))
13047           F.erase();
13048       }
13049       F.done();
13050     }
13051 
13052     // C++11 [namespace.memdef]p3:
13053     //   If the name in a friend declaration is neither qualified nor
13054     //   a template-id and the declaration is a function or an
13055     //   elaborated-type-specifier, the lookup to determine whether
13056     //   the entity has been previously declared shall not consider
13057     //   any scopes outside the innermost enclosing namespace.
13058     //
13059     // MSVC doesn't implement the above rule for types, so a friend tag
13060     // declaration may be a redeclaration of a type declared in an enclosing
13061     // scope.  They do implement this rule for friend functions.
13062     //
13063     // Does it matter that this should be by scope instead of by
13064     // semantic context?
13065     if (!Previous.empty() && TUK == TUK_Friend) {
13066       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13067       LookupResult::Filter F = Previous.makeFilter();
13068       bool FriendSawTagOutsideEnclosingNamespace = false;
13069       while (F.hasNext()) {
13070         NamedDecl *ND = F.next();
13071         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13072         if (DC->isFileContext() &&
13073             !EnclosingNS->Encloses(ND->getDeclContext())) {
13074           if (getLangOpts().MSVCCompat)
13075             FriendSawTagOutsideEnclosingNamespace = true;
13076           else
13077             F.erase();
13078         }
13079       }
13080       F.done();
13081 
13082       // Diagnose this MSVC extension in the easy case where lookup would have
13083       // unambiguously found something outside the enclosing namespace.
13084       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13085         NamedDecl *ND = Previous.getFoundDecl();
13086         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13087             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13088       }
13089     }
13090 
13091     // Note:  there used to be some attempt at recovery here.
13092     if (Previous.isAmbiguous())
13093       return nullptr;
13094 
13095     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13096       // FIXME: This makes sure that we ignore the contexts associated
13097       // with C structs, unions, and enums when looking for a matching
13098       // tag declaration or definition. See the similar lookup tweak
13099       // in Sema::LookupName; is there a better way to deal with this?
13100       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13101         SearchDC = SearchDC->getParent();
13102     }
13103   }
13104 
13105   if (Previous.isSingleResult() &&
13106       Previous.getFoundDecl()->isTemplateParameter()) {
13107     // Maybe we will complain about the shadowed template parameter.
13108     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13109     // Just pretend that we didn't see the previous declaration.
13110     Previous.clear();
13111   }
13112 
13113   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13114       DC->Equals(getStdNamespace())) {
13115     if (Name->isStr("bad_alloc")) {
13116       // This is a declaration of or a reference to "std::bad_alloc".
13117       isStdBadAlloc = true;
13118 
13119       // If std::bad_alloc has been implicitly declared (but made invisible to
13120       // name lookup), fill in this implicit declaration as the previous
13121       // declaration, so that the declarations get chained appropriately.
13122       if (Previous.empty() && StdBadAlloc)
13123         Previous.addDecl(getStdBadAlloc());
13124     } else if (Name->isStr("align_val_t")) {
13125       isStdAlignValT = true;
13126       if (Previous.empty() && StdAlignValT)
13127         Previous.addDecl(getStdAlignValT());
13128     }
13129   }
13130 
13131   // If we didn't find a previous declaration, and this is a reference
13132   // (or friend reference), move to the correct scope.  In C++, we
13133   // also need to do a redeclaration lookup there, just in case
13134   // there's a shadow friend decl.
13135   if (Name && Previous.empty() &&
13136       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13137     if (Invalid) goto CreateNewDecl;
13138     assert(SS.isEmpty());
13139 
13140     if (TUK == TUK_Reference) {
13141       // C++ [basic.scope.pdecl]p5:
13142       //   -- for an elaborated-type-specifier of the form
13143       //
13144       //          class-key identifier
13145       //
13146       //      if the elaborated-type-specifier is used in the
13147       //      decl-specifier-seq or parameter-declaration-clause of a
13148       //      function defined in namespace scope, the identifier is
13149       //      declared as a class-name in the namespace that contains
13150       //      the declaration; otherwise, except as a friend
13151       //      declaration, the identifier is declared in the smallest
13152       //      non-class, non-function-prototype scope that contains the
13153       //      declaration.
13154       //
13155       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13156       // C structs and unions.
13157       //
13158       // It is an error in C++ to declare (rather than define) an enum
13159       // type, including via an elaborated type specifier.  We'll
13160       // diagnose that later; for now, declare the enum in the same
13161       // scope as we would have picked for any other tag type.
13162       //
13163       // GNU C also supports this behavior as part of its incomplete
13164       // enum types extension, while GNU C++ does not.
13165       //
13166       // Find the context where we'll be declaring the tag.
13167       // FIXME: We would like to maintain the current DeclContext as the
13168       // lexical context,
13169       SearchDC = getTagInjectionContext(SearchDC);
13170 
13171       // Find the scope where we'll be declaring the tag.
13172       S = getTagInjectionScope(S, getLangOpts());
13173     } else {
13174       assert(TUK == TUK_Friend);
13175       // C++ [namespace.memdef]p3:
13176       //   If a friend declaration in a non-local class first declares a
13177       //   class or function, the friend class or function is a member of
13178       //   the innermost enclosing namespace.
13179       SearchDC = SearchDC->getEnclosingNamespaceContext();
13180     }
13181 
13182     // In C++, we need to do a redeclaration lookup to properly
13183     // diagnose some problems.
13184     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13185     // hidden declaration so that we don't get ambiguity errors when using a
13186     // type declared by an elaborated-type-specifier.  In C that is not correct
13187     // and we should instead merge compatible types found by lookup.
13188     if (getLangOpts().CPlusPlus) {
13189       Previous.setRedeclarationKind(ForRedeclaration);
13190       LookupQualifiedName(Previous, SearchDC);
13191     } else {
13192       Previous.setRedeclarationKind(ForRedeclaration);
13193       LookupName(Previous, S);
13194     }
13195   }
13196 
13197   // If we have a known previous declaration to use, then use it.
13198   if (Previous.empty() && SkipBody && SkipBody->Previous)
13199     Previous.addDecl(SkipBody->Previous);
13200 
13201   if (!Previous.empty()) {
13202     NamedDecl *PrevDecl = Previous.getFoundDecl();
13203     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13204 
13205     // It's okay to have a tag decl in the same scope as a typedef
13206     // which hides a tag decl in the same scope.  Finding this
13207     // insanity with a redeclaration lookup can only actually happen
13208     // in C++.
13209     //
13210     // This is also okay for elaborated-type-specifiers, which is
13211     // technically forbidden by the current standard but which is
13212     // okay according to the likely resolution of an open issue;
13213     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13214     if (getLangOpts().CPlusPlus) {
13215       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13216         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13217           TagDecl *Tag = TT->getDecl();
13218           if (Tag->getDeclName() == Name &&
13219               Tag->getDeclContext()->getRedeclContext()
13220                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13221             PrevDecl = Tag;
13222             Previous.clear();
13223             Previous.addDecl(Tag);
13224             Previous.resolveKind();
13225           }
13226         }
13227       }
13228     }
13229 
13230     // If this is a redeclaration of a using shadow declaration, it must
13231     // declare a tag in the same context. In MSVC mode, we allow a
13232     // redefinition if either context is within the other.
13233     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13234       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13235       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13236           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13237           !(OldTag && isAcceptableTagRedeclContext(
13238                           *this, OldTag->getDeclContext(), SearchDC))) {
13239         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13240         Diag(Shadow->getTargetDecl()->getLocation(),
13241              diag::note_using_decl_target);
13242         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13243             << 0;
13244         // Recover by ignoring the old declaration.
13245         Previous.clear();
13246         goto CreateNewDecl;
13247       }
13248     }
13249 
13250     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13251       // If this is a use of a previous tag, or if the tag is already declared
13252       // in the same scope (so that the definition/declaration completes or
13253       // rementions the tag), reuse the decl.
13254       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13255           isDeclInScope(DirectPrevDecl, SearchDC, S,
13256                         SS.isNotEmpty() || isMemberSpecialization)) {
13257         // Make sure that this wasn't declared as an enum and now used as a
13258         // struct or something similar.
13259         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13260                                           TUK == TUK_Definition, KWLoc,
13261                                           Name)) {
13262           bool SafeToContinue
13263             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13264                Kind != TTK_Enum);
13265           if (SafeToContinue)
13266             Diag(KWLoc, diag::err_use_with_wrong_tag)
13267               << Name
13268               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13269                                               PrevTagDecl->getKindName());
13270           else
13271             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13272           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13273 
13274           if (SafeToContinue)
13275             Kind = PrevTagDecl->getTagKind();
13276           else {
13277             // Recover by making this an anonymous redefinition.
13278             Name = nullptr;
13279             Previous.clear();
13280             Invalid = true;
13281           }
13282         }
13283 
13284         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13285           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13286 
13287           // If this is an elaborated-type-specifier for a scoped enumeration,
13288           // the 'class' keyword is not necessary and not permitted.
13289           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13290             if (ScopedEnum)
13291               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13292                 << PrevEnum->isScoped()
13293                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13294             return PrevTagDecl;
13295           }
13296 
13297           QualType EnumUnderlyingTy;
13298           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13299             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13300           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13301             EnumUnderlyingTy = QualType(T, 0);
13302 
13303           // All conflicts with previous declarations are recovered by
13304           // returning the previous declaration, unless this is a definition,
13305           // in which case we want the caller to bail out.
13306           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13307                                      ScopedEnum, EnumUnderlyingTy,
13308                                      EnumUnderlyingIsImplicit, PrevEnum))
13309             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13310         }
13311 
13312         // C++11 [class.mem]p1:
13313         //   A member shall not be declared twice in the member-specification,
13314         //   except that a nested class or member class template can be declared
13315         //   and then later defined.
13316         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13317             S->isDeclScope(PrevDecl)) {
13318           Diag(NameLoc, diag::ext_member_redeclared);
13319           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13320         }
13321 
13322         if (!Invalid) {
13323           // If this is a use, just return the declaration we found, unless
13324           // we have attributes.
13325           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13326             if (Attr) {
13327               // FIXME: Diagnose these attributes. For now, we create a new
13328               // declaration to hold them.
13329             } else if (TUK == TUK_Reference &&
13330                        (PrevTagDecl->getFriendObjectKind() ==
13331                             Decl::FOK_Undeclared ||
13332                         PP.getModuleContainingLocation(
13333                             PrevDecl->getLocation()) !=
13334                             PP.getModuleContainingLocation(KWLoc)) &&
13335                        SS.isEmpty()) {
13336               // This declaration is a reference to an existing entity, but
13337               // has different visibility from that entity: it either makes
13338               // a friend visible or it makes a type visible in a new module.
13339               // In either case, create a new declaration. We only do this if
13340               // the declaration would have meant the same thing if no prior
13341               // declaration were found, that is, if it was found in the same
13342               // scope where we would have injected a declaration.
13343               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13344                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13345                 return PrevTagDecl;
13346               // This is in the injected scope, create a new declaration in
13347               // that scope.
13348               S = getTagInjectionScope(S, getLangOpts());
13349             } else {
13350               return PrevTagDecl;
13351             }
13352           }
13353 
13354           // Diagnose attempts to redefine a tag.
13355           if (TUK == TUK_Definition) {
13356             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13357               // If we're defining a specialization and the previous definition
13358               // is from an implicit instantiation, don't emit an error
13359               // here; we'll catch this in the general case below.
13360               bool IsExplicitSpecializationAfterInstantiation = false;
13361               if (isMemberSpecialization) {
13362                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13363                   IsExplicitSpecializationAfterInstantiation =
13364                     RD->getTemplateSpecializationKind() !=
13365                     TSK_ExplicitSpecialization;
13366                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13367                   IsExplicitSpecializationAfterInstantiation =
13368                     ED->getTemplateSpecializationKind() !=
13369                     TSK_ExplicitSpecialization;
13370               }
13371 
13372               NamedDecl *Hidden = nullptr;
13373               if (SkipBody && getLangOpts().CPlusPlus &&
13374                   !hasVisibleDefinition(Def, &Hidden)) {
13375                 // There is a definition of this tag, but it is not visible. We
13376                 // explicitly make use of C++'s one definition rule here, and
13377                 // assume that this definition is identical to the hidden one
13378                 // we already have. Make the existing definition visible and
13379                 // use it in place of this one.
13380                 SkipBody->ShouldSkip = true;
13381                 makeMergedDefinitionVisible(Hidden, KWLoc);
13382                 return Def;
13383               } else if (!IsExplicitSpecializationAfterInstantiation) {
13384                 // A redeclaration in function prototype scope in C isn't
13385                 // visible elsewhere, so merely issue a warning.
13386                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13387                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13388                 else
13389                   Diag(NameLoc, diag::err_redefinition) << Name;
13390                 Diag(Def->getLocation(), diag::note_previous_definition);
13391                 // If this is a redefinition, recover by making this
13392                 // struct be anonymous, which will make any later
13393                 // references get the previous definition.
13394                 Name = nullptr;
13395                 Previous.clear();
13396                 Invalid = true;
13397               }
13398             } else {
13399               // If the type is currently being defined, complain
13400               // about a nested redefinition.
13401               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13402               if (TD->isBeingDefined()) {
13403                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13404                 Diag(PrevTagDecl->getLocation(),
13405                      diag::note_previous_definition);
13406                 Name = nullptr;
13407                 Previous.clear();
13408                 Invalid = true;
13409               }
13410             }
13411 
13412             // Okay, this is definition of a previously declared or referenced
13413             // tag. We're going to create a new Decl for it.
13414           }
13415 
13416           // Okay, we're going to make a redeclaration.  If this is some kind
13417           // of reference, make sure we build the redeclaration in the same DC
13418           // as the original, and ignore the current access specifier.
13419           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13420             SearchDC = PrevTagDecl->getDeclContext();
13421             AS = AS_none;
13422           }
13423         }
13424         // If we get here we have (another) forward declaration or we
13425         // have a definition.  Just create a new decl.
13426 
13427       } else {
13428         // If we get here, this is a definition of a new tag type in a nested
13429         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13430         // new decl/type.  We set PrevDecl to NULL so that the entities
13431         // have distinct types.
13432         Previous.clear();
13433       }
13434       // If we get here, we're going to create a new Decl. If PrevDecl
13435       // is non-NULL, it's a definition of the tag declared by
13436       // PrevDecl. If it's NULL, we have a new definition.
13437 
13438     // Otherwise, PrevDecl is not a tag, but was found with tag
13439     // lookup.  This is only actually possible in C++, where a few
13440     // things like templates still live in the tag namespace.
13441     } else {
13442       // Use a better diagnostic if an elaborated-type-specifier
13443       // found the wrong kind of type on the first
13444       // (non-redeclaration) lookup.
13445       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13446           !Previous.isForRedeclaration()) {
13447         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13448         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13449                                                        << Kind;
13450         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13451         Invalid = true;
13452 
13453       // Otherwise, only diagnose if the declaration is in scope.
13454       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13455                                 SS.isNotEmpty() || isMemberSpecialization)) {
13456         // do nothing
13457 
13458       // Diagnose implicit declarations introduced by elaborated types.
13459       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13460         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13461         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13462         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13463         Invalid = true;
13464 
13465       // Otherwise it's a declaration.  Call out a particularly common
13466       // case here.
13467       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13468         unsigned Kind = 0;
13469         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13470         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13471           << Name << Kind << TND->getUnderlyingType();
13472         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13473         Invalid = true;
13474 
13475       // Otherwise, diagnose.
13476       } else {
13477         // The tag name clashes with something else in the target scope,
13478         // issue an error and recover by making this tag be anonymous.
13479         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13480         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13481         Name = nullptr;
13482         Invalid = true;
13483       }
13484 
13485       // The existing declaration isn't relevant to us; we're in a
13486       // new scope, so clear out the previous declaration.
13487       Previous.clear();
13488     }
13489   }
13490 
13491 CreateNewDecl:
13492 
13493   TagDecl *PrevDecl = nullptr;
13494   if (Previous.isSingleResult())
13495     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13496 
13497   // If there is an identifier, use the location of the identifier as the
13498   // location of the decl, otherwise use the location of the struct/union
13499   // keyword.
13500   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13501 
13502   // Otherwise, create a new declaration. If there is a previous
13503   // declaration of the same entity, the two will be linked via
13504   // PrevDecl.
13505   TagDecl *New;
13506 
13507   bool IsForwardReference = false;
13508   if (Kind == TTK_Enum) {
13509     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13510     // enum X { A, B, C } D;    D should chain to X.
13511     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13512                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13513                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13514 
13515     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13516       StdAlignValT = cast<EnumDecl>(New);
13517 
13518     // If this is an undefined enum, warn.
13519     if (TUK != TUK_Definition && !Invalid) {
13520       TagDecl *Def;
13521       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13522           cast<EnumDecl>(New)->isFixed()) {
13523         // C++0x: 7.2p2: opaque-enum-declaration.
13524         // Conflicts are diagnosed above. Do nothing.
13525       }
13526       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13527         Diag(Loc, diag::ext_forward_ref_enum_def)
13528           << New;
13529         Diag(Def->getLocation(), diag::note_previous_definition);
13530       } else {
13531         unsigned DiagID = diag::ext_forward_ref_enum;
13532         if (getLangOpts().MSVCCompat)
13533           DiagID = diag::ext_ms_forward_ref_enum;
13534         else if (getLangOpts().CPlusPlus)
13535           DiagID = diag::err_forward_ref_enum;
13536         Diag(Loc, DiagID);
13537 
13538         // If this is a forward-declared reference to an enumeration, make a
13539         // note of it; we won't actually be introducing the declaration into
13540         // the declaration context.
13541         if (TUK == TUK_Reference)
13542           IsForwardReference = true;
13543       }
13544     }
13545 
13546     if (EnumUnderlying) {
13547       EnumDecl *ED = cast<EnumDecl>(New);
13548       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13549         ED->setIntegerTypeSourceInfo(TI);
13550       else
13551         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13552       ED->setPromotionType(ED->getIntegerType());
13553     }
13554   } else {
13555     // struct/union/class
13556 
13557     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13558     // struct X { int A; } D;    D should chain to X.
13559     if (getLangOpts().CPlusPlus) {
13560       // FIXME: Look for a way to use RecordDecl for simple structs.
13561       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13562                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13563 
13564       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13565         StdBadAlloc = cast<CXXRecordDecl>(New);
13566     } else
13567       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13568                                cast_or_null<RecordDecl>(PrevDecl));
13569   }
13570 
13571   // C++11 [dcl.type]p3:
13572   //   A type-specifier-seq shall not define a class or enumeration [...].
13573   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13574     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13575       << Context.getTagDeclType(New);
13576     Invalid = true;
13577   }
13578 
13579   // Maybe add qualifier info.
13580   if (SS.isNotEmpty()) {
13581     if (SS.isSet()) {
13582       // If this is either a declaration or a definition, check the
13583       // nested-name-specifier against the current context. We don't do this
13584       // for explicit specializations, because they have similar checking
13585       // (with more specific diagnostics) in the call to
13586       // CheckMemberSpecialization, below.
13587       if (!isMemberSpecialization &&
13588           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13589           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13590         Invalid = true;
13591 
13592       New->setQualifierInfo(SS.getWithLocInContext(Context));
13593       if (TemplateParameterLists.size() > 0) {
13594         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13595       }
13596     }
13597     else
13598       Invalid = true;
13599   }
13600 
13601   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13602     // Add alignment attributes if necessary; these attributes are checked when
13603     // the ASTContext lays out the structure.
13604     //
13605     // It is important for implementing the correct semantics that this
13606     // happen here (in act on tag decl). The #pragma pack stack is
13607     // maintained as a result of parser callbacks which can occur at
13608     // many points during the parsing of a struct declaration (because
13609     // the #pragma tokens are effectively skipped over during the
13610     // parsing of the struct).
13611     if (TUK == TUK_Definition) {
13612       AddAlignmentAttributesForRecord(RD);
13613       AddMsStructLayoutForRecord(RD);
13614     }
13615   }
13616 
13617   if (ModulePrivateLoc.isValid()) {
13618     if (isMemberSpecialization)
13619       Diag(New->getLocation(), diag::err_module_private_specialization)
13620         << 2
13621         << FixItHint::CreateRemoval(ModulePrivateLoc);
13622     // __module_private__ does not apply to local classes. However, we only
13623     // diagnose this as an error when the declaration specifiers are
13624     // freestanding. Here, we just ignore the __module_private__.
13625     else if (!SearchDC->isFunctionOrMethod())
13626       New->setModulePrivate();
13627   }
13628 
13629   // If this is a specialization of a member class (of a class template),
13630   // check the specialization.
13631   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13632     Invalid = true;
13633 
13634   // If we're declaring or defining a tag in function prototype scope in C,
13635   // note that this type can only be used within the function and add it to
13636   // the list of decls to inject into the function definition scope.
13637   if ((Name || Kind == TTK_Enum) &&
13638       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13639     if (getLangOpts().CPlusPlus) {
13640       // C++ [dcl.fct]p6:
13641       //   Types shall not be defined in return or parameter types.
13642       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13643         Diag(Loc, diag::err_type_defined_in_param_type)
13644             << Name;
13645         Invalid = true;
13646       }
13647     } else if (!PrevDecl) {
13648       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13649     }
13650   }
13651 
13652   if (Invalid)
13653     New->setInvalidDecl();
13654 
13655   // Set the lexical context. If the tag has a C++ scope specifier, the
13656   // lexical context will be different from the semantic context.
13657   New->setLexicalDeclContext(CurContext);
13658 
13659   // Mark this as a friend decl if applicable.
13660   // In Microsoft mode, a friend declaration also acts as a forward
13661   // declaration so we always pass true to setObjectOfFriendDecl to make
13662   // the tag name visible.
13663   if (TUK == TUK_Friend)
13664     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13665 
13666   // Set the access specifier.
13667   if (!Invalid && SearchDC->isRecord())
13668     SetMemberAccessSpecifier(New, PrevDecl, AS);
13669 
13670   if (TUK == TUK_Definition)
13671     New->startDefinition();
13672 
13673   if (Attr)
13674     ProcessDeclAttributeList(S, New, Attr);
13675 
13676   // If this has an identifier, add it to the scope stack.
13677   if (TUK == TUK_Friend) {
13678     // We might be replacing an existing declaration in the lookup tables;
13679     // if so, borrow its access specifier.
13680     if (PrevDecl)
13681       New->setAccess(PrevDecl->getAccess());
13682 
13683     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13684     DC->makeDeclVisibleInContext(New);
13685     if (Name) // can be null along some error paths
13686       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13687         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13688   } else if (Name) {
13689     S = getNonFieldDeclScope(S);
13690     PushOnScopeChains(New, S, !IsForwardReference);
13691     if (IsForwardReference)
13692       SearchDC->makeDeclVisibleInContext(New);
13693   } else {
13694     CurContext->addDecl(New);
13695   }
13696 
13697   // If this is the C FILE type, notify the AST context.
13698   if (IdentifierInfo *II = New->getIdentifier())
13699     if (!New->isInvalidDecl() &&
13700         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13701         II->isStr("FILE"))
13702       Context.setFILEDecl(New);
13703 
13704   if (PrevDecl)
13705     mergeDeclAttributes(New, PrevDecl);
13706 
13707   // If there's a #pragma GCC visibility in scope, set the visibility of this
13708   // record.
13709   AddPushedVisibilityAttribute(New);
13710 
13711   OwnedDecl = true;
13712   // In C++, don't return an invalid declaration. We can't recover well from
13713   // the cases where we make the type anonymous.
13714   if (Invalid && getLangOpts().CPlusPlus) {
13715     if (New->isBeingDefined())
13716       if (auto RD = dyn_cast<RecordDecl>(New))
13717         RD->completeDefinition();
13718     return nullptr;
13719   } else {
13720     return New;
13721   }
13722 }
13723 
13724 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13725   AdjustDeclIfTemplate(TagD);
13726   TagDecl *Tag = cast<TagDecl>(TagD);
13727 
13728   // Enter the tag context.
13729   PushDeclContext(S, Tag);
13730 
13731   ActOnDocumentableDecl(TagD);
13732 
13733   // If there's a #pragma GCC visibility in scope, set the visibility of this
13734   // record.
13735   AddPushedVisibilityAttribute(Tag);
13736 }
13737 
13738 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13739   assert(isa<ObjCContainerDecl>(IDecl) &&
13740          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13741   DeclContext *OCD = cast<DeclContext>(IDecl);
13742   assert(getContainingDC(OCD) == CurContext &&
13743       "The next DeclContext should be lexically contained in the current one.");
13744   CurContext = OCD;
13745   return IDecl;
13746 }
13747 
13748 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13749                                            SourceLocation FinalLoc,
13750                                            bool IsFinalSpelledSealed,
13751                                            SourceLocation LBraceLoc) {
13752   AdjustDeclIfTemplate(TagD);
13753   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13754 
13755   FieldCollector->StartClass();
13756 
13757   if (!Record->getIdentifier())
13758     return;
13759 
13760   if (FinalLoc.isValid())
13761     Record->addAttr(new (Context)
13762                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13763 
13764   // C++ [class]p2:
13765   //   [...] The class-name is also inserted into the scope of the
13766   //   class itself; this is known as the injected-class-name. For
13767   //   purposes of access checking, the injected-class-name is treated
13768   //   as if it were a public member name.
13769   CXXRecordDecl *InjectedClassName
13770     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13771                             Record->getLocStart(), Record->getLocation(),
13772                             Record->getIdentifier(),
13773                             /*PrevDecl=*/nullptr,
13774                             /*DelayTypeCreation=*/true);
13775   Context.getTypeDeclType(InjectedClassName, Record);
13776   InjectedClassName->setImplicit();
13777   InjectedClassName->setAccess(AS_public);
13778   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13779       InjectedClassName->setDescribedClassTemplate(Template);
13780   PushOnScopeChains(InjectedClassName, S);
13781   assert(InjectedClassName->isInjectedClassName() &&
13782          "Broken injected-class-name");
13783 }
13784 
13785 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13786                                     SourceRange BraceRange) {
13787   AdjustDeclIfTemplate(TagD);
13788   TagDecl *Tag = cast<TagDecl>(TagD);
13789   Tag->setBraceRange(BraceRange);
13790 
13791   // Make sure we "complete" the definition even it is invalid.
13792   if (Tag->isBeingDefined()) {
13793     assert(Tag->isInvalidDecl() && "We should already have completed it");
13794     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13795       RD->completeDefinition();
13796   }
13797 
13798   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
13799     FieldCollector->FinishClass();
13800     if (Context.getLangOpts().Modules)
13801       RD->computeODRHash();
13802   }
13803 
13804   // Exit this scope of this tag's definition.
13805   PopDeclContext();
13806 
13807   if (getCurLexicalContext()->isObjCContainer() &&
13808       Tag->getDeclContext()->isFileContext())
13809     Tag->setTopLevelDeclInObjCContainer();
13810 
13811   // Notify the consumer that we've defined a tag.
13812   if (!Tag->isInvalidDecl())
13813     Consumer.HandleTagDeclDefinition(Tag);
13814 }
13815 
13816 void Sema::ActOnObjCContainerFinishDefinition() {
13817   // Exit this scope of this interface definition.
13818   PopDeclContext();
13819 }
13820 
13821 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13822   assert(DC == CurContext && "Mismatch of container contexts");
13823   OriginalLexicalContext = DC;
13824   ActOnObjCContainerFinishDefinition();
13825 }
13826 
13827 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13828   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13829   OriginalLexicalContext = nullptr;
13830 }
13831 
13832 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13833   AdjustDeclIfTemplate(TagD);
13834   TagDecl *Tag = cast<TagDecl>(TagD);
13835   Tag->setInvalidDecl();
13836 
13837   // Make sure we "complete" the definition even it is invalid.
13838   if (Tag->isBeingDefined()) {
13839     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13840       RD->completeDefinition();
13841   }
13842 
13843   // We're undoing ActOnTagStartDefinition here, not
13844   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13845   // the FieldCollector.
13846 
13847   PopDeclContext();
13848 }
13849 
13850 // Note that FieldName may be null for anonymous bitfields.
13851 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13852                                 IdentifierInfo *FieldName,
13853                                 QualType FieldTy, bool IsMsStruct,
13854                                 Expr *BitWidth, bool *ZeroWidth) {
13855   // Default to true; that shouldn't confuse checks for emptiness
13856   if (ZeroWidth)
13857     *ZeroWidth = true;
13858 
13859   // C99 6.7.2.1p4 - verify the field type.
13860   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13861   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13862     // Handle incomplete types with specific error.
13863     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13864       return ExprError();
13865     if (FieldName)
13866       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13867         << FieldName << FieldTy << BitWidth->getSourceRange();
13868     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13869       << FieldTy << BitWidth->getSourceRange();
13870   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13871                                              UPPC_BitFieldWidth))
13872     return ExprError();
13873 
13874   // If the bit-width is type- or value-dependent, don't try to check
13875   // it now.
13876   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13877     return BitWidth;
13878 
13879   llvm::APSInt Value;
13880   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13881   if (ICE.isInvalid())
13882     return ICE;
13883   BitWidth = ICE.get();
13884 
13885   if (Value != 0 && ZeroWidth)
13886     *ZeroWidth = false;
13887 
13888   // Zero-width bitfield is ok for anonymous field.
13889   if (Value == 0 && FieldName)
13890     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13891 
13892   if (Value.isSigned() && Value.isNegative()) {
13893     if (FieldName)
13894       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13895                << FieldName << Value.toString(10);
13896     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13897       << Value.toString(10);
13898   }
13899 
13900   if (!FieldTy->isDependentType()) {
13901     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13902     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13903     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13904 
13905     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13906     // ABI.
13907     bool CStdConstraintViolation =
13908         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13909     bool MSBitfieldViolation =
13910         Value.ugt(TypeStorageSize) &&
13911         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13912     if (CStdConstraintViolation || MSBitfieldViolation) {
13913       unsigned DiagWidth =
13914           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13915       if (FieldName)
13916         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13917                << FieldName << (unsigned)Value.getZExtValue()
13918                << !CStdConstraintViolation << DiagWidth;
13919 
13920       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13921              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13922              << DiagWidth;
13923     }
13924 
13925     // Warn on types where the user might conceivably expect to get all
13926     // specified bits as value bits: that's all integral types other than
13927     // 'bool'.
13928     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13929       if (FieldName)
13930         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13931             << FieldName << (unsigned)Value.getZExtValue()
13932             << (unsigned)TypeWidth;
13933       else
13934         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13935             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13936     }
13937   }
13938 
13939   return BitWidth;
13940 }
13941 
13942 /// ActOnField - Each field of a C struct/union is passed into this in order
13943 /// to create a FieldDecl object for it.
13944 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13945                        Declarator &D, Expr *BitfieldWidth) {
13946   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13947                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13948                                /*InitStyle=*/ICIS_NoInit, AS_public);
13949   return Res;
13950 }
13951 
13952 /// HandleField - Analyze a field of a C struct or a C++ data member.
13953 ///
13954 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13955                              SourceLocation DeclStart,
13956                              Declarator &D, Expr *BitWidth,
13957                              InClassInitStyle InitStyle,
13958                              AccessSpecifier AS) {
13959   if (D.isDecompositionDeclarator()) {
13960     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13961     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13962       << Decomp.getSourceRange();
13963     return nullptr;
13964   }
13965 
13966   IdentifierInfo *II = D.getIdentifier();
13967   SourceLocation Loc = DeclStart;
13968   if (II) Loc = D.getIdentifierLoc();
13969 
13970   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13971   QualType T = TInfo->getType();
13972   if (getLangOpts().CPlusPlus) {
13973     CheckExtraCXXDefaultArguments(D);
13974 
13975     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13976                                         UPPC_DataMemberType)) {
13977       D.setInvalidType();
13978       T = Context.IntTy;
13979       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13980     }
13981   }
13982 
13983   // TR 18037 does not allow fields to be declared with address spaces.
13984   if (T.getQualifiers().hasAddressSpace()) {
13985     Diag(Loc, diag::err_field_with_address_space);
13986     D.setInvalidType();
13987   }
13988 
13989   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13990   // used as structure or union field: image, sampler, event or block types.
13991   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13992                           T->isSamplerT() || T->isBlockPointerType())) {
13993     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13994     D.setInvalidType();
13995   }
13996 
13997   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13998 
13999   if (D.getDeclSpec().isInlineSpecified())
14000     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14001         << getLangOpts().CPlusPlus1z;
14002   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14003     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14004          diag::err_invalid_thread)
14005       << DeclSpec::getSpecifierName(TSCS);
14006 
14007   // Check to see if this name was declared as a member previously
14008   NamedDecl *PrevDecl = nullptr;
14009   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14010   LookupName(Previous, S);
14011   switch (Previous.getResultKind()) {
14012     case LookupResult::Found:
14013     case LookupResult::FoundUnresolvedValue:
14014       PrevDecl = Previous.getAsSingle<NamedDecl>();
14015       break;
14016 
14017     case LookupResult::FoundOverloaded:
14018       PrevDecl = Previous.getRepresentativeDecl();
14019       break;
14020 
14021     case LookupResult::NotFound:
14022     case LookupResult::NotFoundInCurrentInstantiation:
14023     case LookupResult::Ambiguous:
14024       break;
14025   }
14026   Previous.suppressDiagnostics();
14027 
14028   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14029     // Maybe we will complain about the shadowed template parameter.
14030     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14031     // Just pretend that we didn't see the previous declaration.
14032     PrevDecl = nullptr;
14033   }
14034 
14035   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14036     PrevDecl = nullptr;
14037 
14038   bool Mutable
14039     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14040   SourceLocation TSSL = D.getLocStart();
14041   FieldDecl *NewFD
14042     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14043                      TSSL, AS, PrevDecl, &D);
14044 
14045   if (NewFD->isInvalidDecl())
14046     Record->setInvalidDecl();
14047 
14048   if (D.getDeclSpec().isModulePrivateSpecified())
14049     NewFD->setModulePrivate();
14050 
14051   if (NewFD->isInvalidDecl() && PrevDecl) {
14052     // Don't introduce NewFD into scope; there's already something
14053     // with the same name in the same scope.
14054   } else if (II) {
14055     PushOnScopeChains(NewFD, S);
14056   } else
14057     Record->addDecl(NewFD);
14058 
14059   return NewFD;
14060 }
14061 
14062 /// \brief Build a new FieldDecl and check its well-formedness.
14063 ///
14064 /// This routine builds a new FieldDecl given the fields name, type,
14065 /// record, etc. \p PrevDecl should refer to any previous declaration
14066 /// with the same name and in the same scope as the field to be
14067 /// created.
14068 ///
14069 /// \returns a new FieldDecl.
14070 ///
14071 /// \todo The Declarator argument is a hack. It will be removed once
14072 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14073                                 TypeSourceInfo *TInfo,
14074                                 RecordDecl *Record, SourceLocation Loc,
14075                                 bool Mutable, Expr *BitWidth,
14076                                 InClassInitStyle InitStyle,
14077                                 SourceLocation TSSL,
14078                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14079                                 Declarator *D) {
14080   IdentifierInfo *II = Name.getAsIdentifierInfo();
14081   bool InvalidDecl = false;
14082   if (D) InvalidDecl = D->isInvalidType();
14083 
14084   // If we receive a broken type, recover by assuming 'int' and
14085   // marking this declaration as invalid.
14086   if (T.isNull()) {
14087     InvalidDecl = true;
14088     T = Context.IntTy;
14089   }
14090 
14091   QualType EltTy = Context.getBaseElementType(T);
14092   if (!EltTy->isDependentType()) {
14093     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14094       // Fields of incomplete type force their record to be invalid.
14095       Record->setInvalidDecl();
14096       InvalidDecl = true;
14097     } else {
14098       NamedDecl *Def;
14099       EltTy->isIncompleteType(&Def);
14100       if (Def && Def->isInvalidDecl()) {
14101         Record->setInvalidDecl();
14102         InvalidDecl = true;
14103       }
14104     }
14105   }
14106 
14107   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14108   if (BitWidth && getLangOpts().OpenCL) {
14109     Diag(Loc, diag::err_opencl_bitfields);
14110     InvalidDecl = true;
14111   }
14112 
14113   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14114   // than a variably modified type.
14115   if (!InvalidDecl && T->isVariablyModifiedType()) {
14116     bool SizeIsNegative;
14117     llvm::APSInt Oversized;
14118 
14119     TypeSourceInfo *FixedTInfo =
14120       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14121                                                     SizeIsNegative,
14122                                                     Oversized);
14123     if (FixedTInfo) {
14124       Diag(Loc, diag::warn_illegal_constant_array_size);
14125       TInfo = FixedTInfo;
14126       T = FixedTInfo->getType();
14127     } else {
14128       if (SizeIsNegative)
14129         Diag(Loc, diag::err_typecheck_negative_array_size);
14130       else if (Oversized.getBoolValue())
14131         Diag(Loc, diag::err_array_too_large)
14132           << Oversized.toString(10);
14133       else
14134         Diag(Loc, diag::err_typecheck_field_variable_size);
14135       InvalidDecl = true;
14136     }
14137   }
14138 
14139   // Fields can not have abstract class types
14140   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14141                                              diag::err_abstract_type_in_decl,
14142                                              AbstractFieldType))
14143     InvalidDecl = true;
14144 
14145   bool ZeroWidth = false;
14146   if (InvalidDecl)
14147     BitWidth = nullptr;
14148   // If this is declared as a bit-field, check the bit-field.
14149   if (BitWidth) {
14150     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14151                               &ZeroWidth).get();
14152     if (!BitWidth) {
14153       InvalidDecl = true;
14154       BitWidth = nullptr;
14155       ZeroWidth = false;
14156     }
14157   }
14158 
14159   // Check that 'mutable' is consistent with the type of the declaration.
14160   if (!InvalidDecl && Mutable) {
14161     unsigned DiagID = 0;
14162     if (T->isReferenceType())
14163       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14164                                         : diag::err_mutable_reference;
14165     else if (T.isConstQualified())
14166       DiagID = diag::err_mutable_const;
14167 
14168     if (DiagID) {
14169       SourceLocation ErrLoc = Loc;
14170       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14171         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14172       Diag(ErrLoc, DiagID);
14173       if (DiagID != diag::ext_mutable_reference) {
14174         Mutable = false;
14175         InvalidDecl = true;
14176       }
14177     }
14178   }
14179 
14180   // C++11 [class.union]p8 (DR1460):
14181   //   At most one variant member of a union may have a
14182   //   brace-or-equal-initializer.
14183   if (InitStyle != ICIS_NoInit)
14184     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14185 
14186   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14187                                        BitWidth, Mutable, InitStyle);
14188   if (InvalidDecl)
14189     NewFD->setInvalidDecl();
14190 
14191   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14192     Diag(Loc, diag::err_duplicate_member) << II;
14193     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14194     NewFD->setInvalidDecl();
14195   }
14196 
14197   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14198     if (Record->isUnion()) {
14199       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14200         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14201         if (RDecl->getDefinition()) {
14202           // C++ [class.union]p1: An object of a class with a non-trivial
14203           // constructor, a non-trivial copy constructor, a non-trivial
14204           // destructor, or a non-trivial copy assignment operator
14205           // cannot be a member of a union, nor can an array of such
14206           // objects.
14207           if (CheckNontrivialField(NewFD))
14208             NewFD->setInvalidDecl();
14209         }
14210       }
14211 
14212       // C++ [class.union]p1: If a union contains a member of reference type,
14213       // the program is ill-formed, except when compiling with MSVC extensions
14214       // enabled.
14215       if (EltTy->isReferenceType()) {
14216         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14217                                     diag::ext_union_member_of_reference_type :
14218                                     diag::err_union_member_of_reference_type)
14219           << NewFD->getDeclName() << EltTy;
14220         if (!getLangOpts().MicrosoftExt)
14221           NewFD->setInvalidDecl();
14222       }
14223     }
14224   }
14225 
14226   // FIXME: We need to pass in the attributes given an AST
14227   // representation, not a parser representation.
14228   if (D) {
14229     // FIXME: The current scope is almost... but not entirely... correct here.
14230     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14231 
14232     if (NewFD->hasAttrs())
14233       CheckAlignasUnderalignment(NewFD);
14234   }
14235 
14236   // In auto-retain/release, infer strong retension for fields of
14237   // retainable type.
14238   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14239     NewFD->setInvalidDecl();
14240 
14241   if (T.isObjCGCWeak())
14242     Diag(Loc, diag::warn_attribute_weak_on_field);
14243 
14244   NewFD->setAccess(AS);
14245   return NewFD;
14246 }
14247 
14248 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14249   assert(FD);
14250   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14251 
14252   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14253     return false;
14254 
14255   QualType EltTy = Context.getBaseElementType(FD->getType());
14256   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14257     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14258     if (RDecl->getDefinition()) {
14259       // We check for copy constructors before constructors
14260       // because otherwise we'll never get complaints about
14261       // copy constructors.
14262 
14263       CXXSpecialMember member = CXXInvalid;
14264       // We're required to check for any non-trivial constructors. Since the
14265       // implicit default constructor is suppressed if there are any
14266       // user-declared constructors, we just need to check that there is a
14267       // trivial default constructor and a trivial copy constructor. (We don't
14268       // worry about move constructors here, since this is a C++98 check.)
14269       if (RDecl->hasNonTrivialCopyConstructor())
14270         member = CXXCopyConstructor;
14271       else if (!RDecl->hasTrivialDefaultConstructor())
14272         member = CXXDefaultConstructor;
14273       else if (RDecl->hasNonTrivialCopyAssignment())
14274         member = CXXCopyAssignment;
14275       else if (RDecl->hasNonTrivialDestructor())
14276         member = CXXDestructor;
14277 
14278       if (member != CXXInvalid) {
14279         if (!getLangOpts().CPlusPlus11 &&
14280             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14281           // Objective-C++ ARC: it is an error to have a non-trivial field of
14282           // a union. However, system headers in Objective-C programs
14283           // occasionally have Objective-C lifetime objects within unions,
14284           // and rather than cause the program to fail, we make those
14285           // members unavailable.
14286           SourceLocation Loc = FD->getLocation();
14287           if (getSourceManager().isInSystemHeader(Loc)) {
14288             if (!FD->hasAttr<UnavailableAttr>())
14289               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14290                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14291             return false;
14292           }
14293         }
14294 
14295         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14296                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14297                diag::err_illegal_union_or_anon_struct_member)
14298           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14299         DiagnoseNontrivial(RDecl, member);
14300         return !getLangOpts().CPlusPlus11;
14301       }
14302     }
14303   }
14304 
14305   return false;
14306 }
14307 
14308 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14309 ///  AST enum value.
14310 static ObjCIvarDecl::AccessControl
14311 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14312   switch (ivarVisibility) {
14313   default: llvm_unreachable("Unknown visitibility kind");
14314   case tok::objc_private: return ObjCIvarDecl::Private;
14315   case tok::objc_public: return ObjCIvarDecl::Public;
14316   case tok::objc_protected: return ObjCIvarDecl::Protected;
14317   case tok::objc_package: return ObjCIvarDecl::Package;
14318   }
14319 }
14320 
14321 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14322 /// in order to create an IvarDecl object for it.
14323 Decl *Sema::ActOnIvar(Scope *S,
14324                                 SourceLocation DeclStart,
14325                                 Declarator &D, Expr *BitfieldWidth,
14326                                 tok::ObjCKeywordKind Visibility) {
14327 
14328   IdentifierInfo *II = D.getIdentifier();
14329   Expr *BitWidth = (Expr*)BitfieldWidth;
14330   SourceLocation Loc = DeclStart;
14331   if (II) Loc = D.getIdentifierLoc();
14332 
14333   // FIXME: Unnamed fields can be handled in various different ways, for
14334   // example, unnamed unions inject all members into the struct namespace!
14335 
14336   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14337   QualType T = TInfo->getType();
14338 
14339   if (BitWidth) {
14340     // 6.7.2.1p3, 6.7.2.1p4
14341     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14342     if (!BitWidth)
14343       D.setInvalidType();
14344   } else {
14345     // Not a bitfield.
14346 
14347     // validate II.
14348 
14349   }
14350   if (T->isReferenceType()) {
14351     Diag(Loc, diag::err_ivar_reference_type);
14352     D.setInvalidType();
14353   }
14354   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14355   // than a variably modified type.
14356   else if (T->isVariablyModifiedType()) {
14357     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14358     D.setInvalidType();
14359   }
14360 
14361   // Get the visibility (access control) for this ivar.
14362   ObjCIvarDecl::AccessControl ac =
14363     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14364                                         : ObjCIvarDecl::None;
14365   // Must set ivar's DeclContext to its enclosing interface.
14366   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14367   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14368     return nullptr;
14369   ObjCContainerDecl *EnclosingContext;
14370   if (ObjCImplementationDecl *IMPDecl =
14371       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14372     if (LangOpts.ObjCRuntime.isFragile()) {
14373     // Case of ivar declared in an implementation. Context is that of its class.
14374       EnclosingContext = IMPDecl->getClassInterface();
14375       assert(EnclosingContext && "Implementation has no class interface!");
14376     }
14377     else
14378       EnclosingContext = EnclosingDecl;
14379   } else {
14380     if (ObjCCategoryDecl *CDecl =
14381         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14382       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14383         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14384         return nullptr;
14385       }
14386     }
14387     EnclosingContext = EnclosingDecl;
14388   }
14389 
14390   // Construct the decl.
14391   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14392                                              DeclStart, Loc, II, T,
14393                                              TInfo, ac, (Expr *)BitfieldWidth);
14394 
14395   if (II) {
14396     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14397                                            ForRedeclaration);
14398     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14399         && !isa<TagDecl>(PrevDecl)) {
14400       Diag(Loc, diag::err_duplicate_member) << II;
14401       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14402       NewID->setInvalidDecl();
14403     }
14404   }
14405 
14406   // Process attributes attached to the ivar.
14407   ProcessDeclAttributes(S, NewID, D);
14408 
14409   if (D.isInvalidType())
14410     NewID->setInvalidDecl();
14411 
14412   // In ARC, infer 'retaining' for ivars of retainable type.
14413   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14414     NewID->setInvalidDecl();
14415 
14416   if (D.getDeclSpec().isModulePrivateSpecified())
14417     NewID->setModulePrivate();
14418 
14419   if (II) {
14420     // FIXME: When interfaces are DeclContexts, we'll need to add
14421     // these to the interface.
14422     S->AddDecl(NewID);
14423     IdResolver.AddDecl(NewID);
14424   }
14425 
14426   if (LangOpts.ObjCRuntime.isNonFragile() &&
14427       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14428     Diag(Loc, diag::warn_ivars_in_interface);
14429 
14430   return NewID;
14431 }
14432 
14433 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14434 /// class and class extensions. For every class \@interface and class
14435 /// extension \@interface, if the last ivar is a bitfield of any type,
14436 /// then add an implicit `char :0` ivar to the end of that interface.
14437 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14438                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14439   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14440     return;
14441 
14442   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14443   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14444 
14445   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14446     return;
14447   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14448   if (!ID) {
14449     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14450       if (!CD->IsClassExtension())
14451         return;
14452     }
14453     // No need to add this to end of @implementation.
14454     else
14455       return;
14456   }
14457   // All conditions are met. Add a new bitfield to the tail end of ivars.
14458   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14459   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14460 
14461   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14462                               DeclLoc, DeclLoc, nullptr,
14463                               Context.CharTy,
14464                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14465                                                                DeclLoc),
14466                               ObjCIvarDecl::Private, BW,
14467                               true);
14468   AllIvarDecls.push_back(Ivar);
14469 }
14470 
14471 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14472                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14473                        SourceLocation RBrac, AttributeList *Attr) {
14474   assert(EnclosingDecl && "missing record or interface decl");
14475 
14476   // If this is an Objective-C @implementation or category and we have
14477   // new fields here we should reset the layout of the interface since
14478   // it will now change.
14479   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14480     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14481     switch (DC->getKind()) {
14482     default: break;
14483     case Decl::ObjCCategory:
14484       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14485       break;
14486     case Decl::ObjCImplementation:
14487       Context.
14488         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14489       break;
14490     }
14491   }
14492 
14493   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14494 
14495   // Start counting up the number of named members; make sure to include
14496   // members of anonymous structs and unions in the total.
14497   unsigned NumNamedMembers = 0;
14498   if (Record) {
14499     for (const auto *I : Record->decls()) {
14500       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14501         if (IFD->getDeclName())
14502           ++NumNamedMembers;
14503     }
14504   }
14505 
14506   // Verify that all the fields are okay.
14507   SmallVector<FieldDecl*, 32> RecFields;
14508 
14509   bool ObjCFieldLifetimeErrReported = false;
14510   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14511        i != end; ++i) {
14512     FieldDecl *FD = cast<FieldDecl>(*i);
14513 
14514     // Get the type for the field.
14515     const Type *FDTy = FD->getType().getTypePtr();
14516 
14517     if (!FD->isAnonymousStructOrUnion()) {
14518       // Remember all fields written by the user.
14519       RecFields.push_back(FD);
14520     }
14521 
14522     // If the field is already invalid for some reason, don't emit more
14523     // diagnostics about it.
14524     if (FD->isInvalidDecl()) {
14525       EnclosingDecl->setInvalidDecl();
14526       continue;
14527     }
14528 
14529     // C99 6.7.2.1p2:
14530     //   A structure or union shall not contain a member with
14531     //   incomplete or function type (hence, a structure shall not
14532     //   contain an instance of itself, but may contain a pointer to
14533     //   an instance of itself), except that the last member of a
14534     //   structure with more than one named member may have incomplete
14535     //   array type; such a structure (and any union containing,
14536     //   possibly recursively, a member that is such a structure)
14537     //   shall not be a member of a structure or an element of an
14538     //   array.
14539     if (FDTy->isFunctionType()) {
14540       // Field declared as a function.
14541       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14542         << FD->getDeclName();
14543       FD->setInvalidDecl();
14544       EnclosingDecl->setInvalidDecl();
14545       continue;
14546     } else if (FDTy->isIncompleteArrayType() && Record &&
14547                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14548                 ((getLangOpts().MicrosoftExt ||
14549                   getLangOpts().CPlusPlus) &&
14550                  (i + 1 == Fields.end() || Record->isUnion())))) {
14551       // Flexible array member.
14552       // Microsoft and g++ is more permissive regarding flexible array.
14553       // It will accept flexible array in union and also
14554       // as the sole element of a struct/class.
14555       unsigned DiagID = 0;
14556       if (Record->isUnion())
14557         DiagID = getLangOpts().MicrosoftExt
14558                      ? diag::ext_flexible_array_union_ms
14559                      : getLangOpts().CPlusPlus
14560                            ? diag::ext_flexible_array_union_gnu
14561                            : diag::err_flexible_array_union;
14562       else if (NumNamedMembers < 1)
14563         DiagID = getLangOpts().MicrosoftExt
14564                      ? diag::ext_flexible_array_empty_aggregate_ms
14565                      : getLangOpts().CPlusPlus
14566                            ? diag::ext_flexible_array_empty_aggregate_gnu
14567                            : diag::err_flexible_array_empty_aggregate;
14568 
14569       if (DiagID)
14570         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14571                                         << Record->getTagKind();
14572       // While the layout of types that contain virtual bases is not specified
14573       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14574       // virtual bases after the derived members.  This would make a flexible
14575       // array member declared at the end of an object not adjacent to the end
14576       // of the type.
14577       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14578         if (RD->getNumVBases() != 0)
14579           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14580             << FD->getDeclName() << Record->getTagKind();
14581       if (!getLangOpts().C99)
14582         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14583           << FD->getDeclName() << Record->getTagKind();
14584 
14585       // If the element type has a non-trivial destructor, we would not
14586       // implicitly destroy the elements, so disallow it for now.
14587       //
14588       // FIXME: GCC allows this. We should probably either implicitly delete
14589       // the destructor of the containing class, or just allow this.
14590       QualType BaseElem = Context.getBaseElementType(FD->getType());
14591       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14592         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14593           << FD->getDeclName() << FD->getType();
14594         FD->setInvalidDecl();
14595         EnclosingDecl->setInvalidDecl();
14596         continue;
14597       }
14598       // Okay, we have a legal flexible array member at the end of the struct.
14599       Record->setHasFlexibleArrayMember(true);
14600     } else if (!FDTy->isDependentType() &&
14601                RequireCompleteType(FD->getLocation(), FD->getType(),
14602                                    diag::err_field_incomplete)) {
14603       // Incomplete type
14604       FD->setInvalidDecl();
14605       EnclosingDecl->setInvalidDecl();
14606       continue;
14607     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14608       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14609         // A type which contains a flexible array member is considered to be a
14610         // flexible array member.
14611         Record->setHasFlexibleArrayMember(true);
14612         if (!Record->isUnion()) {
14613           // If this is a struct/class and this is not the last element, reject
14614           // it.  Note that GCC supports variable sized arrays in the middle of
14615           // structures.
14616           if (i + 1 != Fields.end())
14617             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14618               << FD->getDeclName() << FD->getType();
14619           else {
14620             // We support flexible arrays at the end of structs in
14621             // other structs as an extension.
14622             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14623               << FD->getDeclName();
14624           }
14625         }
14626       }
14627       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14628           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14629                                  diag::err_abstract_type_in_decl,
14630                                  AbstractIvarType)) {
14631         // Ivars can not have abstract class types
14632         FD->setInvalidDecl();
14633       }
14634       if (Record && FDTTy->getDecl()->hasObjectMember())
14635         Record->setHasObjectMember(true);
14636       if (Record && FDTTy->getDecl()->hasVolatileMember())
14637         Record->setHasVolatileMember(true);
14638     } else if (FDTy->isObjCObjectType()) {
14639       /// A field cannot be an Objective-c object
14640       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14641         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14642       QualType T = Context.getObjCObjectPointerType(FD->getType());
14643       FD->setType(T);
14644     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14645                Record && !ObjCFieldLifetimeErrReported &&
14646                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14647       // It's an error in ARC or Weak if a field has lifetime.
14648       // We don't want to report this in a system header, though,
14649       // so we just make the field unavailable.
14650       // FIXME: that's really not sufficient; we need to make the type
14651       // itself invalid to, say, initialize or copy.
14652       QualType T = FD->getType();
14653       if (T.hasNonTrivialObjCLifetime()) {
14654         SourceLocation loc = FD->getLocation();
14655         if (getSourceManager().isInSystemHeader(loc)) {
14656           if (!FD->hasAttr<UnavailableAttr>()) {
14657             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14658                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14659           }
14660         } else {
14661           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14662             << T->isBlockPointerType() << Record->getTagKind();
14663         }
14664         ObjCFieldLifetimeErrReported = true;
14665       }
14666     } else if (getLangOpts().ObjC1 &&
14667                getLangOpts().getGC() != LangOptions::NonGC &&
14668                Record && !Record->hasObjectMember()) {
14669       if (FD->getType()->isObjCObjectPointerType() ||
14670           FD->getType().isObjCGCStrong())
14671         Record->setHasObjectMember(true);
14672       else if (Context.getAsArrayType(FD->getType())) {
14673         QualType BaseType = Context.getBaseElementType(FD->getType());
14674         if (BaseType->isRecordType() &&
14675             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14676           Record->setHasObjectMember(true);
14677         else if (BaseType->isObjCObjectPointerType() ||
14678                  BaseType.isObjCGCStrong())
14679                Record->setHasObjectMember(true);
14680       }
14681     }
14682     if (Record && FD->getType().isVolatileQualified())
14683       Record->setHasVolatileMember(true);
14684     // Keep track of the number of named members.
14685     if (FD->getIdentifier())
14686       ++NumNamedMembers;
14687   }
14688 
14689   // Okay, we successfully defined 'Record'.
14690   if (Record) {
14691     bool Completed = false;
14692     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14693       if (!CXXRecord->isInvalidDecl()) {
14694         // Set access bits correctly on the directly-declared conversions.
14695         for (CXXRecordDecl::conversion_iterator
14696                I = CXXRecord->conversion_begin(),
14697                E = CXXRecord->conversion_end(); I != E; ++I)
14698           I.setAccess((*I)->getAccess());
14699       }
14700 
14701       if (!CXXRecord->isDependentType()) {
14702         if (CXXRecord->hasUserDeclaredDestructor()) {
14703           // Adjust user-defined destructor exception spec.
14704           if (getLangOpts().CPlusPlus11)
14705             AdjustDestructorExceptionSpec(CXXRecord,
14706                                           CXXRecord->getDestructor());
14707         }
14708 
14709         if (!CXXRecord->isInvalidDecl()) {
14710           // Add any implicitly-declared members to this class.
14711           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14712 
14713           // If we have virtual base classes, we may end up finding multiple
14714           // final overriders for a given virtual function. Check for this
14715           // problem now.
14716           if (CXXRecord->getNumVBases()) {
14717             CXXFinalOverriderMap FinalOverriders;
14718             CXXRecord->getFinalOverriders(FinalOverriders);
14719 
14720             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14721                                              MEnd = FinalOverriders.end();
14722                  M != MEnd; ++M) {
14723               for (OverridingMethods::iterator SO = M->second.begin(),
14724                                             SOEnd = M->second.end();
14725                    SO != SOEnd; ++SO) {
14726                 assert(SO->second.size() > 0 &&
14727                        "Virtual function without overridding functions?");
14728                 if (SO->second.size() == 1)
14729                   continue;
14730 
14731                 // C++ [class.virtual]p2:
14732                 //   In a derived class, if a virtual member function of a base
14733                 //   class subobject has more than one final overrider the
14734                 //   program is ill-formed.
14735                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14736                   << (const NamedDecl *)M->first << Record;
14737                 Diag(M->first->getLocation(),
14738                      diag::note_overridden_virtual_function);
14739                 for (OverridingMethods::overriding_iterator
14740                           OM = SO->second.begin(),
14741                        OMEnd = SO->second.end();
14742                      OM != OMEnd; ++OM)
14743                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14744                     << (const NamedDecl *)M->first << OM->Method->getParent();
14745 
14746                 Record->setInvalidDecl();
14747               }
14748             }
14749             CXXRecord->completeDefinition(&FinalOverriders);
14750             Completed = true;
14751           }
14752         }
14753       }
14754     }
14755 
14756     if (!Completed)
14757       Record->completeDefinition();
14758 
14759     // We may have deferred checking for a deleted destructor. Check now.
14760     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14761       auto *Dtor = CXXRecord->getDestructor();
14762       if (Dtor && Dtor->isImplicit() &&
14763           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14764         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14765     }
14766 
14767     if (Record->hasAttrs()) {
14768       CheckAlignasUnderalignment(Record);
14769 
14770       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14771         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14772                                            IA->getRange(), IA->getBestCase(),
14773                                            IA->getSemanticSpelling());
14774     }
14775 
14776     // Check if the structure/union declaration is a type that can have zero
14777     // size in C. For C this is a language extension, for C++ it may cause
14778     // compatibility problems.
14779     bool CheckForZeroSize;
14780     if (!getLangOpts().CPlusPlus) {
14781       CheckForZeroSize = true;
14782     } else {
14783       // For C++ filter out types that cannot be referenced in C code.
14784       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14785       CheckForZeroSize =
14786           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14787           !CXXRecord->isDependentType() &&
14788           CXXRecord->isCLike();
14789     }
14790     if (CheckForZeroSize) {
14791       bool ZeroSize = true;
14792       bool IsEmpty = true;
14793       unsigned NonBitFields = 0;
14794       for (RecordDecl::field_iterator I = Record->field_begin(),
14795                                       E = Record->field_end();
14796            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14797         IsEmpty = false;
14798         if (I->isUnnamedBitfield()) {
14799           if (I->getBitWidthValue(Context) > 0)
14800             ZeroSize = false;
14801         } else {
14802           ++NonBitFields;
14803           QualType FieldType = I->getType();
14804           if (FieldType->isIncompleteType() ||
14805               !Context.getTypeSizeInChars(FieldType).isZero())
14806             ZeroSize = false;
14807         }
14808       }
14809 
14810       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14811       // allowed in C++, but warn if its declaration is inside
14812       // extern "C" block.
14813       if (ZeroSize) {
14814         Diag(RecLoc, getLangOpts().CPlusPlus ?
14815                          diag::warn_zero_size_struct_union_in_extern_c :
14816                          diag::warn_zero_size_struct_union_compat)
14817           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14818       }
14819 
14820       // Structs without named members are extension in C (C99 6.7.2.1p7),
14821       // but are accepted by GCC.
14822       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14823         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14824                                diag::ext_no_named_members_in_struct_union)
14825           << Record->isUnion();
14826       }
14827     }
14828   } else {
14829     ObjCIvarDecl **ClsFields =
14830       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14831     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14832       ID->setEndOfDefinitionLoc(RBrac);
14833       // Add ivar's to class's DeclContext.
14834       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14835         ClsFields[i]->setLexicalDeclContext(ID);
14836         ID->addDecl(ClsFields[i]);
14837       }
14838       // Must enforce the rule that ivars in the base classes may not be
14839       // duplicates.
14840       if (ID->getSuperClass())
14841         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14842     } else if (ObjCImplementationDecl *IMPDecl =
14843                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14844       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14845       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14846         // Ivar declared in @implementation never belongs to the implementation.
14847         // Only it is in implementation's lexical context.
14848         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14849       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14850       IMPDecl->setIvarLBraceLoc(LBrac);
14851       IMPDecl->setIvarRBraceLoc(RBrac);
14852     } else if (ObjCCategoryDecl *CDecl =
14853                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14854       // case of ivars in class extension; all other cases have been
14855       // reported as errors elsewhere.
14856       // FIXME. Class extension does not have a LocEnd field.
14857       // CDecl->setLocEnd(RBrac);
14858       // Add ivar's to class extension's DeclContext.
14859       // Diagnose redeclaration of private ivars.
14860       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14861       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14862         if (IDecl) {
14863           if (const ObjCIvarDecl *ClsIvar =
14864               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14865             Diag(ClsFields[i]->getLocation(),
14866                  diag::err_duplicate_ivar_declaration);
14867             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14868             continue;
14869           }
14870           for (const auto *Ext : IDecl->known_extensions()) {
14871             if (const ObjCIvarDecl *ClsExtIvar
14872                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14873               Diag(ClsFields[i]->getLocation(),
14874                    diag::err_duplicate_ivar_declaration);
14875               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14876               continue;
14877             }
14878           }
14879         }
14880         ClsFields[i]->setLexicalDeclContext(CDecl);
14881         CDecl->addDecl(ClsFields[i]);
14882       }
14883       CDecl->setIvarLBraceLoc(LBrac);
14884       CDecl->setIvarRBraceLoc(RBrac);
14885     }
14886   }
14887 
14888   if (Attr)
14889     ProcessDeclAttributeList(S, Record, Attr);
14890 }
14891 
14892 /// \brief Determine whether the given integral value is representable within
14893 /// the given type T.
14894 static bool isRepresentableIntegerValue(ASTContext &Context,
14895                                         llvm::APSInt &Value,
14896                                         QualType T) {
14897   assert(T->isIntegralType(Context) && "Integral type required!");
14898   unsigned BitWidth = Context.getIntWidth(T);
14899 
14900   if (Value.isUnsigned() || Value.isNonNegative()) {
14901     if (T->isSignedIntegerOrEnumerationType())
14902       --BitWidth;
14903     return Value.getActiveBits() <= BitWidth;
14904   }
14905   return Value.getMinSignedBits() <= BitWidth;
14906 }
14907 
14908 // \brief Given an integral type, return the next larger integral type
14909 // (or a NULL type of no such type exists).
14910 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14911   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14912   // enum checking below.
14913   assert(T->isIntegralType(Context) && "Integral type required!");
14914   const unsigned NumTypes = 4;
14915   QualType SignedIntegralTypes[NumTypes] = {
14916     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14917   };
14918   QualType UnsignedIntegralTypes[NumTypes] = {
14919     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14920     Context.UnsignedLongLongTy
14921   };
14922 
14923   unsigned BitWidth = Context.getTypeSize(T);
14924   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14925                                                         : UnsignedIntegralTypes;
14926   for (unsigned I = 0; I != NumTypes; ++I)
14927     if (Context.getTypeSize(Types[I]) > BitWidth)
14928       return Types[I];
14929 
14930   return QualType();
14931 }
14932 
14933 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14934                                           EnumConstantDecl *LastEnumConst,
14935                                           SourceLocation IdLoc,
14936                                           IdentifierInfo *Id,
14937                                           Expr *Val) {
14938   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14939   llvm::APSInt EnumVal(IntWidth);
14940   QualType EltTy;
14941 
14942   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14943     Val = nullptr;
14944 
14945   if (Val)
14946     Val = DefaultLvalueConversion(Val).get();
14947 
14948   if (Val) {
14949     if (Enum->isDependentType() || Val->isTypeDependent())
14950       EltTy = Context.DependentTy;
14951     else {
14952       SourceLocation ExpLoc;
14953       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14954           !getLangOpts().MSVCCompat) {
14955         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14956         // constant-expression in the enumerator-definition shall be a converted
14957         // constant expression of the underlying type.
14958         EltTy = Enum->getIntegerType();
14959         ExprResult Converted =
14960           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14961                                            CCEK_Enumerator);
14962         if (Converted.isInvalid())
14963           Val = nullptr;
14964         else
14965           Val = Converted.get();
14966       } else if (!Val->isValueDependent() &&
14967                  !(Val = VerifyIntegerConstantExpression(Val,
14968                                                          &EnumVal).get())) {
14969         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14970       } else {
14971         if (Enum->isFixed()) {
14972           EltTy = Enum->getIntegerType();
14973 
14974           // In Obj-C and Microsoft mode, require the enumeration value to be
14975           // representable in the underlying type of the enumeration. In C++11,
14976           // we perform a non-narrowing conversion as part of converted constant
14977           // expression checking.
14978           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14979             if (getLangOpts().MSVCCompat) {
14980               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14981               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14982             } else
14983               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14984           } else
14985             Val = ImpCastExprToType(Val, EltTy,
14986                                     EltTy->isBooleanType() ?
14987                                     CK_IntegralToBoolean : CK_IntegralCast)
14988                     .get();
14989         } else if (getLangOpts().CPlusPlus) {
14990           // C++11 [dcl.enum]p5:
14991           //   If the underlying type is not fixed, the type of each enumerator
14992           //   is the type of its initializing value:
14993           //     - If an initializer is specified for an enumerator, the
14994           //       initializing value has the same type as the expression.
14995           EltTy = Val->getType();
14996         } else {
14997           // C99 6.7.2.2p2:
14998           //   The expression that defines the value of an enumeration constant
14999           //   shall be an integer constant expression that has a value
15000           //   representable as an int.
15001 
15002           // Complain if the value is not representable in an int.
15003           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15004             Diag(IdLoc, diag::ext_enum_value_not_int)
15005               << EnumVal.toString(10) << Val->getSourceRange()
15006               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15007           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15008             // Force the type of the expression to 'int'.
15009             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15010           }
15011           EltTy = Val->getType();
15012         }
15013       }
15014     }
15015   }
15016 
15017   if (!Val) {
15018     if (Enum->isDependentType())
15019       EltTy = Context.DependentTy;
15020     else if (!LastEnumConst) {
15021       // C++0x [dcl.enum]p5:
15022       //   If the underlying type is not fixed, the type of each enumerator
15023       //   is the type of its initializing value:
15024       //     - If no initializer is specified for the first enumerator, the
15025       //       initializing value has an unspecified integral type.
15026       //
15027       // GCC uses 'int' for its unspecified integral type, as does
15028       // C99 6.7.2.2p3.
15029       if (Enum->isFixed()) {
15030         EltTy = Enum->getIntegerType();
15031       }
15032       else {
15033         EltTy = Context.IntTy;
15034       }
15035     } else {
15036       // Assign the last value + 1.
15037       EnumVal = LastEnumConst->getInitVal();
15038       ++EnumVal;
15039       EltTy = LastEnumConst->getType();
15040 
15041       // Check for overflow on increment.
15042       if (EnumVal < LastEnumConst->getInitVal()) {
15043         // C++0x [dcl.enum]p5:
15044         //   If the underlying type is not fixed, the type of each enumerator
15045         //   is the type of its initializing value:
15046         //
15047         //     - Otherwise the type of the initializing value is the same as
15048         //       the type of the initializing value of the preceding enumerator
15049         //       unless the incremented value is not representable in that type,
15050         //       in which case the type is an unspecified integral type
15051         //       sufficient to contain the incremented value. If no such type
15052         //       exists, the program is ill-formed.
15053         QualType T = getNextLargerIntegralType(Context, EltTy);
15054         if (T.isNull() || Enum->isFixed()) {
15055           // There is no integral type larger enough to represent this
15056           // value. Complain, then allow the value to wrap around.
15057           EnumVal = LastEnumConst->getInitVal();
15058           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15059           ++EnumVal;
15060           if (Enum->isFixed())
15061             // When the underlying type is fixed, this is ill-formed.
15062             Diag(IdLoc, diag::err_enumerator_wrapped)
15063               << EnumVal.toString(10)
15064               << EltTy;
15065           else
15066             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15067               << EnumVal.toString(10);
15068         } else {
15069           EltTy = T;
15070         }
15071 
15072         // Retrieve the last enumerator's value, extent that type to the
15073         // type that is supposed to be large enough to represent the incremented
15074         // value, then increment.
15075         EnumVal = LastEnumConst->getInitVal();
15076         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15077         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15078         ++EnumVal;
15079 
15080         // If we're not in C++, diagnose the overflow of enumerator values,
15081         // which in C99 means that the enumerator value is not representable in
15082         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15083         // permits enumerator values that are representable in some larger
15084         // integral type.
15085         if (!getLangOpts().CPlusPlus && !T.isNull())
15086           Diag(IdLoc, diag::warn_enum_value_overflow);
15087       } else if (!getLangOpts().CPlusPlus &&
15088                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15089         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15090         Diag(IdLoc, diag::ext_enum_value_not_int)
15091           << EnumVal.toString(10) << 1;
15092       }
15093     }
15094   }
15095 
15096   if (!EltTy->isDependentType()) {
15097     // Make the enumerator value match the signedness and size of the
15098     // enumerator's type.
15099     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15100     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15101   }
15102 
15103   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15104                                   Val, EnumVal);
15105 }
15106 
15107 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15108                                                 SourceLocation IILoc) {
15109   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15110       !getLangOpts().CPlusPlus)
15111     return SkipBodyInfo();
15112 
15113   // We have an anonymous enum definition. Look up the first enumerator to
15114   // determine if we should merge the definition with an existing one and
15115   // skip the body.
15116   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15117                                          ForRedeclaration);
15118   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15119   if (!PrevECD)
15120     return SkipBodyInfo();
15121 
15122   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15123   NamedDecl *Hidden;
15124   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15125     SkipBodyInfo Skip;
15126     Skip.Previous = Hidden;
15127     return Skip;
15128   }
15129 
15130   return SkipBodyInfo();
15131 }
15132 
15133 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15134                               SourceLocation IdLoc, IdentifierInfo *Id,
15135                               AttributeList *Attr,
15136                               SourceLocation EqualLoc, Expr *Val) {
15137   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15138   EnumConstantDecl *LastEnumConst =
15139     cast_or_null<EnumConstantDecl>(lastEnumConst);
15140 
15141   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15142   // we find one that is.
15143   S = getNonFieldDeclScope(S);
15144 
15145   // Verify that there isn't already something declared with this name in this
15146   // scope.
15147   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15148                                          ForRedeclaration);
15149   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15150     // Maybe we will complain about the shadowed template parameter.
15151     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15152     // Just pretend that we didn't see the previous declaration.
15153     PrevDecl = nullptr;
15154   }
15155 
15156   // C++ [class.mem]p15:
15157   // If T is the name of a class, then each of the following shall have a name
15158   // different from T:
15159   // - every enumerator of every member of class T that is an unscoped
15160   // enumerated type
15161   if (!TheEnumDecl->isScoped())
15162     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15163                             DeclarationNameInfo(Id, IdLoc));
15164 
15165   EnumConstantDecl *New =
15166     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15167   if (!New)
15168     return nullptr;
15169 
15170   if (PrevDecl) {
15171     // When in C++, we may get a TagDecl with the same name; in this case the
15172     // enum constant will 'hide' the tag.
15173     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15174            "Received TagDecl when not in C++!");
15175     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15176         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15177       if (isa<EnumConstantDecl>(PrevDecl))
15178         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15179       else
15180         Diag(IdLoc, diag::err_redefinition) << Id;
15181       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15182       return nullptr;
15183     }
15184   }
15185 
15186   // Process attributes.
15187   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15188 
15189   // Register this decl in the current scope stack.
15190   New->setAccess(TheEnumDecl->getAccess());
15191   PushOnScopeChains(New, S);
15192 
15193   ActOnDocumentableDecl(New);
15194 
15195   return New;
15196 }
15197 
15198 // Returns true when the enum initial expression does not trigger the
15199 // duplicate enum warning.  A few common cases are exempted as follows:
15200 // Element2 = Element1
15201 // Element2 = Element1 + 1
15202 // Element2 = Element1 - 1
15203 // Where Element2 and Element1 are from the same enum.
15204 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15205   Expr *InitExpr = ECD->getInitExpr();
15206   if (!InitExpr)
15207     return true;
15208   InitExpr = InitExpr->IgnoreImpCasts();
15209 
15210   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15211     if (!BO->isAdditiveOp())
15212       return true;
15213     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15214     if (!IL)
15215       return true;
15216     if (IL->getValue() != 1)
15217       return true;
15218 
15219     InitExpr = BO->getLHS();
15220   }
15221 
15222   // This checks if the elements are from the same enum.
15223   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15224   if (!DRE)
15225     return true;
15226 
15227   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15228   if (!EnumConstant)
15229     return true;
15230 
15231   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15232       Enum)
15233     return true;
15234 
15235   return false;
15236 }
15237 
15238 namespace {
15239 struct DupKey {
15240   int64_t val;
15241   bool isTombstoneOrEmptyKey;
15242   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15243     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15244 };
15245 
15246 static DupKey GetDupKey(const llvm::APSInt& Val) {
15247   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15248                 false);
15249 }
15250 
15251 struct DenseMapInfoDupKey {
15252   static DupKey getEmptyKey() { return DupKey(0, true); }
15253   static DupKey getTombstoneKey() { return DupKey(1, true); }
15254   static unsigned getHashValue(const DupKey Key) {
15255     return (unsigned)(Key.val * 37);
15256   }
15257   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15258     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15259            LHS.val == RHS.val;
15260   }
15261 };
15262 } // end anonymous namespace
15263 
15264 // Emits a warning when an element is implicitly set a value that
15265 // a previous element has already been set to.
15266 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15267                                         EnumDecl *Enum,
15268                                         QualType EnumType) {
15269   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15270     return;
15271   // Avoid anonymous enums
15272   if (!Enum->getIdentifier())
15273     return;
15274 
15275   // Only check for small enums.
15276   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15277     return;
15278 
15279   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15280   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15281 
15282   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15283   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15284           ValueToVectorMap;
15285 
15286   DuplicatesVector DupVector;
15287   ValueToVectorMap EnumMap;
15288 
15289   // Populate the EnumMap with all values represented by enum constants without
15290   // an initialier.
15291   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15292     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15293 
15294     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15295     // this constant.  Skip this enum since it may be ill-formed.
15296     if (!ECD) {
15297       return;
15298     }
15299 
15300     if (ECD->getInitExpr())
15301       continue;
15302 
15303     DupKey Key = GetDupKey(ECD->getInitVal());
15304     DeclOrVector &Entry = EnumMap[Key];
15305 
15306     // First time encountering this value.
15307     if (Entry.isNull())
15308       Entry = ECD;
15309   }
15310 
15311   // Create vectors for any values that has duplicates.
15312   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15313     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15314     if (!ValidDuplicateEnum(ECD, Enum))
15315       continue;
15316 
15317     DupKey Key = GetDupKey(ECD->getInitVal());
15318 
15319     DeclOrVector& Entry = EnumMap[Key];
15320     if (Entry.isNull())
15321       continue;
15322 
15323     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15324       // Ensure constants are different.
15325       if (D == ECD)
15326         continue;
15327 
15328       // Create new vector and push values onto it.
15329       ECDVector *Vec = new ECDVector();
15330       Vec->push_back(D);
15331       Vec->push_back(ECD);
15332 
15333       // Update entry to point to the duplicates vector.
15334       Entry = Vec;
15335 
15336       // Store the vector somewhere we can consult later for quick emission of
15337       // diagnostics.
15338       DupVector.push_back(Vec);
15339       continue;
15340     }
15341 
15342     ECDVector *Vec = Entry.get<ECDVector*>();
15343     // Make sure constants are not added more than once.
15344     if (*Vec->begin() == ECD)
15345       continue;
15346 
15347     Vec->push_back(ECD);
15348   }
15349 
15350   // Emit diagnostics.
15351   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15352                                   DupVectorEnd = DupVector.end();
15353        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15354     ECDVector *Vec = *DupVectorIter;
15355     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15356 
15357     // Emit warning for one enum constant.
15358     ECDVector::iterator I = Vec->begin();
15359     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15360       << (*I)->getName() << (*I)->getInitVal().toString(10)
15361       << (*I)->getSourceRange();
15362     ++I;
15363 
15364     // Emit one note for each of the remaining enum constants with
15365     // the same value.
15366     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15367       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15368         << (*I)->getName() << (*I)->getInitVal().toString(10)
15369         << (*I)->getSourceRange();
15370     delete Vec;
15371   }
15372 }
15373 
15374 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15375                              bool AllowMask) const {
15376   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15377   assert(ED->isCompleteDefinition() && "expected enum definition");
15378 
15379   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15380   llvm::APInt &FlagBits = R.first->second;
15381 
15382   if (R.second) {
15383     for (auto *E : ED->enumerators()) {
15384       const auto &EVal = E->getInitVal();
15385       // Only single-bit enumerators introduce new flag values.
15386       if (EVal.isPowerOf2())
15387         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15388     }
15389   }
15390 
15391   // A value is in a flag enum if either its bits are a subset of the enum's
15392   // flag bits (the first condition) or we are allowing masks and the same is
15393   // true of its complement (the second condition). When masks are allowed, we
15394   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15395   //
15396   // While it's true that any value could be used as a mask, the assumption is
15397   // that a mask will have all of the insignificant bits set. Anything else is
15398   // likely a logic error.
15399   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15400   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15401 }
15402 
15403 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15404                          Decl *EnumDeclX,
15405                          ArrayRef<Decl *> Elements,
15406                          Scope *S, AttributeList *Attr) {
15407   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15408   QualType EnumType = Context.getTypeDeclType(Enum);
15409 
15410   if (Attr)
15411     ProcessDeclAttributeList(S, Enum, Attr);
15412 
15413   if (Enum->isDependentType()) {
15414     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15415       EnumConstantDecl *ECD =
15416         cast_or_null<EnumConstantDecl>(Elements[i]);
15417       if (!ECD) continue;
15418 
15419       ECD->setType(EnumType);
15420     }
15421 
15422     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15423     return;
15424   }
15425 
15426   // TODO: If the result value doesn't fit in an int, it must be a long or long
15427   // long value.  ISO C does not support this, but GCC does as an extension,
15428   // emit a warning.
15429   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15430   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15431   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15432 
15433   // Verify that all the values are okay, compute the size of the values, and
15434   // reverse the list.
15435   unsigned NumNegativeBits = 0;
15436   unsigned NumPositiveBits = 0;
15437 
15438   // Keep track of whether all elements have type int.
15439   bool AllElementsInt = true;
15440 
15441   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15442     EnumConstantDecl *ECD =
15443       cast_or_null<EnumConstantDecl>(Elements[i]);
15444     if (!ECD) continue;  // Already issued a diagnostic.
15445 
15446     const llvm::APSInt &InitVal = ECD->getInitVal();
15447 
15448     // Keep track of the size of positive and negative values.
15449     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15450       NumPositiveBits = std::max(NumPositiveBits,
15451                                  (unsigned)InitVal.getActiveBits());
15452     else
15453       NumNegativeBits = std::max(NumNegativeBits,
15454                                  (unsigned)InitVal.getMinSignedBits());
15455 
15456     // Keep track of whether every enum element has type int (very commmon).
15457     if (AllElementsInt)
15458       AllElementsInt = ECD->getType() == Context.IntTy;
15459   }
15460 
15461   // Figure out the type that should be used for this enum.
15462   QualType BestType;
15463   unsigned BestWidth;
15464 
15465   // C++0x N3000 [conv.prom]p3:
15466   //   An rvalue of an unscoped enumeration type whose underlying
15467   //   type is not fixed can be converted to an rvalue of the first
15468   //   of the following types that can represent all the values of
15469   //   the enumeration: int, unsigned int, long int, unsigned long
15470   //   int, long long int, or unsigned long long int.
15471   // C99 6.4.4.3p2:
15472   //   An identifier declared as an enumeration constant has type int.
15473   // The C99 rule is modified by a gcc extension
15474   QualType BestPromotionType;
15475 
15476   bool Packed = Enum->hasAttr<PackedAttr>();
15477   // -fshort-enums is the equivalent to specifying the packed attribute on all
15478   // enum definitions.
15479   if (LangOpts.ShortEnums)
15480     Packed = true;
15481 
15482   if (Enum->isFixed()) {
15483     BestType = Enum->getIntegerType();
15484     if (BestType->isPromotableIntegerType())
15485       BestPromotionType = Context.getPromotedIntegerType(BestType);
15486     else
15487       BestPromotionType = BestType;
15488 
15489     BestWidth = Context.getIntWidth(BestType);
15490   }
15491   else if (NumNegativeBits) {
15492     // If there is a negative value, figure out the smallest integer type (of
15493     // int/long/longlong) that fits.
15494     // If it's packed, check also if it fits a char or a short.
15495     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15496       BestType = Context.SignedCharTy;
15497       BestWidth = CharWidth;
15498     } else if (Packed && NumNegativeBits <= ShortWidth &&
15499                NumPositiveBits < ShortWidth) {
15500       BestType = Context.ShortTy;
15501       BestWidth = ShortWidth;
15502     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15503       BestType = Context.IntTy;
15504       BestWidth = IntWidth;
15505     } else {
15506       BestWidth = Context.getTargetInfo().getLongWidth();
15507 
15508       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15509         BestType = Context.LongTy;
15510       } else {
15511         BestWidth = Context.getTargetInfo().getLongLongWidth();
15512 
15513         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15514           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15515         BestType = Context.LongLongTy;
15516       }
15517     }
15518     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15519   } else {
15520     // If there is no negative value, figure out the smallest type that fits
15521     // all of the enumerator values.
15522     // If it's packed, check also if it fits a char or a short.
15523     if (Packed && NumPositiveBits <= CharWidth) {
15524       BestType = Context.UnsignedCharTy;
15525       BestPromotionType = Context.IntTy;
15526       BestWidth = CharWidth;
15527     } else if (Packed && NumPositiveBits <= ShortWidth) {
15528       BestType = Context.UnsignedShortTy;
15529       BestPromotionType = Context.IntTy;
15530       BestWidth = ShortWidth;
15531     } else if (NumPositiveBits <= IntWidth) {
15532       BestType = Context.UnsignedIntTy;
15533       BestWidth = IntWidth;
15534       BestPromotionType
15535         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15536                            ? Context.UnsignedIntTy : Context.IntTy;
15537     } else if (NumPositiveBits <=
15538                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15539       BestType = Context.UnsignedLongTy;
15540       BestPromotionType
15541         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15542                            ? Context.UnsignedLongTy : Context.LongTy;
15543     } else {
15544       BestWidth = Context.getTargetInfo().getLongLongWidth();
15545       assert(NumPositiveBits <= BestWidth &&
15546              "How could an initializer get larger than ULL?");
15547       BestType = Context.UnsignedLongLongTy;
15548       BestPromotionType
15549         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15550                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15551     }
15552   }
15553 
15554   // Loop over all of the enumerator constants, changing their types to match
15555   // the type of the enum if needed.
15556   for (auto *D : Elements) {
15557     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15558     if (!ECD) continue;  // Already issued a diagnostic.
15559 
15560     // Standard C says the enumerators have int type, but we allow, as an
15561     // extension, the enumerators to be larger than int size.  If each
15562     // enumerator value fits in an int, type it as an int, otherwise type it the
15563     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15564     // that X has type 'int', not 'unsigned'.
15565 
15566     // Determine whether the value fits into an int.
15567     llvm::APSInt InitVal = ECD->getInitVal();
15568 
15569     // If it fits into an integer type, force it.  Otherwise force it to match
15570     // the enum decl type.
15571     QualType NewTy;
15572     unsigned NewWidth;
15573     bool NewSign;
15574     if (!getLangOpts().CPlusPlus &&
15575         !Enum->isFixed() &&
15576         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15577       NewTy = Context.IntTy;
15578       NewWidth = IntWidth;
15579       NewSign = true;
15580     } else if (ECD->getType() == BestType) {
15581       // Already the right type!
15582       if (getLangOpts().CPlusPlus)
15583         // C++ [dcl.enum]p4: Following the closing brace of an
15584         // enum-specifier, each enumerator has the type of its
15585         // enumeration.
15586         ECD->setType(EnumType);
15587       continue;
15588     } else {
15589       NewTy = BestType;
15590       NewWidth = BestWidth;
15591       NewSign = BestType->isSignedIntegerOrEnumerationType();
15592     }
15593 
15594     // Adjust the APSInt value.
15595     InitVal = InitVal.extOrTrunc(NewWidth);
15596     InitVal.setIsSigned(NewSign);
15597     ECD->setInitVal(InitVal);
15598 
15599     // Adjust the Expr initializer and type.
15600     if (ECD->getInitExpr() &&
15601         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15602       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15603                                                 CK_IntegralCast,
15604                                                 ECD->getInitExpr(),
15605                                                 /*base paths*/ nullptr,
15606                                                 VK_RValue));
15607     if (getLangOpts().CPlusPlus)
15608       // C++ [dcl.enum]p4: Following the closing brace of an
15609       // enum-specifier, each enumerator has the type of its
15610       // enumeration.
15611       ECD->setType(EnumType);
15612     else
15613       ECD->setType(NewTy);
15614   }
15615 
15616   Enum->completeDefinition(BestType, BestPromotionType,
15617                            NumPositiveBits, NumNegativeBits);
15618 
15619   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15620 
15621   if (Enum->isClosedFlag()) {
15622     for (Decl *D : Elements) {
15623       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15624       if (!ECD) continue;  // Already issued a diagnostic.
15625 
15626       llvm::APSInt InitVal = ECD->getInitVal();
15627       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15628           !IsValueInFlagEnum(Enum, InitVal, true))
15629         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15630           << ECD << Enum;
15631     }
15632   }
15633 
15634   // Now that the enum type is defined, ensure it's not been underaligned.
15635   if (Enum->hasAttrs())
15636     CheckAlignasUnderalignment(Enum);
15637 }
15638 
15639 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15640                                   SourceLocation StartLoc,
15641                                   SourceLocation EndLoc) {
15642   StringLiteral *AsmString = cast<StringLiteral>(expr);
15643 
15644   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15645                                                    AsmString, StartLoc,
15646                                                    EndLoc);
15647   CurContext->addDecl(New);
15648   return New;
15649 }
15650 
15651 static void checkModuleImportContext(Sema &S, Module *M,
15652                                      SourceLocation ImportLoc, DeclContext *DC,
15653                                      bool FromInclude = false) {
15654   SourceLocation ExternCLoc;
15655 
15656   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15657     switch (LSD->getLanguage()) {
15658     case LinkageSpecDecl::lang_c:
15659       if (ExternCLoc.isInvalid())
15660         ExternCLoc = LSD->getLocStart();
15661       break;
15662     case LinkageSpecDecl::lang_cxx:
15663       break;
15664     }
15665     DC = LSD->getParent();
15666   }
15667 
15668   while (isa<LinkageSpecDecl>(DC))
15669     DC = DC->getParent();
15670 
15671   if (!isa<TranslationUnitDecl>(DC)) {
15672     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15673                           ? diag::ext_module_import_not_at_top_level_noop
15674                           : diag::err_module_import_not_at_top_level_fatal)
15675         << M->getFullModuleName() << DC;
15676     S.Diag(cast<Decl>(DC)->getLocStart(),
15677            diag::note_module_import_not_at_top_level) << DC;
15678   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15679     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15680       << M->getFullModuleName();
15681     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15682   }
15683 }
15684 
15685 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15686                                            ModuleDeclKind MDK,
15687                                            ModuleIdPath Path) {
15688   // 'module implementation' requires that we are not compiling a module of any
15689   // kind. 'module' and 'module partition' require that we are compiling a
15690   // module inteface (not a module map).
15691   auto CMK = getLangOpts().getCompilingModule();
15692   if (MDK == ModuleDeclKind::Implementation
15693           ? CMK != LangOptions::CMK_None
15694           : CMK != LangOptions::CMK_ModuleInterface) {
15695     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15696       << (unsigned)MDK;
15697     return nullptr;
15698   }
15699 
15700   // FIXME: Create a ModuleDecl and return it.
15701 
15702   // FIXME: Most of this work should be done by the preprocessor rather than
15703   // here, in case we look ahead across something where the current
15704   // module matters (eg a #include).
15705 
15706   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15707   // hierarchical module map modules, the dots here are just another character
15708   // that can appear in a module name. Flatten down to the actual module name.
15709   std::string ModuleName;
15710   for (auto &Piece : Path) {
15711     if (!ModuleName.empty())
15712       ModuleName += ".";
15713     ModuleName += Piece.first->getName();
15714   }
15715 
15716   // If a module name was explicitly specified on the command line, it must be
15717   // correct.
15718   if (!getLangOpts().CurrentModule.empty() &&
15719       getLangOpts().CurrentModule != ModuleName) {
15720     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15721         << SourceRange(Path.front().second, Path.back().second)
15722         << getLangOpts().CurrentModule;
15723     return nullptr;
15724   }
15725   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15726 
15727   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15728 
15729   switch (MDK) {
15730   case ModuleDeclKind::Module: {
15731     // FIXME: Check we're not in a submodule.
15732 
15733     // We can't have imported a definition of this module or parsed a module
15734     // map defining it already.
15735     if (auto *M = Map.findModule(ModuleName)) {
15736       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15737       if (M->DefinitionLoc.isValid())
15738         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15739       else if (const auto *FE = M->getASTFile())
15740         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15741             << FE->getName();
15742       return nullptr;
15743     }
15744 
15745     // Create a Module for the module that we're defining.
15746     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15747     assert(Mod && "module creation should not fail");
15748 
15749     // Enter the semantic scope of the module.
15750     ActOnModuleBegin(ModuleLoc, Mod);
15751     return nullptr;
15752   }
15753 
15754   case ModuleDeclKind::Partition:
15755     // FIXME: Check we are in a submodule of the named module.
15756     return nullptr;
15757 
15758   case ModuleDeclKind::Implementation:
15759     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15760         PP.getIdentifierInfo(ModuleName), Path[0].second);
15761 
15762     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15763     if (Import.isInvalid())
15764       return nullptr;
15765     return ConvertDeclToDeclGroup(Import.get());
15766   }
15767 
15768   llvm_unreachable("unexpected module decl kind");
15769 }
15770 
15771 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15772                                    SourceLocation ImportLoc,
15773                                    ModuleIdPath Path) {
15774   Module *Mod =
15775       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15776                                    /*IsIncludeDirective=*/false);
15777   if (!Mod)
15778     return true;
15779 
15780   VisibleModules.setVisible(Mod, ImportLoc);
15781 
15782   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15783 
15784   // FIXME: we should support importing a submodule within a different submodule
15785   // of the same top-level module. Until we do, make it an error rather than
15786   // silently ignoring the import.
15787   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15788   // warn on a redundant import of the current module?
15789   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15790       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15791     Diag(ImportLoc, getLangOpts().isCompilingModule()
15792                         ? diag::err_module_self_import
15793                         : diag::err_module_import_in_implementation)
15794         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15795 
15796   SmallVector<SourceLocation, 2> IdentifierLocs;
15797   Module *ModCheck = Mod;
15798   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15799     // If we've run out of module parents, just drop the remaining identifiers.
15800     // We need the length to be consistent.
15801     if (!ModCheck)
15802       break;
15803     ModCheck = ModCheck->Parent;
15804 
15805     IdentifierLocs.push_back(Path[I].second);
15806   }
15807 
15808   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15809   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15810                                           Mod, IdentifierLocs);
15811   if (!ModuleScopes.empty())
15812     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15813   TU->addDecl(Import);
15814   return Import;
15815 }
15816 
15817 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15818   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15819   BuildModuleInclude(DirectiveLoc, Mod);
15820 }
15821 
15822 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15823   // Determine whether we're in the #include buffer for a module. The #includes
15824   // in that buffer do not qualify as module imports; they're just an
15825   // implementation detail of us building the module.
15826   //
15827   // FIXME: Should we even get ActOnModuleInclude calls for those?
15828   bool IsInModuleIncludes =
15829       TUKind == TU_Module &&
15830       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15831 
15832   bool ShouldAddImport = !IsInModuleIncludes;
15833 
15834   // If this module import was due to an inclusion directive, create an
15835   // implicit import declaration to capture it in the AST.
15836   if (ShouldAddImport) {
15837     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15838     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15839                                                      DirectiveLoc, Mod,
15840                                                      DirectiveLoc);
15841     if (!ModuleScopes.empty())
15842       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15843     TU->addDecl(ImportD);
15844     Consumer.HandleImplicitImportDecl(ImportD);
15845   }
15846 
15847   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15848   VisibleModules.setVisible(Mod, DirectiveLoc);
15849 }
15850 
15851 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15852   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15853 
15854   ModuleScopes.push_back({});
15855   ModuleScopes.back().Module = Mod;
15856   if (getLangOpts().ModulesLocalVisibility)
15857     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15858 
15859   VisibleModules.setVisible(Mod, DirectiveLoc);
15860 }
15861 
15862 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15863   if (getLangOpts().ModulesLocalVisibility) {
15864     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15865     // Leaving a module hides namespace names, so our visible namespace cache
15866     // is now out of date.
15867     VisibleNamespaceCache.clear();
15868   }
15869 
15870   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15871          "left the wrong module scope");
15872   ModuleScopes.pop_back();
15873 
15874   // We got to the end of processing a #include of a local module. Create an
15875   // ImportDecl as we would for an imported module.
15876   FileID File = getSourceManager().getFileID(EofLoc);
15877   assert(File != getSourceManager().getMainFileID() &&
15878          "end of submodule in main source file");
15879   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15880   BuildModuleInclude(DirectiveLoc, Mod);
15881 }
15882 
15883 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15884                                                       Module *Mod) {
15885   // Bail if we're not allowed to implicitly import a module here.
15886   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15887     return;
15888 
15889   // Create the implicit import declaration.
15890   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15891   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15892                                                    Loc, Mod, Loc);
15893   TU->addDecl(ImportD);
15894   Consumer.HandleImplicitImportDecl(ImportD);
15895 
15896   // Make the module visible.
15897   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15898   VisibleModules.setVisible(Mod, Loc);
15899 }
15900 
15901 /// We have parsed the start of an export declaration, including the '{'
15902 /// (if present).
15903 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15904                                  SourceLocation LBraceLoc) {
15905   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15906 
15907   // C++ Modules TS draft:
15908   //   An export-declaration [...] shall not contain more than one
15909   //   export keyword.
15910   //
15911   // The intent here is that an export-declaration cannot appear within another
15912   // export-declaration.
15913   if (D->isExported())
15914     Diag(ExportLoc, diag::err_export_within_export);
15915 
15916   CurContext->addDecl(D);
15917   PushDeclContext(S, D);
15918   return D;
15919 }
15920 
15921 /// Complete the definition of an export declaration.
15922 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15923   auto *ED = cast<ExportDecl>(D);
15924   if (RBraceLoc.isValid())
15925     ED->setRBraceLoc(RBraceLoc);
15926 
15927   // FIXME: Diagnose export of internal-linkage declaration (including
15928   // anonymous namespace).
15929 
15930   PopDeclContext();
15931   return D;
15932 }
15933 
15934 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15935                                       IdentifierInfo* AliasName,
15936                                       SourceLocation PragmaLoc,
15937                                       SourceLocation NameLoc,
15938                                       SourceLocation AliasNameLoc) {
15939   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15940                                          LookupOrdinaryName);
15941   AsmLabelAttr *Attr =
15942       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15943 
15944   // If a declaration that:
15945   // 1) declares a function or a variable
15946   // 2) has external linkage
15947   // already exists, add a label attribute to it.
15948   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15949     if (isDeclExternC(PrevDecl))
15950       PrevDecl->addAttr(Attr);
15951     else
15952       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15953           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15954   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15955   } else
15956     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15957 }
15958 
15959 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15960                              SourceLocation PragmaLoc,
15961                              SourceLocation NameLoc) {
15962   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15963 
15964   if (PrevDecl) {
15965     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15966   } else {
15967     (void)WeakUndeclaredIdentifiers.insert(
15968       std::pair<IdentifierInfo*,WeakInfo>
15969         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15970   }
15971 }
15972 
15973 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15974                                 IdentifierInfo* AliasName,
15975                                 SourceLocation PragmaLoc,
15976                                 SourceLocation NameLoc,
15977                                 SourceLocation AliasNameLoc) {
15978   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15979                                     LookupOrdinaryName);
15980   WeakInfo W = WeakInfo(Name, NameLoc);
15981 
15982   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15983     if (!PrevDecl->hasAttr<AliasAttr>())
15984       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15985         DeclApplyPragmaWeak(TUScope, ND, W);
15986   } else {
15987     (void)WeakUndeclaredIdentifiers.insert(
15988       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15989   }
15990 }
15991 
15992 Decl *Sema::getObjCDeclContext() const {
15993   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15994 }
15995