1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   default:
152     break;
153   }
154 
155   return false;
156 }
157 
158 namespace {
159 enum class UnqualifiedTypeNameLookupResult {
160   NotFound,
161   FoundNonType,
162   FoundType
163 };
164 } // end anonymous namespace
165 
166 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// dependent class.
168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169 /// type decl, \a FoundType if only type decls are found.
170 static UnqualifiedTypeNameLookupResult
171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172                                 SourceLocation NameLoc,
173                                 const CXXRecordDecl *RD) {
174   if (!RD->hasDefinition())
175     return UnqualifiedTypeNameLookupResult::NotFound;
176   // Look for type decls in base classes.
177   UnqualifiedTypeNameLookupResult FoundTypeDecl =
178       UnqualifiedTypeNameLookupResult::NotFound;
179   for (const auto &Base : RD->bases()) {
180     const CXXRecordDecl *BaseRD = nullptr;
181     if (auto *BaseTT = Base.getType()->getAs<TagType>())
182       BaseRD = BaseTT->getAsCXXRecordDecl();
183     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184       // Look for type decls in dependent base classes that have known primary
185       // templates.
186       if (!TST || !TST->isDependentType())
187         continue;
188       auto *TD = TST->getTemplateName().getAsTemplateDecl();
189       if (!TD)
190         continue;
191       if (auto *BasePrimaryTemplate =
192           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194           BaseRD = BasePrimaryTemplate;
195         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196           if (const ClassTemplatePartialSpecializationDecl *PS =
197                   CTD->findPartialSpecialization(Base.getType()))
198             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199               BaseRD = PS;
200         }
201       }
202     }
203     if (BaseRD) {
204       for (NamedDecl *ND : BaseRD->lookup(&II)) {
205         if (!isa<TypeDecl>(ND))
206           return UnqualifiedTypeNameLookupResult::FoundNonType;
207         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208       }
209       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211         case UnqualifiedTypeNameLookupResult::FoundNonType:
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         case UnqualifiedTypeNameLookupResult::FoundType:
214           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215           break;
216         case UnqualifiedTypeNameLookupResult::NotFound:
217           break;
218         }
219       }
220     }
221   }
222 
223   return FoundTypeDecl;
224 }
225 
226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227                                                       const IdentifierInfo &II,
228                                                       SourceLocation NameLoc) {
229   // Lookup in the parent class template context, if any.
230   const CXXRecordDecl *RD = nullptr;
231   UnqualifiedTypeNameLookupResult FoundTypeDecl =
232       UnqualifiedTypeNameLookupResult::NotFound;
233   for (DeclContext *DC = S.CurContext;
234        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235        DC = DC->getParent()) {
236     // Look for type decls in dependent base classes that have known primary
237     // templates.
238     RD = dyn_cast<CXXRecordDecl>(DC);
239     if (RD && RD->getDescribedClassTemplate())
240       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241   }
242   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243     return nullptr;
244 
245   // We found some types in dependent base classes.  Recover as if the user
246   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
247   // lookup during template instantiation.
248   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 
250   ASTContext &Context = S.Context;
251   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252                                           cast<Type>(Context.getRecordType(RD)));
253   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254 
255   CXXScopeSpec SS;
256   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 
258   TypeLocBuilder Builder;
259   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260   DepTL.setNameLoc(NameLoc);
261   DepTL.setElaboratedKeywordLoc(SourceLocation());
262   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264 }
265 
266 /// \brief If the identifier refers to a type name within this scope,
267 /// return the declaration of that type.
268 ///
269 /// This routine performs ordinary name lookup of the identifier II
270 /// within the given scope, with optional C++ scope specifier SS, to
271 /// determine whether the name refers to a type. If so, returns an
272 /// opaque pointer (actually a QualType) corresponding to that
273 /// type. Otherwise, returns NULL.
274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275                              Scope *S, CXXScopeSpec *SS,
276                              bool isClassName, bool HasTrailingDot,
277                              ParsedType ObjectTypePtr,
278                              bool IsCtorOrDtorName,
279                              bool WantNontrivialTypeSourceInfo,
280                              bool IsClassTemplateDeductionContext,
281                              IdentifierInfo **CorrectedII) {
282   // FIXME: Consider allowing this outside C++1z mode as an extension.
283   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
285                               !isClassName && !HasTrailingDot;
286 
287   // Determine where we will perform name lookup.
288   DeclContext *LookupCtx = nullptr;
289   if (ObjectTypePtr) {
290     QualType ObjectType = ObjectTypePtr.get();
291     if (ObjectType->isRecordType())
292       LookupCtx = computeDeclContext(ObjectType);
293   } else if (SS && SS->isNotEmpty()) {
294     LookupCtx = computeDeclContext(*SS, false);
295 
296     if (!LookupCtx) {
297       if (isDependentScopeSpecifier(*SS)) {
298         // C++ [temp.res]p3:
299         //   A qualified-id that refers to a type and in which the
300         //   nested-name-specifier depends on a template-parameter (14.6.2)
301         //   shall be prefixed by the keyword typename to indicate that the
302         //   qualified-id denotes a type, forming an
303         //   elaborated-type-specifier (7.1.5.3).
304         //
305         // We therefore do not perform any name lookup if the result would
306         // refer to a member of an unknown specialization.
307         if (!isClassName && !IsCtorOrDtorName)
308           return nullptr;
309 
310         // We know from the grammar that this name refers to a type,
311         // so build a dependent node to describe the type.
312         if (WantNontrivialTypeSourceInfo)
313           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 
315         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317                                        II, NameLoc);
318         return ParsedType::make(T);
319       }
320 
321       return nullptr;
322     }
323 
324     if (!LookupCtx->isDependentContext() &&
325         RequireCompleteDeclContext(*SS, LookupCtx))
326       return nullptr;
327   }
328 
329   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330   // lookup for class-names.
331   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332                                       LookupOrdinaryName;
333   LookupResult Result(*this, &II, NameLoc, Kind);
334   if (LookupCtx) {
335     // Perform "qualified" name lookup into the declaration context we
336     // computed, which is either the type of the base of a member access
337     // expression or the declaration context associated with a prior
338     // nested-name-specifier.
339     LookupQualifiedName(Result, LookupCtx);
340 
341     if (ObjectTypePtr && Result.empty()) {
342       // C++ [basic.lookup.classref]p3:
343       //   If the unqualified-id is ~type-name, the type-name is looked up
344       //   in the context of the entire postfix-expression. If the type T of
345       //   the object expression is of a class type C, the type-name is also
346       //   looked up in the scope of class C. At least one of the lookups shall
347       //   find a name that refers to (possibly cv-qualified) T.
348       LookupName(Result, S);
349     }
350   } else {
351     // Perform unqualified name lookup.
352     LookupName(Result, S);
353 
354     // For unqualified lookup in a class template in MSVC mode, look into
355     // dependent base classes where the primary class template is known.
356     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357       if (ParsedType TypeInBase =
358               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359         return TypeInBase;
360     }
361   }
362 
363   NamedDecl *IIDecl = nullptr;
364   switch (Result.getResultKind()) {
365   case LookupResult::NotFound:
366   case LookupResult::NotFoundInCurrentInstantiation:
367     if (CorrectedII) {
368       TypoCorrection Correction =
369           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370                       llvm::make_unique<TypeNameValidatorCCC>(
371                           true, isClassName, AllowDeducedTemplate),
372                       CTK_ErrorRecovery);
373       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374       TemplateTy Template;
375       bool MemberOfUnknownSpecialization;
376       UnqualifiedId TemplateName;
377       TemplateName.setIdentifier(NewII, NameLoc);
378       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379       CXXScopeSpec NewSS, *NewSSPtr = SS;
380       if (SS && NNS) {
381         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382         NewSSPtr = &NewSS;
383       }
384       if (Correction && (NNS || NewII != &II) &&
385           // Ignore a correction to a template type as the to-be-corrected
386           // identifier is not a template (typo correction for template names
387           // is handled elsewhere).
388           !(getLangOpts().CPlusPlus && NewSSPtr &&
389             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390                            Template, MemberOfUnknownSpecialization))) {
391         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392                                     isClassName, HasTrailingDot, ObjectTypePtr,
393                                     IsCtorOrDtorName,
394                                     WantNontrivialTypeSourceInfo,
395                                     IsClassTemplateDeductionContext);
396         if (Ty) {
397           diagnoseTypo(Correction,
398                        PDiag(diag::err_unknown_type_or_class_name_suggest)
399                          << Result.getLookupName() << isClassName);
400           if (SS && NNS)
401             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402           *CorrectedII = NewII;
403           return Ty;
404         }
405       }
406     }
407     // If typo correction failed or was not performed, fall through
408     LLVM_FALLTHROUGH;
409   case LookupResult::FoundOverloaded:
410   case LookupResult::FoundUnresolvedValue:
411     Result.suppressDiagnostics();
412     return nullptr;
413 
414   case LookupResult::Ambiguous:
415     // Recover from type-hiding ambiguities by hiding the type.  We'll
416     // do the lookup again when looking for an object, and we can
417     // diagnose the error then.  If we don't do this, then the error
418     // about hiding the type will be immediately followed by an error
419     // that only makes sense if the identifier was treated like a type.
420     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421       Result.suppressDiagnostics();
422       return nullptr;
423     }
424 
425     // Look to see if we have a type anywhere in the list of results.
426     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427          Res != ResEnd; ++Res) {
428       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430         if (!IIDecl ||
431             (*Res)->getLocation().getRawEncoding() <
432               IIDecl->getLocation().getRawEncoding())
433           IIDecl = *Res;
434       }
435     }
436 
437     if (!IIDecl) {
438       // None of the entities we found is a type, so there is no way
439       // to even assume that the result is a type. In this case, don't
440       // complain about the ambiguity. The parser will either try to
441       // perform this lookup again (e.g., as an object name), which
442       // will produce the ambiguity, or will complain that it expected
443       // a type name.
444       Result.suppressDiagnostics();
445       return nullptr;
446     }
447 
448     // We found a type within the ambiguous lookup; diagnose the
449     // ambiguity and then return that type. This might be the right
450     // answer, or it might not be, but it suppresses any attempt to
451     // perform the name lookup again.
452     break;
453 
454   case LookupResult::Found:
455     IIDecl = Result.getFoundDecl();
456     break;
457   }
458 
459   assert(IIDecl && "Didn't find decl");
460 
461   QualType T;
462   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463     // C++ [class.qual]p2: A lookup that would find the injected-class-name
464     // instead names the constructors of the class, except when naming a class.
465     // This is ill-formed when we're not actually forming a ctor or dtor name.
466     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469         FoundRD->isInjectedClassName() &&
470         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472           << &II << /*Type*/1;
473 
474     DiagnoseUseOfDecl(IIDecl, NameLoc);
475 
476     T = Context.getTypeDeclType(TD);
477     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480     if (!HasTrailingDot)
481       T = Context.getObjCInterfaceType(IDecl);
482   } else if (AllowDeducedTemplate) {
483     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485                                                        QualType(), false);
486   }
487 
488   if (T.isNull()) {
489     // If it's not plausibly a type, suppress diagnostics.
490     Result.suppressDiagnostics();
491     return nullptr;
492   }
493 
494   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495   // constructor or destructor name (in such a case, the scope specifier
496   // will be attached to the enclosing Expr or Decl node).
497   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498       !isa<ObjCInterfaceDecl>(IIDecl)) {
499     if (WantNontrivialTypeSourceInfo) {
500       // Construct a type with type-source information.
501       TypeLocBuilder Builder;
502       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 
504       T = getElaboratedType(ETK_None, *SS, T);
505       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506       ElabTL.setElaboratedKeywordLoc(SourceLocation());
507       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509     } else {
510       T = getElaboratedType(ETK_None, *SS, T);
511     }
512   }
513 
514   return ParsedType::make(T);
515 }
516 
517 // Builds a fake NNS for the given decl context.
518 static NestedNameSpecifier *
519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520   for (;; DC = DC->getLookupParent()) {
521     DC = DC->getPrimaryContext();
522     auto *ND = dyn_cast<NamespaceDecl>(DC);
523     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524       return NestedNameSpecifier::Create(Context, nullptr, ND);
525     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527                                          RD->getTypeForDecl());
528     else if (isa<TranslationUnitDecl>(DC))
529       return NestedNameSpecifier::GlobalSpecifier(Context);
530   }
531   llvm_unreachable("something isn't in TU scope?");
532 }
533 
534 /// Find the parent class with dependent bases of the innermost enclosing method
535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536 /// up allowing unqualified dependent type names at class-level, which MSVC
537 /// correctly rejects.
538 static const CXXRecordDecl *
539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541     DC = DC->getPrimaryContext();
542     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543       if (MD->getParent()->hasAnyDependentBases())
544         return MD->getParent();
545   }
546   return nullptr;
547 }
548 
549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550                                           SourceLocation NameLoc,
551                                           bool IsTemplateTypeArg) {
552   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 
554   NestedNameSpecifier *NNS = nullptr;
555   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556     // If we weren't able to parse a default template argument, delay lookup
557     // until instantiation time by making a non-dependent DependentTypeName. We
558     // pretend we saw a NestedNameSpecifier referring to the current scope, and
559     // lookup is retried.
560     // FIXME: This hurts our diagnostic quality, since we get errors like "no
561     // type named 'Foo' in 'current_namespace'" when the user didn't write any
562     // name specifiers.
563     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565   } else if (const CXXRecordDecl *RD =
566                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567     // Build a DependentNameType that will perform lookup into RD at
568     // instantiation time.
569     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570                                       RD->getTypeForDecl());
571 
572     // Diagnose that this identifier was undeclared, and retry the lookup during
573     // template instantiation.
574     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575                                                                       << RD;
576   } else {
577     // This is not a situation that we should recover from.
578     return ParsedType();
579   }
580 
581   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 
583   // Build type location information.  We synthesized the qualifier, so we have
584   // to build a fake NestedNameSpecifierLoc.
585   NestedNameSpecifierLocBuilder NNSLocBuilder;
586   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 
589   TypeLocBuilder Builder;
590   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591   DepTL.setNameLoc(NameLoc);
592   DepTL.setElaboratedKeywordLoc(SourceLocation());
593   DepTL.setQualifierLoc(QualifierLoc);
594   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 }
596 
597 /// isTagName() - This method is called *for error recovery purposes only*
598 /// to determine if the specified name is a valid tag name ("struct foo").  If
599 /// so, this returns the TST for the tag corresponding to it (TST_enum,
600 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
601 /// cases in C where the user forgot to specify the tag.
602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603   // Do a tag name lookup in this scope.
604   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605   LookupName(R, S, false);
606   R.suppressDiagnostics();
607   if (R.getResultKind() == LookupResult::Found)
608     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609       switch (TD->getTagKind()) {
610       case TTK_Struct: return DeclSpec::TST_struct;
611       case TTK_Interface: return DeclSpec::TST_interface;
612       case TTK_Union:  return DeclSpec::TST_union;
613       case TTK_Class:  return DeclSpec::TST_class;
614       case TTK_Enum:   return DeclSpec::TST_enum;
615       }
616     }
617 
618   return DeclSpec::TST_unspecified;
619 }
620 
621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
623 /// then downgrade the missing typename error to a warning.
624 /// This is needed for MSVC compatibility; Example:
625 /// @code
626 /// template<class T> class A {
627 /// public:
628 ///   typedef int TYPE;
629 /// };
630 /// template<class T> class B : public A<T> {
631 /// public:
632 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
633 /// };
634 /// @endcode
635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636   if (CurContext->isRecord()) {
637     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638       return true;
639 
640     const Type *Ty = SS->getScopeRep()->getAsType();
641 
642     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643     for (const auto &Base : RD->bases())
644       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645         return true;
646     return S->isFunctionPrototypeScope();
647   }
648   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 }
650 
651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652                                    SourceLocation IILoc,
653                                    Scope *S,
654                                    CXXScopeSpec *SS,
655                                    ParsedType &SuggestedType,
656                                    bool IsTemplateName) {
657   // Don't report typename errors for editor placeholders.
658   if (II->isEditorPlaceholder())
659     return;
660   // We don't have anything to suggest (yet).
661   SuggestedType = nullptr;
662 
663   // There may have been a typo in the name of the type. Look up typo
664   // results, in case we have something that we can suggest.
665   if (TypoCorrection Corrected =
666           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667                       llvm::make_unique<TypeNameValidatorCCC>(
668                           false, false, IsTemplateName, !IsTemplateName),
669                       CTK_ErrorRecovery)) {
670     // FIXME: Support error recovery for the template-name case.
671     bool CanRecover = !IsTemplateName;
672     if (Corrected.isKeyword()) {
673       // We corrected to a keyword.
674       diagnoseTypo(Corrected,
675                    PDiag(IsTemplateName ? diag::err_no_template_suggest
676                                         : diag::err_unknown_typename_suggest)
677                        << II);
678       II = Corrected.getCorrectionAsIdentifierInfo();
679     } else {
680       // We found a similarly-named type or interface; suggest that.
681       if (!SS || !SS->isSet()) {
682         diagnoseTypo(Corrected,
683                      PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                           : diag::err_unknown_typename_suggest)
685                          << II, CanRecover);
686       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689                                 II->getName().equals(CorrectedStr);
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName
692                                ? diag::err_no_member_template_suggest
693                                : diag::err_unknown_nested_typename_suggest)
694                          << II << DC << DroppedSpecifier << SS->getRange(),
695                      CanRecover);
696       } else {
697         llvm_unreachable("could not have corrected a typo here");
698       }
699 
700       if (!CanRecover)
701         return;
702 
703       CXXScopeSpec tmpSS;
704       if (Corrected.getCorrectionSpecifier())
705         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706                           SourceRange(IILoc));
707       // FIXME: Support class template argument deduction here.
708       SuggestedType =
709           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711                       /*IsCtorOrDtorName=*/false,
712                       /*NonTrivialTypeSourceInfo=*/true);
713     }
714     return;
715   }
716 
717   if (getLangOpts().CPlusPlus && !IsTemplateName) {
718     // See if II is a class template that the user forgot to pass arguments to.
719     UnqualifiedId Name;
720     Name.setIdentifier(II, IILoc);
721     CXXScopeSpec EmptySS;
722     TemplateTy TemplateResult;
723     bool MemberOfUnknownSpecialization;
724     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725                        Name, nullptr, true, TemplateResult,
726                        MemberOfUnknownSpecialization) == TNK_Type_template) {
727       TemplateName TplName = TemplateResult.get();
728       Diag(IILoc, diag::err_template_missing_args)
729         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732           << TplDecl->getTemplateParameters()->getSourceRange();
733       }
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// \brief Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand,
851                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     // In C, we first see whether there is a tag type by the same name, in
922     // which case it's likely that the user just forgot to write "enum",
923     // "struct", or "union".
924     if (!getLangOpts().CPlusPlus && !SecondTry &&
925         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926       break;
927     }
928 
929     // Perform typo correction to determine if there is another name that is
930     // close to this name.
931     if (!SecondTry && CCC) {
932       SecondTry = true;
933       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934                                                  Result.getLookupKind(), S,
935                                                  &SS, std::move(CCC),
936                                                  CTK_ErrorRecovery)) {
937         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938         unsigned QualifiedDiag = diag::err_no_member_suggest;
939 
940         NamedDecl *FirstDecl = Corrected.getFoundDecl();
941         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944           UnqualifiedDiag = diag::err_no_template_suggest;
945           QualifiedDiag = diag::err_no_member_template_suggest;
946         } else if (UnderlyingFirstDecl &&
947                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950           UnqualifiedDiag = diag::err_unknown_typename_suggest;
951           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952         }
953 
954         if (SS.isEmpty()) {
955           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956         } else {// FIXME: is this even reachable? Test it.
957           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959                                   Name->getName().equals(CorrectedStr);
960           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961                                     << Name << computeDeclContext(SS, false)
962                                     << DroppedSpecifier << SS.getRange());
963         }
964 
965         // Update the name, so that the caller has the new name.
966         Name = Corrected.getCorrectionAsIdentifierInfo();
967 
968         // Typo correction corrected to a keyword.
969         if (Corrected.isKeyword())
970           return Name;
971 
972         // Also update the LookupResult...
973         // FIXME: This should probably go away at some point
974         Result.clear();
975         Result.setLookupName(Corrected.getCorrection());
976         if (FirstDecl)
977           Result.addDecl(FirstDecl);
978 
979         // If we found an Objective-C instance variable, let
980         // LookupInObjCMethod build the appropriate expression to
981         // reference the ivar.
982         // FIXME: This is a gross hack.
983         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984           Result.clear();
985           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986           return E;
987         }
988 
989         goto Corrected;
990       }
991     }
992 
993     // We failed to correct; just fall through and let the parser deal with it.
994     Result.suppressDiagnostics();
995     return NameClassification::Unknown();
996 
997   case LookupResult::NotFoundInCurrentInstantiation: {
998     // We performed name lookup into the current instantiation, and there were
999     // dependent bases, so we treat this result the same way as any other
1000     // dependent nested-name-specifier.
1001 
1002     // C++ [temp.res]p2:
1003     //   A name used in a template declaration or definition and that is
1004     //   dependent on a template-parameter is assumed not to name a type
1005     //   unless the applicable name lookup finds a type name or the name is
1006     //   qualified by the keyword typename.
1007     //
1008     // FIXME: If the next token is '<', we might want to ask the parser to
1009     // perform some heroics to see if we actually have a
1010     // template-argument-list, which would indicate a missing 'template'
1011     // keyword here.
1012     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013                                       NameInfo, IsAddressOfOperand,
1014                                       /*TemplateArgs=*/nullptr);
1015   }
1016 
1017   case LookupResult::Found:
1018   case LookupResult::FoundOverloaded:
1019   case LookupResult::FoundUnresolvedValue:
1020     break;
1021 
1022   case LookupResult::Ambiguous:
1023     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024         hasAnyAcceptableTemplateNames(Result)) {
1025       // C++ [temp.local]p3:
1026       //   A lookup that finds an injected-class-name (10.2) can result in an
1027       //   ambiguity in certain cases (for example, if it is found in more than
1028       //   one base class). If all of the injected-class-names that are found
1029       //   refer to specializations of the same class template, and if the name
1030       //   is followed by a template-argument-list, the reference refers to the
1031       //   class template itself and not a specialization thereof, and is not
1032       //   ambiguous.
1033       //
1034       // This filtering can make an ambiguous result into an unambiguous one,
1035       // so try again after filtering out template names.
1036       FilterAcceptableTemplateNames(Result);
1037       if (!Result.isAmbiguous()) {
1038         IsFilteredTemplateName = true;
1039         break;
1040       }
1041     }
1042 
1043     // Diagnose the ambiguity and return an error.
1044     return NameClassification::Error();
1045   }
1046 
1047   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049     // C++ [temp.names]p3:
1050     //   After name lookup (3.4) finds that a name is a template-name or that
1051     //   an operator-function-id or a literal- operator-id refers to a set of
1052     //   overloaded functions any member of which is a function template if
1053     //   this is followed by a <, the < is always taken as the delimiter of a
1054     //   template-argument-list and never as the less-than operator.
1055     if (!IsFilteredTemplateName)
1056       FilterAcceptableTemplateNames(Result);
1057 
1058     if (!Result.empty()) {
1059       bool IsFunctionTemplate;
1060       bool IsVarTemplate;
1061       TemplateName Template;
1062       if (Result.end() - Result.begin() > 1) {
1063         IsFunctionTemplate = true;
1064         Template = Context.getOverloadedTemplateName(Result.begin(),
1065                                                      Result.end());
1066       } else {
1067         TemplateDecl *TD
1068           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074                                                     /*TemplateKeyword=*/false,
1075                                                       TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// \brief Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 static bool isUsingDecl(NamedDecl *D) {
1452   return isa<UsingShadowDecl>(D) ||
1453          isa<UnresolvedUsingTypenameDecl>(D) ||
1454          isa<UnresolvedUsingValueDecl>(D);
1455 }
1456 
1457 /// Removes using shadow declarations from the lookup results.
1458 static void RemoveUsingDecls(LookupResult &R) {
1459   LookupResult::Filter F = R.makeFilter();
1460   while (F.hasNext())
1461     if (isUsingDecl(F.next()))
1462       F.erase();
1463 
1464   F.done();
1465 }
1466 
1467 /// \brief Check for this common pattern:
1468 /// @code
1469 /// class S {
1470 ///   S(const S&); // DO NOT IMPLEMENT
1471 ///   void operator=(const S&); // DO NOT IMPLEMENT
1472 /// };
1473 /// @endcode
1474 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1475   // FIXME: Should check for private access too but access is set after we get
1476   // the decl here.
1477   if (D->doesThisDeclarationHaveABody())
1478     return false;
1479 
1480   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1481     return CD->isCopyConstructor();
1482   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1483     return Method->isCopyAssignmentOperator();
1484   return false;
1485 }
1486 
1487 // We need this to handle
1488 //
1489 // typedef struct {
1490 //   void *foo() { return 0; }
1491 // } A;
1492 //
1493 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1494 // for example. If 'A', foo will have external linkage. If we have '*A',
1495 // foo will have no linkage. Since we can't know until we get to the end
1496 // of the typedef, this function finds out if D might have non-external linkage.
1497 // Callers should verify at the end of the TU if it D has external linkage or
1498 // not.
1499 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1500   const DeclContext *DC = D->getDeclContext();
1501   while (!DC->isTranslationUnit()) {
1502     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1503       if (!RD->hasNameForLinkage())
1504         return true;
1505     }
1506     DC = DC->getParent();
1507   }
1508 
1509   return !D->isExternallyVisible();
1510 }
1511 
1512 // FIXME: This needs to be refactored; some other isInMainFile users want
1513 // these semantics.
1514 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1515   if (S.TUKind != TU_Complete)
1516     return false;
1517   return S.SourceMgr.isInMainFile(Loc);
1518 }
1519 
1520 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1521   assert(D);
1522 
1523   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1524     return false;
1525 
1526   // Ignore all entities declared within templates, and out-of-line definitions
1527   // of members of class templates.
1528   if (D->getDeclContext()->isDependentContext() ||
1529       D->getLexicalDeclContext()->isDependentContext())
1530     return false;
1531 
1532   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1533     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1534       return false;
1535     // A non-out-of-line declaration of a member specialization was implicitly
1536     // instantiated; it's the out-of-line declaration that we're interested in.
1537     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1538         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1539       return false;
1540 
1541     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1542       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1543         return false;
1544     } else {
1545       // 'static inline' functions are defined in headers; don't warn.
1546       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1547         return false;
1548     }
1549 
1550     if (FD->doesThisDeclarationHaveABody() &&
1551         Context.DeclMustBeEmitted(FD))
1552       return false;
1553   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1554     // Constants and utility variables are defined in headers with internal
1555     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1556     // like "inline".)
1557     if (!isMainFileLoc(*this, VD->getLocation()))
1558       return false;
1559 
1560     if (Context.DeclMustBeEmitted(VD))
1561       return false;
1562 
1563     if (VD->isStaticDataMember() &&
1564         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1565       return false;
1566     if (VD->isStaticDataMember() &&
1567         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1568         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1569       return false;
1570 
1571     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1572       return false;
1573   } else {
1574     return false;
1575   }
1576 
1577   // Only warn for unused decls internal to the translation unit.
1578   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1579   // for inline functions defined in the main source file, for instance.
1580   return mightHaveNonExternalLinkage(D);
1581 }
1582 
1583 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1584   if (!D)
1585     return;
1586 
1587   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1588     const FunctionDecl *First = FD->getFirstDecl();
1589     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1590       return; // First should already be in the vector.
1591   }
1592 
1593   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594     const VarDecl *First = VD->getFirstDecl();
1595     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1596       return; // First should already be in the vector.
1597   }
1598 
1599   if (ShouldWarnIfUnusedFileScopedDecl(D))
1600     UnusedFileScopedDecls.push_back(D);
1601 }
1602 
1603 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1604   if (D->isInvalidDecl())
1605     return false;
1606 
1607   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1608       D->hasAttr<ObjCPreciseLifetimeAttr>())
1609     return false;
1610 
1611   if (isa<LabelDecl>(D))
1612     return true;
1613 
1614   // Except for labels, we only care about unused decls that are local to
1615   // functions.
1616   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1617   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1618     // For dependent types, the diagnostic is deferred.
1619     WithinFunction =
1620         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1621   if (!WithinFunction)
1622     return false;
1623 
1624   if (isa<TypedefNameDecl>(D))
1625     return true;
1626 
1627   // White-list anything that isn't a local variable.
1628   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1629     return false;
1630 
1631   // Types of valid local variables should be complete, so this should succeed.
1632   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1633 
1634     // White-list anything with an __attribute__((unused)) type.
1635     const auto *Ty = VD->getType().getTypePtr();
1636 
1637     // Only look at the outermost level of typedef.
1638     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1639       if (TT->getDecl()->hasAttr<UnusedAttr>())
1640         return false;
1641     }
1642 
1643     // If we failed to complete the type for some reason, or if the type is
1644     // dependent, don't diagnose the variable.
1645     if (Ty->isIncompleteType() || Ty->isDependentType())
1646       return false;
1647 
1648     // Look at the element type to ensure that the warning behaviour is
1649     // consistent for both scalars and arrays.
1650     Ty = Ty->getBaseElementTypeUnsafe();
1651 
1652     if (const TagType *TT = Ty->getAs<TagType>()) {
1653       const TagDecl *Tag = TT->getDecl();
1654       if (Tag->hasAttr<UnusedAttr>())
1655         return false;
1656 
1657       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1658         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1659           return false;
1660 
1661         if (const Expr *Init = VD->getInit()) {
1662           if (const ExprWithCleanups *Cleanups =
1663                   dyn_cast<ExprWithCleanups>(Init))
1664             Init = Cleanups->getSubExpr();
1665           const CXXConstructExpr *Construct =
1666             dyn_cast<CXXConstructExpr>(Init);
1667           if (Construct && !Construct->isElidable()) {
1668             CXXConstructorDecl *CD = Construct->getConstructor();
1669             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1670               return false;
1671           }
1672         }
1673       }
1674     }
1675 
1676     // TODO: __attribute__((unused)) templates?
1677   }
1678 
1679   return true;
1680 }
1681 
1682 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1683                                      FixItHint &Hint) {
1684   if (isa<LabelDecl>(D)) {
1685     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1686                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1687     if (AfterColon.isInvalid())
1688       return;
1689     Hint = FixItHint::CreateRemoval(CharSourceRange::
1690                                     getCharRange(D->getLocStart(), AfterColon));
1691   }
1692 }
1693 
1694 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1695   if (D->getTypeForDecl()->isDependentType())
1696     return;
1697 
1698   for (auto *TmpD : D->decls()) {
1699     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1700       DiagnoseUnusedDecl(T);
1701     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1702       DiagnoseUnusedNestedTypedefs(R);
1703   }
1704 }
1705 
1706 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1707 /// unless they are marked attr(unused).
1708 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1709   if (!ShouldDiagnoseUnusedDecl(D))
1710     return;
1711 
1712   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1713     // typedefs can be referenced later on, so the diagnostics are emitted
1714     // at end-of-translation-unit.
1715     UnusedLocalTypedefNameCandidates.insert(TD);
1716     return;
1717   }
1718 
1719   FixItHint Hint;
1720   GenerateFixForUnusedDecl(D, Context, Hint);
1721 
1722   unsigned DiagID;
1723   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1724     DiagID = diag::warn_unused_exception_param;
1725   else if (isa<LabelDecl>(D))
1726     DiagID = diag::warn_unused_label;
1727   else
1728     DiagID = diag::warn_unused_variable;
1729 
1730   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1731 }
1732 
1733 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1734   // Verify that we have no forward references left.  If so, there was a goto
1735   // or address of a label taken, but no definition of it.  Label fwd
1736   // definitions are indicated with a null substmt which is also not a resolved
1737   // MS inline assembly label name.
1738   bool Diagnose = false;
1739   if (L->isMSAsmLabel())
1740     Diagnose = !L->isResolvedMSAsmLabel();
1741   else
1742     Diagnose = L->getStmt() == nullptr;
1743   if (Diagnose)
1744     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1745 }
1746 
1747 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1748   S->mergeNRVOIntoParent();
1749 
1750   if (S->decl_empty()) return;
1751   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1752          "Scope shouldn't contain decls!");
1753 
1754   for (auto *TmpD : S->decls()) {
1755     assert(TmpD && "This decl didn't get pushed??");
1756 
1757     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1758     NamedDecl *D = cast<NamedDecl>(TmpD);
1759 
1760     if (!D->getDeclName()) continue;
1761 
1762     // Diagnose unused variables in this scope.
1763     if (!S->hasUnrecoverableErrorOccurred()) {
1764       DiagnoseUnusedDecl(D);
1765       if (const auto *RD = dyn_cast<RecordDecl>(D))
1766         DiagnoseUnusedNestedTypedefs(RD);
1767     }
1768 
1769     // If this was a forward reference to a label, verify it was defined.
1770     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1771       CheckPoppedLabel(LD, *this);
1772 
1773     // Remove this name from our lexical scope, and warn on it if we haven't
1774     // already.
1775     IdResolver.RemoveDecl(D);
1776     auto ShadowI = ShadowingDecls.find(D);
1777     if (ShadowI != ShadowingDecls.end()) {
1778       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1779         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1780             << D << FD << FD->getParent();
1781         Diag(FD->getLocation(), diag::note_previous_declaration);
1782       }
1783       ShadowingDecls.erase(ShadowI);
1784     }
1785   }
1786 }
1787 
1788 /// \brief Look for an Objective-C class in the translation unit.
1789 ///
1790 /// \param Id The name of the Objective-C class we're looking for. If
1791 /// typo-correction fixes this name, the Id will be updated
1792 /// to the fixed name.
1793 ///
1794 /// \param IdLoc The location of the name in the translation unit.
1795 ///
1796 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1797 /// if there is no class with the given name.
1798 ///
1799 /// \returns The declaration of the named Objective-C class, or NULL if the
1800 /// class could not be found.
1801 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1802                                               SourceLocation IdLoc,
1803                                               bool DoTypoCorrection) {
1804   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1805   // creation from this context.
1806   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1807 
1808   if (!IDecl && DoTypoCorrection) {
1809     // Perform typo correction at the given location, but only if we
1810     // find an Objective-C class name.
1811     if (TypoCorrection C = CorrectTypo(
1812             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1813             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1814             CTK_ErrorRecovery)) {
1815       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1816       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1817       Id = IDecl->getIdentifier();
1818     }
1819   }
1820   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1821   // This routine must always return a class definition, if any.
1822   if (Def && Def->getDefinition())
1823       Def = Def->getDefinition();
1824   return Def;
1825 }
1826 
1827 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1828 /// from S, where a non-field would be declared. This routine copes
1829 /// with the difference between C and C++ scoping rules in structs and
1830 /// unions. For example, the following code is well-formed in C but
1831 /// ill-formed in C++:
1832 /// @code
1833 /// struct S6 {
1834 ///   enum { BAR } e;
1835 /// };
1836 ///
1837 /// void test_S6() {
1838 ///   struct S6 a;
1839 ///   a.e = BAR;
1840 /// }
1841 /// @endcode
1842 /// For the declaration of BAR, this routine will return a different
1843 /// scope. The scope S will be the scope of the unnamed enumeration
1844 /// within S6. In C++, this routine will return the scope associated
1845 /// with S6, because the enumeration's scope is a transparent
1846 /// context but structures can contain non-field names. In C, this
1847 /// routine will return the translation unit scope, since the
1848 /// enumeration's scope is a transparent context and structures cannot
1849 /// contain non-field names.
1850 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1851   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1852          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1853          (S->isClassScope() && !getLangOpts().CPlusPlus))
1854     S = S->getParent();
1855   return S;
1856 }
1857 
1858 /// \brief Looks up the declaration of "struct objc_super" and
1859 /// saves it for later use in building builtin declaration of
1860 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1861 /// pre-existing declaration exists no action takes place.
1862 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1863                                         IdentifierInfo *II) {
1864   if (!II->isStr("objc_msgSendSuper"))
1865     return;
1866   ASTContext &Context = ThisSema.Context;
1867 
1868   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1869                       SourceLocation(), Sema::LookupTagName);
1870   ThisSema.LookupName(Result, S);
1871   if (Result.getResultKind() == LookupResult::Found)
1872     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1873       Context.setObjCSuperType(Context.getTagDeclType(TD));
1874 }
1875 
1876 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1877   switch (Error) {
1878   case ASTContext::GE_None:
1879     return "";
1880   case ASTContext::GE_Missing_stdio:
1881     return "stdio.h";
1882   case ASTContext::GE_Missing_setjmp:
1883     return "setjmp.h";
1884   case ASTContext::GE_Missing_ucontext:
1885     return "ucontext.h";
1886   }
1887   llvm_unreachable("unhandled error kind");
1888 }
1889 
1890 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1891 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1892 /// if we're creating this built-in in anticipation of redeclaring the
1893 /// built-in.
1894 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1895                                      Scope *S, bool ForRedeclaration,
1896                                      SourceLocation Loc) {
1897   LookupPredefedObjCSuperType(*this, S, II);
1898 
1899   ASTContext::GetBuiltinTypeError Error;
1900   QualType R = Context.GetBuiltinType(ID, Error);
1901   if (Error) {
1902     if (ForRedeclaration)
1903       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1904           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1905     return nullptr;
1906   }
1907 
1908   if (!ForRedeclaration &&
1909       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1910        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1911     Diag(Loc, diag::ext_implicit_lib_function_decl)
1912         << Context.BuiltinInfo.getName(ID) << R;
1913     if (Context.BuiltinInfo.getHeaderName(ID) &&
1914         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1915       Diag(Loc, diag::note_include_header_or_declare)
1916           << Context.BuiltinInfo.getHeaderName(ID)
1917           << Context.BuiltinInfo.getName(ID);
1918   }
1919 
1920   if (R.isNull())
1921     return nullptr;
1922 
1923   DeclContext *Parent = Context.getTranslationUnitDecl();
1924   if (getLangOpts().CPlusPlus) {
1925     LinkageSpecDecl *CLinkageDecl =
1926         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1927                                 LinkageSpecDecl::lang_c, false);
1928     CLinkageDecl->setImplicit();
1929     Parent->addDecl(CLinkageDecl);
1930     Parent = CLinkageDecl;
1931   }
1932 
1933   FunctionDecl *New = FunctionDecl::Create(Context,
1934                                            Parent,
1935                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1936                                            SC_Extern,
1937                                            false,
1938                                            R->isFunctionProtoType());
1939   New->setImplicit();
1940 
1941   // Create Decl objects for each parameter, adding them to the
1942   // FunctionDecl.
1943   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1944     SmallVector<ParmVarDecl*, 16> Params;
1945     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1946       ParmVarDecl *parm =
1947           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1948                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1949                               SC_None, nullptr);
1950       parm->setScopeInfo(0, i);
1951       Params.push_back(parm);
1952     }
1953     New->setParams(Params);
1954   }
1955 
1956   AddKnownFunctionAttributes(New);
1957   RegisterLocallyScopedExternCDecl(New, S);
1958 
1959   // TUScope is the translation-unit scope to insert this function into.
1960   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1961   // relate Scopes to DeclContexts, and probably eliminate CurContext
1962   // entirely, but we're not there yet.
1963   DeclContext *SavedContext = CurContext;
1964   CurContext = Parent;
1965   PushOnScopeChains(New, TUScope);
1966   CurContext = SavedContext;
1967   return New;
1968 }
1969 
1970 /// Typedef declarations don't have linkage, but they still denote the same
1971 /// entity if their types are the same.
1972 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1973 /// isSameEntity.
1974 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1975                                                      TypedefNameDecl *Decl,
1976                                                      LookupResult &Previous) {
1977   // This is only interesting when modules are enabled.
1978   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1979     return;
1980 
1981   // Empty sets are uninteresting.
1982   if (Previous.empty())
1983     return;
1984 
1985   LookupResult::Filter Filter = Previous.makeFilter();
1986   while (Filter.hasNext()) {
1987     NamedDecl *Old = Filter.next();
1988 
1989     // Non-hidden declarations are never ignored.
1990     if (S.isVisible(Old))
1991       continue;
1992 
1993     // Declarations of the same entity are not ignored, even if they have
1994     // different linkages.
1995     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1996       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1997                                 Decl->getUnderlyingType()))
1998         continue;
1999 
2000       // If both declarations give a tag declaration a typedef name for linkage
2001       // purposes, then they declare the same entity.
2002       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2003           Decl->getAnonDeclWithTypedefName())
2004         continue;
2005     }
2006 
2007     Filter.erase();
2008   }
2009 
2010   Filter.done();
2011 }
2012 
2013 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2014   QualType OldType;
2015   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2016     OldType = OldTypedef->getUnderlyingType();
2017   else
2018     OldType = Context.getTypeDeclType(Old);
2019   QualType NewType = New->getUnderlyingType();
2020 
2021   if (NewType->isVariablyModifiedType()) {
2022     // Must not redefine a typedef with a variably-modified type.
2023     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2024     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2025       << Kind << NewType;
2026     if (Old->getLocation().isValid())
2027       notePreviousDefinition(Old, New->getLocation());
2028     New->setInvalidDecl();
2029     return true;
2030   }
2031 
2032   if (OldType != NewType &&
2033       !OldType->isDependentType() &&
2034       !NewType->isDependentType() &&
2035       !Context.hasSameType(OldType, NewType)) {
2036     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2037     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2038       << Kind << NewType << OldType;
2039     if (Old->getLocation().isValid())
2040       notePreviousDefinition(Old, New->getLocation());
2041     New->setInvalidDecl();
2042     return true;
2043   }
2044   return false;
2045 }
2046 
2047 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2048 /// same name and scope as a previous declaration 'Old'.  Figure out
2049 /// how to resolve this situation, merging decls or emitting
2050 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2051 ///
2052 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2053                                 LookupResult &OldDecls) {
2054   // If the new decl is known invalid already, don't bother doing any
2055   // merging checks.
2056   if (New->isInvalidDecl()) return;
2057 
2058   // Allow multiple definitions for ObjC built-in typedefs.
2059   // FIXME: Verify the underlying types are equivalent!
2060   if (getLangOpts().ObjC1) {
2061     const IdentifierInfo *TypeID = New->getIdentifier();
2062     switch (TypeID->getLength()) {
2063     default: break;
2064     case 2:
2065       {
2066         if (!TypeID->isStr("id"))
2067           break;
2068         QualType T = New->getUnderlyingType();
2069         if (!T->isPointerType())
2070           break;
2071         if (!T->isVoidPointerType()) {
2072           QualType PT = T->getAs<PointerType>()->getPointeeType();
2073           if (!PT->isStructureType())
2074             break;
2075         }
2076         Context.setObjCIdRedefinitionType(T);
2077         // Install the built-in type for 'id', ignoring the current definition.
2078         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2079         return;
2080       }
2081     case 5:
2082       if (!TypeID->isStr("Class"))
2083         break;
2084       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2085       // Install the built-in type for 'Class', ignoring the current definition.
2086       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2087       return;
2088     case 3:
2089       if (!TypeID->isStr("SEL"))
2090         break;
2091       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2092       // Install the built-in type for 'SEL', ignoring the current definition.
2093       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2094       return;
2095     }
2096     // Fall through - the typedef name was not a builtin type.
2097   }
2098 
2099   // Verify the old decl was also a type.
2100   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2101   if (!Old) {
2102     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2103       << New->getDeclName();
2104 
2105     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2106     if (OldD->getLocation().isValid())
2107       notePreviousDefinition(OldD, New->getLocation());
2108 
2109     return New->setInvalidDecl();
2110   }
2111 
2112   // If the old declaration is invalid, just give up here.
2113   if (Old->isInvalidDecl())
2114     return New->setInvalidDecl();
2115 
2116   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2117     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2118     auto *NewTag = New->getAnonDeclWithTypedefName();
2119     NamedDecl *Hidden = nullptr;
2120     if (OldTag && NewTag &&
2121         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2122         !hasVisibleDefinition(OldTag, &Hidden)) {
2123       // There is a definition of this tag, but it is not visible. Use it
2124       // instead of our tag.
2125       New->setTypeForDecl(OldTD->getTypeForDecl());
2126       if (OldTD->isModed())
2127         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2128                                     OldTD->getUnderlyingType());
2129       else
2130         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2131 
2132       // Make the old tag definition visible.
2133       makeMergedDefinitionVisible(Hidden);
2134 
2135       // If this was an unscoped enumeration, yank all of its enumerators
2136       // out of the scope.
2137       if (isa<EnumDecl>(NewTag)) {
2138         Scope *EnumScope = getNonFieldDeclScope(S);
2139         for (auto *D : NewTag->decls()) {
2140           auto *ED = cast<EnumConstantDecl>(D);
2141           assert(EnumScope->isDeclScope(ED));
2142           EnumScope->RemoveDecl(ED);
2143           IdResolver.RemoveDecl(ED);
2144           ED->getLexicalDeclContext()->removeDecl(ED);
2145         }
2146       }
2147     }
2148   }
2149 
2150   // If the typedef types are not identical, reject them in all languages and
2151   // with any extensions enabled.
2152   if (isIncompatibleTypedef(Old, New))
2153     return;
2154 
2155   // The types match.  Link up the redeclaration chain and merge attributes if
2156   // the old declaration was a typedef.
2157   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2158     New->setPreviousDecl(Typedef);
2159     mergeDeclAttributes(New, Old);
2160   }
2161 
2162   if (getLangOpts().MicrosoftExt)
2163     return;
2164 
2165   if (getLangOpts().CPlusPlus) {
2166     // C++ [dcl.typedef]p2:
2167     //   In a given non-class scope, a typedef specifier can be used to
2168     //   redefine the name of any type declared in that scope to refer
2169     //   to the type to which it already refers.
2170     if (!isa<CXXRecordDecl>(CurContext))
2171       return;
2172 
2173     // C++0x [dcl.typedef]p4:
2174     //   In a given class scope, a typedef specifier can be used to redefine
2175     //   any class-name declared in that scope that is not also a typedef-name
2176     //   to refer to the type to which it already refers.
2177     //
2178     // This wording came in via DR424, which was a correction to the
2179     // wording in DR56, which accidentally banned code like:
2180     //
2181     //   struct S {
2182     //     typedef struct A { } A;
2183     //   };
2184     //
2185     // in the C++03 standard. We implement the C++0x semantics, which
2186     // allow the above but disallow
2187     //
2188     //   struct S {
2189     //     typedef int I;
2190     //     typedef int I;
2191     //   };
2192     //
2193     // since that was the intent of DR56.
2194     if (!isa<TypedefNameDecl>(Old))
2195       return;
2196 
2197     Diag(New->getLocation(), diag::err_redefinition)
2198       << New->getDeclName();
2199     notePreviousDefinition(Old, New->getLocation());
2200     return New->setInvalidDecl();
2201   }
2202 
2203   // Modules always permit redefinition of typedefs, as does C11.
2204   if (getLangOpts().Modules || getLangOpts().C11)
2205     return;
2206 
2207   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2208   // is normally mapped to an error, but can be controlled with
2209   // -Wtypedef-redefinition.  If either the original or the redefinition is
2210   // in a system header, don't emit this for compatibility with GCC.
2211   if (getDiagnostics().getSuppressSystemWarnings() &&
2212       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2213       (Old->isImplicit() ||
2214        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2215        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2216     return;
2217 
2218   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2219     << New->getDeclName();
2220   notePreviousDefinition(Old, New->getLocation());
2221 }
2222 
2223 /// DeclhasAttr - returns true if decl Declaration already has the target
2224 /// attribute.
2225 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2226   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2227   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2228   for (const auto *i : D->attrs())
2229     if (i->getKind() == A->getKind()) {
2230       if (Ann) {
2231         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2232           return true;
2233         continue;
2234       }
2235       // FIXME: Don't hardcode this check
2236       if (OA && isa<OwnershipAttr>(i))
2237         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2238       return true;
2239     }
2240 
2241   return false;
2242 }
2243 
2244 static bool isAttributeTargetADefinition(Decl *D) {
2245   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2246     return VD->isThisDeclarationADefinition();
2247   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2248     return TD->isCompleteDefinition() || TD->isBeingDefined();
2249   return true;
2250 }
2251 
2252 /// Merge alignment attributes from \p Old to \p New, taking into account the
2253 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2254 ///
2255 /// \return \c true if any attributes were added to \p New.
2256 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2257   // Look for alignas attributes on Old, and pick out whichever attribute
2258   // specifies the strictest alignment requirement.
2259   AlignedAttr *OldAlignasAttr = nullptr;
2260   AlignedAttr *OldStrictestAlignAttr = nullptr;
2261   unsigned OldAlign = 0;
2262   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2263     // FIXME: We have no way of representing inherited dependent alignments
2264     // in a case like:
2265     //   template<int A, int B> struct alignas(A) X;
2266     //   template<int A, int B> struct alignas(B) X {};
2267     // For now, we just ignore any alignas attributes which are not on the
2268     // definition in such a case.
2269     if (I->isAlignmentDependent())
2270       return false;
2271 
2272     if (I->isAlignas())
2273       OldAlignasAttr = I;
2274 
2275     unsigned Align = I->getAlignment(S.Context);
2276     if (Align > OldAlign) {
2277       OldAlign = Align;
2278       OldStrictestAlignAttr = I;
2279     }
2280   }
2281 
2282   // Look for alignas attributes on New.
2283   AlignedAttr *NewAlignasAttr = nullptr;
2284   unsigned NewAlign = 0;
2285   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2286     if (I->isAlignmentDependent())
2287       return false;
2288 
2289     if (I->isAlignas())
2290       NewAlignasAttr = I;
2291 
2292     unsigned Align = I->getAlignment(S.Context);
2293     if (Align > NewAlign)
2294       NewAlign = Align;
2295   }
2296 
2297   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2298     // Both declarations have 'alignas' attributes. We require them to match.
2299     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2300     // fall short. (If two declarations both have alignas, they must both match
2301     // every definition, and so must match each other if there is a definition.)
2302 
2303     // If either declaration only contains 'alignas(0)' specifiers, then it
2304     // specifies the natural alignment for the type.
2305     if (OldAlign == 0 || NewAlign == 0) {
2306       QualType Ty;
2307       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2308         Ty = VD->getType();
2309       else
2310         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2311 
2312       if (OldAlign == 0)
2313         OldAlign = S.Context.getTypeAlign(Ty);
2314       if (NewAlign == 0)
2315         NewAlign = S.Context.getTypeAlign(Ty);
2316     }
2317 
2318     if (OldAlign != NewAlign) {
2319       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2320         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2321         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2322       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2323     }
2324   }
2325 
2326   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2327     // C++11 [dcl.align]p6:
2328     //   if any declaration of an entity has an alignment-specifier,
2329     //   every defining declaration of that entity shall specify an
2330     //   equivalent alignment.
2331     // C11 6.7.5/7:
2332     //   If the definition of an object does not have an alignment
2333     //   specifier, any other declaration of that object shall also
2334     //   have no alignment specifier.
2335     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2336       << OldAlignasAttr;
2337     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2338       << OldAlignasAttr;
2339   }
2340 
2341   bool AnyAdded = false;
2342 
2343   // Ensure we have an attribute representing the strictest alignment.
2344   if (OldAlign > NewAlign) {
2345     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2346     Clone->setInherited(true);
2347     New->addAttr(Clone);
2348     AnyAdded = true;
2349   }
2350 
2351   // Ensure we have an alignas attribute if the old declaration had one.
2352   if (OldAlignasAttr && !NewAlignasAttr &&
2353       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2354     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2355     Clone->setInherited(true);
2356     New->addAttr(Clone);
2357     AnyAdded = true;
2358   }
2359 
2360   return AnyAdded;
2361 }
2362 
2363 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2364                                const InheritableAttr *Attr,
2365                                Sema::AvailabilityMergeKind AMK) {
2366   // This function copies an attribute Attr from a previous declaration to the
2367   // new declaration D if the new declaration doesn't itself have that attribute
2368   // yet or if that attribute allows duplicates.
2369   // If you're adding a new attribute that requires logic different from
2370   // "use explicit attribute on decl if present, else use attribute from
2371   // previous decl", for example if the attribute needs to be consistent
2372   // between redeclarations, you need to call a custom merge function here.
2373   InheritableAttr *NewAttr = nullptr;
2374   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2375   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2376     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2377                                       AA->isImplicit(), AA->getIntroduced(),
2378                                       AA->getDeprecated(),
2379                                       AA->getObsoleted(), AA->getUnavailable(),
2380                                       AA->getMessage(), AA->getStrict(),
2381                                       AA->getReplacement(), AMK,
2382                                       AttrSpellingListIndex);
2383   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2384     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2385                                     AttrSpellingListIndex);
2386   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2387     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2388                                         AttrSpellingListIndex);
2389   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2390     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2391                                    AttrSpellingListIndex);
2392   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2393     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2394                                    AttrSpellingListIndex);
2395   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2396     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2397                                 FA->getFormatIdx(), FA->getFirstArg(),
2398                                 AttrSpellingListIndex);
2399   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2400     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2401                                  AttrSpellingListIndex);
2402   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2403     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2404                                        AttrSpellingListIndex,
2405                                        IA->getSemanticSpelling());
2406   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2407     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2408                                       &S.Context.Idents.get(AA->getSpelling()),
2409                                       AttrSpellingListIndex);
2410   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2411            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2412             isa<CUDAGlobalAttr>(Attr))) {
2413     // CUDA target attributes are part of function signature for
2414     // overloading purposes and must not be merged.
2415     return false;
2416   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2417     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2418   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2419     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2420   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2421     NewAttr = S.mergeInternalLinkageAttr(
2422         D, InternalLinkageA->getRange(),
2423         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2424         AttrSpellingListIndex);
2425   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2426     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2427                                 &S.Context.Idents.get(CommonA->getSpelling()),
2428                                 AttrSpellingListIndex);
2429   else if (isa<AlignedAttr>(Attr))
2430     // AlignedAttrs are handled separately, because we need to handle all
2431     // such attributes on a declaration at the same time.
2432     NewAttr = nullptr;
2433   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2434            (AMK == Sema::AMK_Override ||
2435             AMK == Sema::AMK_ProtocolImplementation))
2436     NewAttr = nullptr;
2437   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2438     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2439                               UA->getGuid());
2440   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2441     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2442 
2443   if (NewAttr) {
2444     NewAttr->setInherited(true);
2445     D->addAttr(NewAttr);
2446     if (isa<MSInheritanceAttr>(NewAttr))
2447       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2448     return true;
2449   }
2450 
2451   return false;
2452 }
2453 
2454 static const NamedDecl *getDefinition(const Decl *D) {
2455   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2456     return TD->getDefinition();
2457   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2458     const VarDecl *Def = VD->getDefinition();
2459     if (Def)
2460       return Def;
2461     return VD->getActingDefinition();
2462   }
2463   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2464     return FD->getDefinition();
2465   return nullptr;
2466 }
2467 
2468 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2469   for (const auto *Attribute : D->attrs())
2470     if (Attribute->getKind() == Kind)
2471       return true;
2472   return false;
2473 }
2474 
2475 /// checkNewAttributesAfterDef - If we already have a definition, check that
2476 /// there are no new attributes in this declaration.
2477 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2478   if (!New->hasAttrs())
2479     return;
2480 
2481   const NamedDecl *Def = getDefinition(Old);
2482   if (!Def || Def == New)
2483     return;
2484 
2485   AttrVec &NewAttributes = New->getAttrs();
2486   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2487     const Attr *NewAttribute = NewAttributes[I];
2488 
2489     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2490       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2491         Sema::SkipBodyInfo SkipBody;
2492         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2493 
2494         // If we're skipping this definition, drop the "alias" attribute.
2495         if (SkipBody.ShouldSkip) {
2496           NewAttributes.erase(NewAttributes.begin() + I);
2497           --E;
2498           continue;
2499         }
2500       } else {
2501         VarDecl *VD = cast<VarDecl>(New);
2502         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2503                                 VarDecl::TentativeDefinition
2504                             ? diag::err_alias_after_tentative
2505                             : diag::err_redefinition;
2506         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2507         if (Diag == diag::err_redefinition)
2508           S.notePreviousDefinition(Def, VD->getLocation());
2509         else
2510           S.Diag(Def->getLocation(), diag::note_previous_definition);
2511         VD->setInvalidDecl();
2512       }
2513       ++I;
2514       continue;
2515     }
2516 
2517     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2518       // Tentative definitions are only interesting for the alias check above.
2519       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2520         ++I;
2521         continue;
2522       }
2523     }
2524 
2525     if (hasAttribute(Def, NewAttribute->getKind())) {
2526       ++I;
2527       continue; // regular attr merging will take care of validating this.
2528     }
2529 
2530     if (isa<C11NoReturnAttr>(NewAttribute)) {
2531       // C's _Noreturn is allowed to be added to a function after it is defined.
2532       ++I;
2533       continue;
2534     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2535       if (AA->isAlignas()) {
2536         // C++11 [dcl.align]p6:
2537         //   if any declaration of an entity has an alignment-specifier,
2538         //   every defining declaration of that entity shall specify an
2539         //   equivalent alignment.
2540         // C11 6.7.5/7:
2541         //   If the definition of an object does not have an alignment
2542         //   specifier, any other declaration of that object shall also
2543         //   have no alignment specifier.
2544         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2545           << AA;
2546         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2547           << AA;
2548         NewAttributes.erase(NewAttributes.begin() + I);
2549         --E;
2550         continue;
2551       }
2552     }
2553 
2554     S.Diag(NewAttribute->getLocation(),
2555            diag::warn_attribute_precede_definition);
2556     S.Diag(Def->getLocation(), diag::note_previous_definition);
2557     NewAttributes.erase(NewAttributes.begin() + I);
2558     --E;
2559   }
2560 }
2561 
2562 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2563 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2564                                AvailabilityMergeKind AMK) {
2565   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2566     UsedAttr *NewAttr = OldAttr->clone(Context);
2567     NewAttr->setInherited(true);
2568     New->addAttr(NewAttr);
2569   }
2570 
2571   if (!Old->hasAttrs() && !New->hasAttrs())
2572     return;
2573 
2574   // Attributes declared post-definition are currently ignored.
2575   checkNewAttributesAfterDef(*this, New, Old);
2576 
2577   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2578     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2579       if (OldA->getLabel() != NewA->getLabel()) {
2580         // This redeclaration changes __asm__ label.
2581         Diag(New->getLocation(), diag::err_different_asm_label);
2582         Diag(OldA->getLocation(), diag::note_previous_declaration);
2583       }
2584     } else if (Old->isUsed()) {
2585       // This redeclaration adds an __asm__ label to a declaration that has
2586       // already been ODR-used.
2587       Diag(New->getLocation(), diag::err_late_asm_label_name)
2588         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2589     }
2590   }
2591 
2592   // Re-declaration cannot add abi_tag's.
2593   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2594     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2595       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2596         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2597                       NewTag) == OldAbiTagAttr->tags_end()) {
2598           Diag(NewAbiTagAttr->getLocation(),
2599                diag::err_new_abi_tag_on_redeclaration)
2600               << NewTag;
2601           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2602         }
2603       }
2604     } else {
2605       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2606       Diag(Old->getLocation(), diag::note_previous_declaration);
2607     }
2608   }
2609 
2610   if (!Old->hasAttrs())
2611     return;
2612 
2613   bool foundAny = New->hasAttrs();
2614 
2615   // Ensure that any moving of objects within the allocated map is done before
2616   // we process them.
2617   if (!foundAny) New->setAttrs(AttrVec());
2618 
2619   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2620     // Ignore deprecated/unavailable/availability attributes if requested.
2621     AvailabilityMergeKind LocalAMK = AMK_None;
2622     if (isa<DeprecatedAttr>(I) ||
2623         isa<UnavailableAttr>(I) ||
2624         isa<AvailabilityAttr>(I)) {
2625       switch (AMK) {
2626       case AMK_None:
2627         continue;
2628 
2629       case AMK_Redeclaration:
2630       case AMK_Override:
2631       case AMK_ProtocolImplementation:
2632         LocalAMK = AMK;
2633         break;
2634       }
2635     }
2636 
2637     // Already handled.
2638     if (isa<UsedAttr>(I))
2639       continue;
2640 
2641     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2642       foundAny = true;
2643   }
2644 
2645   if (mergeAlignedAttrs(*this, New, Old))
2646     foundAny = true;
2647 
2648   if (!foundAny) New->dropAttrs();
2649 }
2650 
2651 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2652 /// to the new one.
2653 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2654                                      const ParmVarDecl *oldDecl,
2655                                      Sema &S) {
2656   // C++11 [dcl.attr.depend]p2:
2657   //   The first declaration of a function shall specify the
2658   //   carries_dependency attribute for its declarator-id if any declaration
2659   //   of the function specifies the carries_dependency attribute.
2660   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2661   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2662     S.Diag(CDA->getLocation(),
2663            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2664     // Find the first declaration of the parameter.
2665     // FIXME: Should we build redeclaration chains for function parameters?
2666     const FunctionDecl *FirstFD =
2667       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2668     const ParmVarDecl *FirstVD =
2669       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2670     S.Diag(FirstVD->getLocation(),
2671            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2672   }
2673 
2674   if (!oldDecl->hasAttrs())
2675     return;
2676 
2677   bool foundAny = newDecl->hasAttrs();
2678 
2679   // Ensure that any moving of objects within the allocated map is
2680   // done before we process them.
2681   if (!foundAny) newDecl->setAttrs(AttrVec());
2682 
2683   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2684     if (!DeclHasAttr(newDecl, I)) {
2685       InheritableAttr *newAttr =
2686         cast<InheritableParamAttr>(I->clone(S.Context));
2687       newAttr->setInherited(true);
2688       newDecl->addAttr(newAttr);
2689       foundAny = true;
2690     }
2691   }
2692 
2693   if (!foundAny) newDecl->dropAttrs();
2694 }
2695 
2696 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2697                                 const ParmVarDecl *OldParam,
2698                                 Sema &S) {
2699   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2700     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2701       if (*Oldnullability != *Newnullability) {
2702         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2703           << DiagNullabilityKind(
2704                *Newnullability,
2705                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2706                 != 0))
2707           << DiagNullabilityKind(
2708                *Oldnullability,
2709                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2710                 != 0));
2711         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2712       }
2713     } else {
2714       QualType NewT = NewParam->getType();
2715       NewT = S.Context.getAttributedType(
2716                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2717                          NewT, NewT);
2718       NewParam->setType(NewT);
2719     }
2720   }
2721 }
2722 
2723 namespace {
2724 
2725 /// Used in MergeFunctionDecl to keep track of function parameters in
2726 /// C.
2727 struct GNUCompatibleParamWarning {
2728   ParmVarDecl *OldParm;
2729   ParmVarDecl *NewParm;
2730   QualType PromotedType;
2731 };
2732 
2733 } // end anonymous namespace
2734 
2735 /// getSpecialMember - get the special member enum for a method.
2736 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2737   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2738     if (Ctor->isDefaultConstructor())
2739       return Sema::CXXDefaultConstructor;
2740 
2741     if (Ctor->isCopyConstructor())
2742       return Sema::CXXCopyConstructor;
2743 
2744     if (Ctor->isMoveConstructor())
2745       return Sema::CXXMoveConstructor;
2746   } else if (isa<CXXDestructorDecl>(MD)) {
2747     return Sema::CXXDestructor;
2748   } else if (MD->isCopyAssignmentOperator()) {
2749     return Sema::CXXCopyAssignment;
2750   } else if (MD->isMoveAssignmentOperator()) {
2751     return Sema::CXXMoveAssignment;
2752   }
2753 
2754   return Sema::CXXInvalid;
2755 }
2756 
2757 // Determine whether the previous declaration was a definition, implicit
2758 // declaration, or a declaration.
2759 template <typename T>
2760 static std::pair<diag::kind, SourceLocation>
2761 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2762   diag::kind PrevDiag;
2763   SourceLocation OldLocation = Old->getLocation();
2764   if (Old->isThisDeclarationADefinition())
2765     PrevDiag = diag::note_previous_definition;
2766   else if (Old->isImplicit()) {
2767     PrevDiag = diag::note_previous_implicit_declaration;
2768     if (OldLocation.isInvalid())
2769       OldLocation = New->getLocation();
2770   } else
2771     PrevDiag = diag::note_previous_declaration;
2772   return std::make_pair(PrevDiag, OldLocation);
2773 }
2774 
2775 /// canRedefineFunction - checks if a function can be redefined. Currently,
2776 /// only extern inline functions can be redefined, and even then only in
2777 /// GNU89 mode.
2778 static bool canRedefineFunction(const FunctionDecl *FD,
2779                                 const LangOptions& LangOpts) {
2780   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2781           !LangOpts.CPlusPlus &&
2782           FD->isInlineSpecified() &&
2783           FD->getStorageClass() == SC_Extern);
2784 }
2785 
2786 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2787   const AttributedType *AT = T->getAs<AttributedType>();
2788   while (AT && !AT->isCallingConv())
2789     AT = AT->getModifiedType()->getAs<AttributedType>();
2790   return AT;
2791 }
2792 
2793 template <typename T>
2794 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2795   const DeclContext *DC = Old->getDeclContext();
2796   if (DC->isRecord())
2797     return false;
2798 
2799   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2800   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2801     return true;
2802   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2803     return true;
2804   return false;
2805 }
2806 
2807 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2808 static bool isExternC(VarTemplateDecl *) { return false; }
2809 
2810 /// \brief Check whether a redeclaration of an entity introduced by a
2811 /// using-declaration is valid, given that we know it's not an overload
2812 /// (nor a hidden tag declaration).
2813 template<typename ExpectedDecl>
2814 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2815                                    ExpectedDecl *New) {
2816   // C++11 [basic.scope.declarative]p4:
2817   //   Given a set of declarations in a single declarative region, each of
2818   //   which specifies the same unqualified name,
2819   //   -- they shall all refer to the same entity, or all refer to functions
2820   //      and function templates; or
2821   //   -- exactly one declaration shall declare a class name or enumeration
2822   //      name that is not a typedef name and the other declarations shall all
2823   //      refer to the same variable or enumerator, or all refer to functions
2824   //      and function templates; in this case the class name or enumeration
2825   //      name is hidden (3.3.10).
2826 
2827   // C++11 [namespace.udecl]p14:
2828   //   If a function declaration in namespace scope or block scope has the
2829   //   same name and the same parameter-type-list as a function introduced
2830   //   by a using-declaration, and the declarations do not declare the same
2831   //   function, the program is ill-formed.
2832 
2833   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2834   if (Old &&
2835       !Old->getDeclContext()->getRedeclContext()->Equals(
2836           New->getDeclContext()->getRedeclContext()) &&
2837       !(isExternC(Old) && isExternC(New)))
2838     Old = nullptr;
2839 
2840   if (!Old) {
2841     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2842     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2843     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2844     return true;
2845   }
2846   return false;
2847 }
2848 
2849 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2850                                             const FunctionDecl *B) {
2851   assert(A->getNumParams() == B->getNumParams());
2852 
2853   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2854     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2855     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2856     if (AttrA == AttrB)
2857       return true;
2858     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2859   };
2860 
2861   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2862 }
2863 
2864 /// MergeFunctionDecl - We just parsed a function 'New' from
2865 /// declarator D which has the same name and scope as a previous
2866 /// declaration 'Old'.  Figure out how to resolve this situation,
2867 /// merging decls or emitting diagnostics as appropriate.
2868 ///
2869 /// In C++, New and Old must be declarations that are not
2870 /// overloaded. Use IsOverload to determine whether New and Old are
2871 /// overloaded, and to select the Old declaration that New should be
2872 /// merged with.
2873 ///
2874 /// Returns true if there was an error, false otherwise.
2875 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2876                              Scope *S, bool MergeTypeWithOld) {
2877   // Verify the old decl was also a function.
2878   FunctionDecl *Old = OldD->getAsFunction();
2879   if (!Old) {
2880     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2881       if (New->getFriendObjectKind()) {
2882         Diag(New->getLocation(), diag::err_using_decl_friend);
2883         Diag(Shadow->getTargetDecl()->getLocation(),
2884              diag::note_using_decl_target);
2885         Diag(Shadow->getUsingDecl()->getLocation(),
2886              diag::note_using_decl) << 0;
2887         return true;
2888       }
2889 
2890       // Check whether the two declarations might declare the same function.
2891       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2892         return true;
2893       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2894     } else {
2895       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2896         << New->getDeclName();
2897       notePreviousDefinition(OldD, New->getLocation());
2898       return true;
2899     }
2900   }
2901 
2902   // If the old declaration is invalid, just give up here.
2903   if (Old->isInvalidDecl())
2904     return true;
2905 
2906   diag::kind PrevDiag;
2907   SourceLocation OldLocation;
2908   std::tie(PrevDiag, OldLocation) =
2909       getNoteDiagForInvalidRedeclaration(Old, New);
2910 
2911   // Don't complain about this if we're in GNU89 mode and the old function
2912   // is an extern inline function.
2913   // Don't complain about specializations. They are not supposed to have
2914   // storage classes.
2915   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2916       New->getStorageClass() == SC_Static &&
2917       Old->hasExternalFormalLinkage() &&
2918       !New->getTemplateSpecializationInfo() &&
2919       !canRedefineFunction(Old, getLangOpts())) {
2920     if (getLangOpts().MicrosoftExt) {
2921       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2922       Diag(OldLocation, PrevDiag);
2923     } else {
2924       Diag(New->getLocation(), diag::err_static_non_static) << New;
2925       Diag(OldLocation, PrevDiag);
2926       return true;
2927     }
2928   }
2929 
2930   if (New->hasAttr<InternalLinkageAttr>() &&
2931       !Old->hasAttr<InternalLinkageAttr>()) {
2932     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2933         << New->getDeclName();
2934     notePreviousDefinition(Old, New->getLocation());
2935     New->dropAttr<InternalLinkageAttr>();
2936   }
2937 
2938   if (!getLangOpts().CPlusPlus) {
2939     bool OldOvl = Old->hasAttr<OverloadableAttr>();
2940     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
2941       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
2942         << New << OldOvl;
2943 
2944       // Try our best to find a decl that actually has the overloadable
2945       // attribute for the note. In most cases (e.g. programs with only one
2946       // broken declaration/definition), this won't matter.
2947       //
2948       // FIXME: We could do this if we juggled some extra state in
2949       // OverloadableAttr, rather than just removing it.
2950       const Decl *DiagOld = Old;
2951       if (OldOvl) {
2952         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
2953           const auto *A = D->getAttr<OverloadableAttr>();
2954           return A && !A->isImplicit();
2955         });
2956         // If we've implicitly added *all* of the overloadable attrs to this
2957         // chain, emitting a "previous redecl" note is pointless.
2958         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
2959       }
2960 
2961       if (DiagOld)
2962         Diag(DiagOld->getLocation(),
2963              diag::note_attribute_overloadable_prev_overload)
2964           << OldOvl;
2965 
2966       if (OldOvl)
2967         New->addAttr(OverloadableAttr::CreateImplicit(Context));
2968       else
2969         New->dropAttr<OverloadableAttr>();
2970     }
2971   }
2972 
2973   // If a function is first declared with a calling convention, but is later
2974   // declared or defined without one, all following decls assume the calling
2975   // convention of the first.
2976   //
2977   // It's OK if a function is first declared without a calling convention,
2978   // but is later declared or defined with the default calling convention.
2979   //
2980   // To test if either decl has an explicit calling convention, we look for
2981   // AttributedType sugar nodes on the type as written.  If they are missing or
2982   // were canonicalized away, we assume the calling convention was implicit.
2983   //
2984   // Note also that we DO NOT return at this point, because we still have
2985   // other tests to run.
2986   QualType OldQType = Context.getCanonicalType(Old->getType());
2987   QualType NewQType = Context.getCanonicalType(New->getType());
2988   const FunctionType *OldType = cast<FunctionType>(OldQType);
2989   const FunctionType *NewType = cast<FunctionType>(NewQType);
2990   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2991   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2992   bool RequiresAdjustment = false;
2993 
2994   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2995     FunctionDecl *First = Old->getFirstDecl();
2996     const FunctionType *FT =
2997         First->getType().getCanonicalType()->castAs<FunctionType>();
2998     FunctionType::ExtInfo FI = FT->getExtInfo();
2999     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3000     if (!NewCCExplicit) {
3001       // Inherit the CC from the previous declaration if it was specified
3002       // there but not here.
3003       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3004       RequiresAdjustment = true;
3005     } else {
3006       // Calling conventions aren't compatible, so complain.
3007       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3008       Diag(New->getLocation(), diag::err_cconv_change)
3009         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3010         << !FirstCCExplicit
3011         << (!FirstCCExplicit ? "" :
3012             FunctionType::getNameForCallConv(FI.getCC()));
3013 
3014       // Put the note on the first decl, since it is the one that matters.
3015       Diag(First->getLocation(), diag::note_previous_declaration);
3016       return true;
3017     }
3018   }
3019 
3020   // FIXME: diagnose the other way around?
3021   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3022     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3023     RequiresAdjustment = true;
3024   }
3025 
3026   // Merge regparm attribute.
3027   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3028       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3029     if (NewTypeInfo.getHasRegParm()) {
3030       Diag(New->getLocation(), diag::err_regparm_mismatch)
3031         << NewType->getRegParmType()
3032         << OldType->getRegParmType();
3033       Diag(OldLocation, diag::note_previous_declaration);
3034       return true;
3035     }
3036 
3037     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3038     RequiresAdjustment = true;
3039   }
3040 
3041   // Merge ns_returns_retained attribute.
3042   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3043     if (NewTypeInfo.getProducesResult()) {
3044       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3045           << "'ns_returns_retained'";
3046       Diag(OldLocation, diag::note_previous_declaration);
3047       return true;
3048     }
3049 
3050     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3051     RequiresAdjustment = true;
3052   }
3053 
3054   if (OldTypeInfo.getNoCallerSavedRegs() !=
3055       NewTypeInfo.getNoCallerSavedRegs()) {
3056     if (NewTypeInfo.getNoCallerSavedRegs()) {
3057       AnyX86NoCallerSavedRegistersAttr *Attr =
3058         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3059       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3060       Diag(OldLocation, diag::note_previous_declaration);
3061       return true;
3062     }
3063 
3064     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3065     RequiresAdjustment = true;
3066   }
3067 
3068   if (RequiresAdjustment) {
3069     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3070     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3071     New->setType(QualType(AdjustedType, 0));
3072     NewQType = Context.getCanonicalType(New->getType());
3073     NewType = cast<FunctionType>(NewQType);
3074   }
3075 
3076   // If this redeclaration makes the function inline, we may need to add it to
3077   // UndefinedButUsed.
3078   if (!Old->isInlined() && New->isInlined() &&
3079       !New->hasAttr<GNUInlineAttr>() &&
3080       !getLangOpts().GNUInline &&
3081       Old->isUsed(false) &&
3082       !Old->isDefined() && !New->isThisDeclarationADefinition())
3083     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3084                                            SourceLocation()));
3085 
3086   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3087   // about it.
3088   if (New->hasAttr<GNUInlineAttr>() &&
3089       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3090     UndefinedButUsed.erase(Old->getCanonicalDecl());
3091   }
3092 
3093   // If pass_object_size params don't match up perfectly, this isn't a valid
3094   // redeclaration.
3095   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3096       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3097     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3098         << New->getDeclName();
3099     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3100     return true;
3101   }
3102 
3103   if (getLangOpts().CPlusPlus) {
3104     // C++1z [over.load]p2
3105     //   Certain function declarations cannot be overloaded:
3106     //     -- Function declarations that differ only in the return type,
3107     //        the exception specification, or both cannot be overloaded.
3108 
3109     // Check the exception specifications match. This may recompute the type of
3110     // both Old and New if it resolved exception specifications, so grab the
3111     // types again after this. Because this updates the type, we do this before
3112     // any of the other checks below, which may update the "de facto" NewQType
3113     // but do not necessarily update the type of New.
3114     if (CheckEquivalentExceptionSpec(Old, New))
3115       return true;
3116     OldQType = Context.getCanonicalType(Old->getType());
3117     NewQType = Context.getCanonicalType(New->getType());
3118 
3119     // Go back to the type source info to compare the declared return types,
3120     // per C++1y [dcl.type.auto]p13:
3121     //   Redeclarations or specializations of a function or function template
3122     //   with a declared return type that uses a placeholder type shall also
3123     //   use that placeholder, not a deduced type.
3124     QualType OldDeclaredReturnType =
3125         (Old->getTypeSourceInfo()
3126              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3127              : OldType)->getReturnType();
3128     QualType NewDeclaredReturnType =
3129         (New->getTypeSourceInfo()
3130              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3131              : NewType)->getReturnType();
3132     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3133         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3134           New->isLocalExternDecl())) {
3135       QualType ResQT;
3136       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3137           OldDeclaredReturnType->isObjCObjectPointerType())
3138         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3139       if (ResQT.isNull()) {
3140         if (New->isCXXClassMember() && New->isOutOfLine())
3141           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3142               << New << New->getReturnTypeSourceRange();
3143         else
3144           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3145               << New->getReturnTypeSourceRange();
3146         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3147                                     << Old->getReturnTypeSourceRange();
3148         return true;
3149       }
3150       else
3151         NewQType = ResQT;
3152     }
3153 
3154     QualType OldReturnType = OldType->getReturnType();
3155     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3156     if (OldReturnType != NewReturnType) {
3157       // If this function has a deduced return type and has already been
3158       // defined, copy the deduced value from the old declaration.
3159       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3160       if (OldAT && OldAT->isDeduced()) {
3161         New->setType(
3162             SubstAutoType(New->getType(),
3163                           OldAT->isDependentType() ? Context.DependentTy
3164                                                    : OldAT->getDeducedType()));
3165         NewQType = Context.getCanonicalType(
3166             SubstAutoType(NewQType,
3167                           OldAT->isDependentType() ? Context.DependentTy
3168                                                    : OldAT->getDeducedType()));
3169       }
3170     }
3171 
3172     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3173     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3174     if (OldMethod && NewMethod) {
3175       // Preserve triviality.
3176       NewMethod->setTrivial(OldMethod->isTrivial());
3177 
3178       // MSVC allows explicit template specialization at class scope:
3179       // 2 CXXMethodDecls referring to the same function will be injected.
3180       // We don't want a redeclaration error.
3181       bool IsClassScopeExplicitSpecialization =
3182                               OldMethod->isFunctionTemplateSpecialization() &&
3183                               NewMethod->isFunctionTemplateSpecialization();
3184       bool isFriend = NewMethod->getFriendObjectKind();
3185 
3186       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3187           !IsClassScopeExplicitSpecialization) {
3188         //    -- Member function declarations with the same name and the
3189         //       same parameter types cannot be overloaded if any of them
3190         //       is a static member function declaration.
3191         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3192           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3193           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3194           return true;
3195         }
3196 
3197         // C++ [class.mem]p1:
3198         //   [...] A member shall not be declared twice in the
3199         //   member-specification, except that a nested class or member
3200         //   class template can be declared and then later defined.
3201         if (!inTemplateInstantiation()) {
3202           unsigned NewDiag;
3203           if (isa<CXXConstructorDecl>(OldMethod))
3204             NewDiag = diag::err_constructor_redeclared;
3205           else if (isa<CXXDestructorDecl>(NewMethod))
3206             NewDiag = diag::err_destructor_redeclared;
3207           else if (isa<CXXConversionDecl>(NewMethod))
3208             NewDiag = diag::err_conv_function_redeclared;
3209           else
3210             NewDiag = diag::err_member_redeclared;
3211 
3212           Diag(New->getLocation(), NewDiag);
3213         } else {
3214           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3215             << New << New->getType();
3216         }
3217         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3218         return true;
3219 
3220       // Complain if this is an explicit declaration of a special
3221       // member that was initially declared implicitly.
3222       //
3223       // As an exception, it's okay to befriend such methods in order
3224       // to permit the implicit constructor/destructor/operator calls.
3225       } else if (OldMethod->isImplicit()) {
3226         if (isFriend) {
3227           NewMethod->setImplicit();
3228         } else {
3229           Diag(NewMethod->getLocation(),
3230                diag::err_definition_of_implicitly_declared_member)
3231             << New << getSpecialMember(OldMethod);
3232           return true;
3233         }
3234       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3235         Diag(NewMethod->getLocation(),
3236              diag::err_definition_of_explicitly_defaulted_member)
3237           << getSpecialMember(OldMethod);
3238         return true;
3239       }
3240     }
3241 
3242     // C++11 [dcl.attr.noreturn]p1:
3243     //   The first declaration of a function shall specify the noreturn
3244     //   attribute if any declaration of that function specifies the noreturn
3245     //   attribute.
3246     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3247     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3248       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3249       Diag(Old->getFirstDecl()->getLocation(),
3250            diag::note_noreturn_missing_first_decl);
3251     }
3252 
3253     // C++11 [dcl.attr.depend]p2:
3254     //   The first declaration of a function shall specify the
3255     //   carries_dependency attribute for its declarator-id if any declaration
3256     //   of the function specifies the carries_dependency attribute.
3257     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3258     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3259       Diag(CDA->getLocation(),
3260            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3261       Diag(Old->getFirstDecl()->getLocation(),
3262            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3263     }
3264 
3265     // (C++98 8.3.5p3):
3266     //   All declarations for a function shall agree exactly in both the
3267     //   return type and the parameter-type-list.
3268     // We also want to respect all the extended bits except noreturn.
3269 
3270     // noreturn should now match unless the old type info didn't have it.
3271     QualType OldQTypeForComparison = OldQType;
3272     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3273       auto *OldType = OldQType->castAs<FunctionProtoType>();
3274       const FunctionType *OldTypeForComparison
3275         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3276       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3277       assert(OldQTypeForComparison.isCanonical());
3278     }
3279 
3280     if (haveIncompatibleLanguageLinkages(Old, New)) {
3281       // As a special case, retain the language linkage from previous
3282       // declarations of a friend function as an extension.
3283       //
3284       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3285       // and is useful because there's otherwise no way to specify language
3286       // linkage within class scope.
3287       //
3288       // Check cautiously as the friend object kind isn't yet complete.
3289       if (New->getFriendObjectKind() != Decl::FOK_None) {
3290         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3291         Diag(OldLocation, PrevDiag);
3292       } else {
3293         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3294         Diag(OldLocation, PrevDiag);
3295         return true;
3296       }
3297     }
3298 
3299     if (OldQTypeForComparison == NewQType)
3300       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3301 
3302     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3303         New->isLocalExternDecl()) {
3304       // It's OK if we couldn't merge types for a local function declaraton
3305       // if either the old or new type is dependent. We'll merge the types
3306       // when we instantiate the function.
3307       return false;
3308     }
3309 
3310     // Fall through for conflicting redeclarations and redefinitions.
3311   }
3312 
3313   // C: Function types need to be compatible, not identical. This handles
3314   // duplicate function decls like "void f(int); void f(enum X);" properly.
3315   if (!getLangOpts().CPlusPlus &&
3316       Context.typesAreCompatible(OldQType, NewQType)) {
3317     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3318     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3319     const FunctionProtoType *OldProto = nullptr;
3320     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3321         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3322       // The old declaration provided a function prototype, but the
3323       // new declaration does not. Merge in the prototype.
3324       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3325       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3326       NewQType =
3327           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3328                                   OldProto->getExtProtoInfo());
3329       New->setType(NewQType);
3330       New->setHasInheritedPrototype();
3331 
3332       // Synthesize parameters with the same types.
3333       SmallVector<ParmVarDecl*, 16> Params;
3334       for (const auto &ParamType : OldProto->param_types()) {
3335         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3336                                                  SourceLocation(), nullptr,
3337                                                  ParamType, /*TInfo=*/nullptr,
3338                                                  SC_None, nullptr);
3339         Param->setScopeInfo(0, Params.size());
3340         Param->setImplicit();
3341         Params.push_back(Param);
3342       }
3343 
3344       New->setParams(Params);
3345     }
3346 
3347     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3348   }
3349 
3350   // GNU C permits a K&R definition to follow a prototype declaration
3351   // if the declared types of the parameters in the K&R definition
3352   // match the types in the prototype declaration, even when the
3353   // promoted types of the parameters from the K&R definition differ
3354   // from the types in the prototype. GCC then keeps the types from
3355   // the prototype.
3356   //
3357   // If a variadic prototype is followed by a non-variadic K&R definition,
3358   // the K&R definition becomes variadic.  This is sort of an edge case, but
3359   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3360   // C99 6.9.1p8.
3361   if (!getLangOpts().CPlusPlus &&
3362       Old->hasPrototype() && !New->hasPrototype() &&
3363       New->getType()->getAs<FunctionProtoType>() &&
3364       Old->getNumParams() == New->getNumParams()) {
3365     SmallVector<QualType, 16> ArgTypes;
3366     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3367     const FunctionProtoType *OldProto
3368       = Old->getType()->getAs<FunctionProtoType>();
3369     const FunctionProtoType *NewProto
3370       = New->getType()->getAs<FunctionProtoType>();
3371 
3372     // Determine whether this is the GNU C extension.
3373     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3374                                                NewProto->getReturnType());
3375     bool LooseCompatible = !MergedReturn.isNull();
3376     for (unsigned Idx = 0, End = Old->getNumParams();
3377          LooseCompatible && Idx != End; ++Idx) {
3378       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3379       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3380       if (Context.typesAreCompatible(OldParm->getType(),
3381                                      NewProto->getParamType(Idx))) {
3382         ArgTypes.push_back(NewParm->getType());
3383       } else if (Context.typesAreCompatible(OldParm->getType(),
3384                                             NewParm->getType(),
3385                                             /*CompareUnqualified=*/true)) {
3386         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3387                                            NewProto->getParamType(Idx) };
3388         Warnings.push_back(Warn);
3389         ArgTypes.push_back(NewParm->getType());
3390       } else
3391         LooseCompatible = false;
3392     }
3393 
3394     if (LooseCompatible) {
3395       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3396         Diag(Warnings[Warn].NewParm->getLocation(),
3397              diag::ext_param_promoted_not_compatible_with_prototype)
3398           << Warnings[Warn].PromotedType
3399           << Warnings[Warn].OldParm->getType();
3400         if (Warnings[Warn].OldParm->getLocation().isValid())
3401           Diag(Warnings[Warn].OldParm->getLocation(),
3402                diag::note_previous_declaration);
3403       }
3404 
3405       if (MergeTypeWithOld)
3406         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3407                                              OldProto->getExtProtoInfo()));
3408       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3409     }
3410 
3411     // Fall through to diagnose conflicting types.
3412   }
3413 
3414   // A function that has already been declared has been redeclared or
3415   // defined with a different type; show an appropriate diagnostic.
3416 
3417   // If the previous declaration was an implicitly-generated builtin
3418   // declaration, then at the very least we should use a specialized note.
3419   unsigned BuiltinID;
3420   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3421     // If it's actually a library-defined builtin function like 'malloc'
3422     // or 'printf', just warn about the incompatible redeclaration.
3423     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3424       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3425       Diag(OldLocation, diag::note_previous_builtin_declaration)
3426         << Old << Old->getType();
3427 
3428       // If this is a global redeclaration, just forget hereafter
3429       // about the "builtin-ness" of the function.
3430       //
3431       // Doing this for local extern declarations is problematic.  If
3432       // the builtin declaration remains visible, a second invalid
3433       // local declaration will produce a hard error; if it doesn't
3434       // remain visible, a single bogus local redeclaration (which is
3435       // actually only a warning) could break all the downstream code.
3436       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3437         New->getIdentifier()->revertBuiltin();
3438 
3439       return false;
3440     }
3441 
3442     PrevDiag = diag::note_previous_builtin_declaration;
3443   }
3444 
3445   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3446   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3447   return true;
3448 }
3449 
3450 /// \brief Completes the merge of two function declarations that are
3451 /// known to be compatible.
3452 ///
3453 /// This routine handles the merging of attributes and other
3454 /// properties of function declarations from the old declaration to
3455 /// the new declaration, once we know that New is in fact a
3456 /// redeclaration of Old.
3457 ///
3458 /// \returns false
3459 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3460                                         Scope *S, bool MergeTypeWithOld) {
3461   // Merge the attributes
3462   mergeDeclAttributes(New, Old);
3463 
3464   // Merge "pure" flag.
3465   if (Old->isPure())
3466     New->setPure();
3467 
3468   // Merge "used" flag.
3469   if (Old->getMostRecentDecl()->isUsed(false))
3470     New->setIsUsed();
3471 
3472   // Merge attributes from the parameters.  These can mismatch with K&R
3473   // declarations.
3474   if (New->getNumParams() == Old->getNumParams())
3475       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3476         ParmVarDecl *NewParam = New->getParamDecl(i);
3477         ParmVarDecl *OldParam = Old->getParamDecl(i);
3478         mergeParamDeclAttributes(NewParam, OldParam, *this);
3479         mergeParamDeclTypes(NewParam, OldParam, *this);
3480       }
3481 
3482   if (getLangOpts().CPlusPlus)
3483     return MergeCXXFunctionDecl(New, Old, S);
3484 
3485   // Merge the function types so the we get the composite types for the return
3486   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3487   // was visible.
3488   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3489   if (!Merged.isNull() && MergeTypeWithOld)
3490     New->setType(Merged);
3491 
3492   return false;
3493 }
3494 
3495 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3496                                 ObjCMethodDecl *oldMethod) {
3497   // Merge the attributes, including deprecated/unavailable
3498   AvailabilityMergeKind MergeKind =
3499     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3500       ? AMK_ProtocolImplementation
3501       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3502                                                        : AMK_Override;
3503 
3504   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3505 
3506   // Merge attributes from the parameters.
3507   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3508                                        oe = oldMethod->param_end();
3509   for (ObjCMethodDecl::param_iterator
3510          ni = newMethod->param_begin(), ne = newMethod->param_end();
3511        ni != ne && oi != oe; ++ni, ++oi)
3512     mergeParamDeclAttributes(*ni, *oi, *this);
3513 
3514   CheckObjCMethodOverride(newMethod, oldMethod);
3515 }
3516 
3517 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3518   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3519 
3520   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3521          ? diag::err_redefinition_different_type
3522          : diag::err_redeclaration_different_type)
3523     << New->getDeclName() << New->getType() << Old->getType();
3524 
3525   diag::kind PrevDiag;
3526   SourceLocation OldLocation;
3527   std::tie(PrevDiag, OldLocation)
3528     = getNoteDiagForInvalidRedeclaration(Old, New);
3529   S.Diag(OldLocation, PrevDiag);
3530   New->setInvalidDecl();
3531 }
3532 
3533 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3534 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3535 /// emitting diagnostics as appropriate.
3536 ///
3537 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3538 /// to here in AddInitializerToDecl. We can't check them before the initializer
3539 /// is attached.
3540 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3541                              bool MergeTypeWithOld) {
3542   if (New->isInvalidDecl() || Old->isInvalidDecl())
3543     return;
3544 
3545   QualType MergedT;
3546   if (getLangOpts().CPlusPlus) {
3547     if (New->getType()->isUndeducedType()) {
3548       // We don't know what the new type is until the initializer is attached.
3549       return;
3550     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3551       // These could still be something that needs exception specs checked.
3552       return MergeVarDeclExceptionSpecs(New, Old);
3553     }
3554     // C++ [basic.link]p10:
3555     //   [...] the types specified by all declarations referring to a given
3556     //   object or function shall be identical, except that declarations for an
3557     //   array object can specify array types that differ by the presence or
3558     //   absence of a major array bound (8.3.4).
3559     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3560       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3561       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3562 
3563       // We are merging a variable declaration New into Old. If it has an array
3564       // bound, and that bound differs from Old's bound, we should diagnose the
3565       // mismatch.
3566       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3567         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3568              PrevVD = PrevVD->getPreviousDecl()) {
3569           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3570           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3571             continue;
3572 
3573           if (!Context.hasSameType(NewArray, PrevVDTy))
3574             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3575         }
3576       }
3577 
3578       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3579         if (Context.hasSameType(OldArray->getElementType(),
3580                                 NewArray->getElementType()))
3581           MergedT = New->getType();
3582       }
3583       // FIXME: Check visibility. New is hidden but has a complete type. If New
3584       // has no array bound, it should not inherit one from Old, if Old is not
3585       // visible.
3586       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3587         if (Context.hasSameType(OldArray->getElementType(),
3588                                 NewArray->getElementType()))
3589           MergedT = Old->getType();
3590       }
3591     }
3592     else if (New->getType()->isObjCObjectPointerType() &&
3593                Old->getType()->isObjCObjectPointerType()) {
3594       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3595                                               Old->getType());
3596     }
3597   } else {
3598     // C 6.2.7p2:
3599     //   All declarations that refer to the same object or function shall have
3600     //   compatible type.
3601     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3602   }
3603   if (MergedT.isNull()) {
3604     // It's OK if we couldn't merge types if either type is dependent, for a
3605     // block-scope variable. In other cases (static data members of class
3606     // templates, variable templates, ...), we require the types to be
3607     // equivalent.
3608     // FIXME: The C++ standard doesn't say anything about this.
3609     if ((New->getType()->isDependentType() ||
3610          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3611       // If the old type was dependent, we can't merge with it, so the new type
3612       // becomes dependent for now. We'll reproduce the original type when we
3613       // instantiate the TypeSourceInfo for the variable.
3614       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3615         New->setType(Context.DependentTy);
3616       return;
3617     }
3618     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3619   }
3620 
3621   // Don't actually update the type on the new declaration if the old
3622   // declaration was an extern declaration in a different scope.
3623   if (MergeTypeWithOld)
3624     New->setType(MergedT);
3625 }
3626 
3627 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3628                                   LookupResult &Previous) {
3629   // C11 6.2.7p4:
3630   //   For an identifier with internal or external linkage declared
3631   //   in a scope in which a prior declaration of that identifier is
3632   //   visible, if the prior declaration specifies internal or
3633   //   external linkage, the type of the identifier at the later
3634   //   declaration becomes the composite type.
3635   //
3636   // If the variable isn't visible, we do not merge with its type.
3637   if (Previous.isShadowed())
3638     return false;
3639 
3640   if (S.getLangOpts().CPlusPlus) {
3641     // C++11 [dcl.array]p3:
3642     //   If there is a preceding declaration of the entity in the same
3643     //   scope in which the bound was specified, an omitted array bound
3644     //   is taken to be the same as in that earlier declaration.
3645     return NewVD->isPreviousDeclInSameBlockScope() ||
3646            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3647             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3648   } else {
3649     // If the old declaration was function-local, don't merge with its
3650     // type unless we're in the same function.
3651     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3652            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3653   }
3654 }
3655 
3656 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3657 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3658 /// situation, merging decls or emitting diagnostics as appropriate.
3659 ///
3660 /// Tentative definition rules (C99 6.9.2p2) are checked by
3661 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3662 /// definitions here, since the initializer hasn't been attached.
3663 ///
3664 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3665   // If the new decl is already invalid, don't do any other checking.
3666   if (New->isInvalidDecl())
3667     return;
3668 
3669   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3670     return;
3671 
3672   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3673 
3674   // Verify the old decl was also a variable or variable template.
3675   VarDecl *Old = nullptr;
3676   VarTemplateDecl *OldTemplate = nullptr;
3677   if (Previous.isSingleResult()) {
3678     if (NewTemplate) {
3679       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3680       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3681 
3682       if (auto *Shadow =
3683               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3684         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3685           return New->setInvalidDecl();
3686     } else {
3687       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3688 
3689       if (auto *Shadow =
3690               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3691         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3692           return New->setInvalidDecl();
3693     }
3694   }
3695   if (!Old) {
3696     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3697         << New->getDeclName();
3698     notePreviousDefinition(Previous.getRepresentativeDecl(),
3699                            New->getLocation());
3700     return New->setInvalidDecl();
3701   }
3702 
3703   // Ensure the template parameters are compatible.
3704   if (NewTemplate &&
3705       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3706                                       OldTemplate->getTemplateParameters(),
3707                                       /*Complain=*/true, TPL_TemplateMatch))
3708     return New->setInvalidDecl();
3709 
3710   // C++ [class.mem]p1:
3711   //   A member shall not be declared twice in the member-specification [...]
3712   //
3713   // Here, we need only consider static data members.
3714   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3715     Diag(New->getLocation(), diag::err_duplicate_member)
3716       << New->getIdentifier();
3717     Diag(Old->getLocation(), diag::note_previous_declaration);
3718     New->setInvalidDecl();
3719   }
3720 
3721   mergeDeclAttributes(New, Old);
3722   // Warn if an already-declared variable is made a weak_import in a subsequent
3723   // declaration
3724   if (New->hasAttr<WeakImportAttr>() &&
3725       Old->getStorageClass() == SC_None &&
3726       !Old->hasAttr<WeakImportAttr>()) {
3727     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3728     notePreviousDefinition(Old, New->getLocation());
3729     // Remove weak_import attribute on new declaration.
3730     New->dropAttr<WeakImportAttr>();
3731   }
3732 
3733   if (New->hasAttr<InternalLinkageAttr>() &&
3734       !Old->hasAttr<InternalLinkageAttr>()) {
3735     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3736         << New->getDeclName();
3737     notePreviousDefinition(Old, New->getLocation());
3738     New->dropAttr<InternalLinkageAttr>();
3739   }
3740 
3741   // Merge the types.
3742   VarDecl *MostRecent = Old->getMostRecentDecl();
3743   if (MostRecent != Old) {
3744     MergeVarDeclTypes(New, MostRecent,
3745                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3746     if (New->isInvalidDecl())
3747       return;
3748   }
3749 
3750   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3751   if (New->isInvalidDecl())
3752     return;
3753 
3754   diag::kind PrevDiag;
3755   SourceLocation OldLocation;
3756   std::tie(PrevDiag, OldLocation) =
3757       getNoteDiagForInvalidRedeclaration(Old, New);
3758 
3759   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3760   if (New->getStorageClass() == SC_Static &&
3761       !New->isStaticDataMember() &&
3762       Old->hasExternalFormalLinkage()) {
3763     if (getLangOpts().MicrosoftExt) {
3764       Diag(New->getLocation(), diag::ext_static_non_static)
3765           << New->getDeclName();
3766       Diag(OldLocation, PrevDiag);
3767     } else {
3768       Diag(New->getLocation(), diag::err_static_non_static)
3769           << New->getDeclName();
3770       Diag(OldLocation, PrevDiag);
3771       return New->setInvalidDecl();
3772     }
3773   }
3774   // C99 6.2.2p4:
3775   //   For an identifier declared with the storage-class specifier
3776   //   extern in a scope in which a prior declaration of that
3777   //   identifier is visible,23) if the prior declaration specifies
3778   //   internal or external linkage, the linkage of the identifier at
3779   //   the later declaration is the same as the linkage specified at
3780   //   the prior declaration. If no prior declaration is visible, or
3781   //   if the prior declaration specifies no linkage, then the
3782   //   identifier has external linkage.
3783   if (New->hasExternalStorage() && Old->hasLinkage())
3784     /* Okay */;
3785   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3786            !New->isStaticDataMember() &&
3787            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3788     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3789     Diag(OldLocation, PrevDiag);
3790     return New->setInvalidDecl();
3791   }
3792 
3793   // Check if extern is followed by non-extern and vice-versa.
3794   if (New->hasExternalStorage() &&
3795       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3796     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3797     Diag(OldLocation, PrevDiag);
3798     return New->setInvalidDecl();
3799   }
3800   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3801       !New->hasExternalStorage()) {
3802     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3803     Diag(OldLocation, PrevDiag);
3804     return New->setInvalidDecl();
3805   }
3806 
3807   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3808 
3809   // FIXME: The test for external storage here seems wrong? We still
3810   // need to check for mismatches.
3811   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3812       // Don't complain about out-of-line definitions of static members.
3813       !(Old->getLexicalDeclContext()->isRecord() &&
3814         !New->getLexicalDeclContext()->isRecord())) {
3815     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3816     Diag(OldLocation, PrevDiag);
3817     return New->setInvalidDecl();
3818   }
3819 
3820   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3821     if (VarDecl *Def = Old->getDefinition()) {
3822       // C++1z [dcl.fcn.spec]p4:
3823       //   If the definition of a variable appears in a translation unit before
3824       //   its first declaration as inline, the program is ill-formed.
3825       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3826       Diag(Def->getLocation(), diag::note_previous_definition);
3827     }
3828   }
3829 
3830   // If this redeclaration makes the function inline, we may need to add it to
3831   // UndefinedButUsed.
3832   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3833       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3834     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3835                                            SourceLocation()));
3836 
3837   if (New->getTLSKind() != Old->getTLSKind()) {
3838     if (!Old->getTLSKind()) {
3839       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3840       Diag(OldLocation, PrevDiag);
3841     } else if (!New->getTLSKind()) {
3842       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3843       Diag(OldLocation, PrevDiag);
3844     } else {
3845       // Do not allow redeclaration to change the variable between requiring
3846       // static and dynamic initialization.
3847       // FIXME: GCC allows this, but uses the TLS keyword on the first
3848       // declaration to determine the kind. Do we need to be compatible here?
3849       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3850         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3851       Diag(OldLocation, PrevDiag);
3852     }
3853   }
3854 
3855   // C++ doesn't have tentative definitions, so go right ahead and check here.
3856   if (getLangOpts().CPlusPlus &&
3857       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3858     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3859         Old->getCanonicalDecl()->isConstexpr()) {
3860       // This definition won't be a definition any more once it's been merged.
3861       Diag(New->getLocation(),
3862            diag::warn_deprecated_redundant_constexpr_static_def);
3863     } else if (VarDecl *Def = Old->getDefinition()) {
3864       if (checkVarDeclRedefinition(Def, New))
3865         return;
3866     }
3867   }
3868 
3869   if (haveIncompatibleLanguageLinkages(Old, New)) {
3870     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3871     Diag(OldLocation, PrevDiag);
3872     New->setInvalidDecl();
3873     return;
3874   }
3875 
3876   // Merge "used" flag.
3877   if (Old->getMostRecentDecl()->isUsed(false))
3878     New->setIsUsed();
3879 
3880   // Keep a chain of previous declarations.
3881   New->setPreviousDecl(Old);
3882   if (NewTemplate)
3883     NewTemplate->setPreviousDecl(OldTemplate);
3884 
3885   // Inherit access appropriately.
3886   New->setAccess(Old->getAccess());
3887   if (NewTemplate)
3888     NewTemplate->setAccess(New->getAccess());
3889 
3890   if (Old->isInline())
3891     New->setImplicitlyInline();
3892 }
3893 
3894 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3895   SourceManager &SrcMgr = getSourceManager();
3896   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3897   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3898   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3899   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3900   auto &HSI = PP.getHeaderSearchInfo();
3901   StringRef HdrFilename =
3902       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3903 
3904   auto noteFromModuleOrInclude = [&](Module *Mod,
3905                                      SourceLocation IncLoc) -> bool {
3906     // Redefinition errors with modules are common with non modular mapped
3907     // headers, example: a non-modular header H in module A that also gets
3908     // included directly in a TU. Pointing twice to the same header/definition
3909     // is confusing, try to get better diagnostics when modules is on.
3910     if (IncLoc.isValid()) {
3911       if (Mod) {
3912         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3913             << HdrFilename.str() << Mod->getFullModuleName();
3914         if (!Mod->DefinitionLoc.isInvalid())
3915           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3916               << Mod->getFullModuleName();
3917       } else {
3918         Diag(IncLoc, diag::note_redefinition_include_same_file)
3919             << HdrFilename.str();
3920       }
3921       return true;
3922     }
3923 
3924     return false;
3925   };
3926 
3927   // Is it the same file and same offset? Provide more information on why
3928   // this leads to a redefinition error.
3929   bool EmittedDiag = false;
3930   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3931     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3932     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3933     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3934     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3935 
3936     // If the header has no guards, emit a note suggesting one.
3937     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3938       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3939 
3940     if (EmittedDiag)
3941       return;
3942   }
3943 
3944   // Redefinition coming from different files or couldn't do better above.
3945   Diag(Old->getLocation(), diag::note_previous_definition);
3946 }
3947 
3948 /// We've just determined that \p Old and \p New both appear to be definitions
3949 /// of the same variable. Either diagnose or fix the problem.
3950 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3951   if (!hasVisibleDefinition(Old) &&
3952       (New->getFormalLinkage() == InternalLinkage ||
3953        New->isInline() ||
3954        New->getDescribedVarTemplate() ||
3955        New->getNumTemplateParameterLists() ||
3956        New->getDeclContext()->isDependentContext())) {
3957     // The previous definition is hidden, and multiple definitions are
3958     // permitted (in separate TUs). Demote this to a declaration.
3959     New->demoteThisDefinitionToDeclaration();
3960 
3961     // Make the canonical definition visible.
3962     if (auto *OldTD = Old->getDescribedVarTemplate())
3963       makeMergedDefinitionVisible(OldTD);
3964     makeMergedDefinitionVisible(Old);
3965     return false;
3966   } else {
3967     Diag(New->getLocation(), diag::err_redefinition) << New;
3968     notePreviousDefinition(Old, New->getLocation());
3969     New->setInvalidDecl();
3970     return true;
3971   }
3972 }
3973 
3974 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3975 /// no declarator (e.g. "struct foo;") is parsed.
3976 Decl *
3977 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3978                                  RecordDecl *&AnonRecord) {
3979   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3980                                     AnonRecord);
3981 }
3982 
3983 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3984 // disambiguate entities defined in different scopes.
3985 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3986 // compatibility.
3987 // We will pick our mangling number depending on which version of MSVC is being
3988 // targeted.
3989 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3990   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3991              ? S->getMSCurManglingNumber()
3992              : S->getMSLastManglingNumber();
3993 }
3994 
3995 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3996   if (!Context.getLangOpts().CPlusPlus)
3997     return;
3998 
3999   if (isa<CXXRecordDecl>(Tag->getParent())) {
4000     // If this tag is the direct child of a class, number it if
4001     // it is anonymous.
4002     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4003       return;
4004     MangleNumberingContext &MCtx =
4005         Context.getManglingNumberContext(Tag->getParent());
4006     Context.setManglingNumber(
4007         Tag, MCtx.getManglingNumber(
4008                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4009     return;
4010   }
4011 
4012   // If this tag isn't a direct child of a class, number it if it is local.
4013   Decl *ManglingContextDecl;
4014   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4015           Tag->getDeclContext(), ManglingContextDecl)) {
4016     Context.setManglingNumber(
4017         Tag, MCtx->getManglingNumber(
4018                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4019   }
4020 }
4021 
4022 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4023                                         TypedefNameDecl *NewTD) {
4024   if (TagFromDeclSpec->isInvalidDecl())
4025     return;
4026 
4027   // Do nothing if the tag already has a name for linkage purposes.
4028   if (TagFromDeclSpec->hasNameForLinkage())
4029     return;
4030 
4031   // A well-formed anonymous tag must always be a TUK_Definition.
4032   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4033 
4034   // The type must match the tag exactly;  no qualifiers allowed.
4035   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4036                            Context.getTagDeclType(TagFromDeclSpec))) {
4037     if (getLangOpts().CPlusPlus)
4038       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4039     return;
4040   }
4041 
4042   // If we've already computed linkage for the anonymous tag, then
4043   // adding a typedef name for the anonymous decl can change that
4044   // linkage, which might be a serious problem.  Diagnose this as
4045   // unsupported and ignore the typedef name.  TODO: we should
4046   // pursue this as a language defect and establish a formal rule
4047   // for how to handle it.
4048   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4049     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4050 
4051     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4052     tagLoc = getLocForEndOfToken(tagLoc);
4053 
4054     llvm::SmallString<40> textToInsert;
4055     textToInsert += ' ';
4056     textToInsert += NewTD->getIdentifier()->getName();
4057     Diag(tagLoc, diag::note_typedef_changes_linkage)
4058         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4059     return;
4060   }
4061 
4062   // Otherwise, set this is the anon-decl typedef for the tag.
4063   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4064 }
4065 
4066 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4067   switch (T) {
4068   case DeclSpec::TST_class:
4069     return 0;
4070   case DeclSpec::TST_struct:
4071     return 1;
4072   case DeclSpec::TST_interface:
4073     return 2;
4074   case DeclSpec::TST_union:
4075     return 3;
4076   case DeclSpec::TST_enum:
4077     return 4;
4078   default:
4079     llvm_unreachable("unexpected type specifier");
4080   }
4081 }
4082 
4083 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4084 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4085 /// parameters to cope with template friend declarations.
4086 Decl *
4087 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4088                                  MultiTemplateParamsArg TemplateParams,
4089                                  bool IsExplicitInstantiation,
4090                                  RecordDecl *&AnonRecord) {
4091   Decl *TagD = nullptr;
4092   TagDecl *Tag = nullptr;
4093   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4094       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4095       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4096       DS.getTypeSpecType() == DeclSpec::TST_union ||
4097       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4098     TagD = DS.getRepAsDecl();
4099 
4100     if (!TagD) // We probably had an error
4101       return nullptr;
4102 
4103     // Note that the above type specs guarantee that the
4104     // type rep is a Decl, whereas in many of the others
4105     // it's a Type.
4106     if (isa<TagDecl>(TagD))
4107       Tag = cast<TagDecl>(TagD);
4108     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4109       Tag = CTD->getTemplatedDecl();
4110   }
4111 
4112   if (Tag) {
4113     handleTagNumbering(Tag, S);
4114     Tag->setFreeStanding();
4115     if (Tag->isInvalidDecl())
4116       return Tag;
4117   }
4118 
4119   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4120     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4121     // or incomplete types shall not be restrict-qualified."
4122     if (TypeQuals & DeclSpec::TQ_restrict)
4123       Diag(DS.getRestrictSpecLoc(),
4124            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4125            << DS.getSourceRange();
4126   }
4127 
4128   if (DS.isInlineSpecified())
4129     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4130         << getLangOpts().CPlusPlus1z;
4131 
4132   if (DS.isConstexprSpecified()) {
4133     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4134     // and definitions of functions and variables.
4135     if (Tag)
4136       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4137           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4138     else
4139       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4140     // Don't emit warnings after this error.
4141     return TagD;
4142   }
4143 
4144   if (DS.isConceptSpecified()) {
4145     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4146     // either a function concept and its definition or a variable concept and
4147     // its initializer.
4148     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4149     return TagD;
4150   }
4151 
4152   DiagnoseFunctionSpecifiers(DS);
4153 
4154   if (DS.isFriendSpecified()) {
4155     // If we're dealing with a decl but not a TagDecl, assume that
4156     // whatever routines created it handled the friendship aspect.
4157     if (TagD && !Tag)
4158       return nullptr;
4159     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4160   }
4161 
4162   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4163   bool IsExplicitSpecialization =
4164     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4165   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4166       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4167       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4168     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4169     // nested-name-specifier unless it is an explicit instantiation
4170     // or an explicit specialization.
4171     //
4172     // FIXME: We allow class template partial specializations here too, per the
4173     // obvious intent of DR1819.
4174     //
4175     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4176     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4177         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4178     return nullptr;
4179   }
4180 
4181   // Track whether this decl-specifier declares anything.
4182   bool DeclaresAnything = true;
4183 
4184   // Handle anonymous struct definitions.
4185   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4186     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4187         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4188       if (getLangOpts().CPlusPlus ||
4189           Record->getDeclContext()->isRecord()) {
4190         // If CurContext is a DeclContext that can contain statements,
4191         // RecursiveASTVisitor won't visit the decls that
4192         // BuildAnonymousStructOrUnion() will put into CurContext.
4193         // Also store them here so that they can be part of the
4194         // DeclStmt that gets created in this case.
4195         // FIXME: Also return the IndirectFieldDecls created by
4196         // BuildAnonymousStructOr union, for the same reason?
4197         if (CurContext->isFunctionOrMethod())
4198           AnonRecord = Record;
4199         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4200                                            Context.getPrintingPolicy());
4201       }
4202 
4203       DeclaresAnything = false;
4204     }
4205   }
4206 
4207   // C11 6.7.2.1p2:
4208   //   A struct-declaration that does not declare an anonymous structure or
4209   //   anonymous union shall contain a struct-declarator-list.
4210   //
4211   // This rule also existed in C89 and C99; the grammar for struct-declaration
4212   // did not permit a struct-declaration without a struct-declarator-list.
4213   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4214       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4215     // Check for Microsoft C extension: anonymous struct/union member.
4216     // Handle 2 kinds of anonymous struct/union:
4217     //   struct STRUCT;
4218     //   union UNION;
4219     // and
4220     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4221     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4222     if ((Tag && Tag->getDeclName()) ||
4223         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4224       RecordDecl *Record = nullptr;
4225       if (Tag)
4226         Record = dyn_cast<RecordDecl>(Tag);
4227       else if (const RecordType *RT =
4228                    DS.getRepAsType().get()->getAsStructureType())
4229         Record = RT->getDecl();
4230       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4231         Record = UT->getDecl();
4232 
4233       if (Record && getLangOpts().MicrosoftExt) {
4234         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4235           << Record->isUnion() << DS.getSourceRange();
4236         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4237       }
4238 
4239       DeclaresAnything = false;
4240     }
4241   }
4242 
4243   // Skip all the checks below if we have a type error.
4244   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4245       (TagD && TagD->isInvalidDecl()))
4246     return TagD;
4247 
4248   if (getLangOpts().CPlusPlus &&
4249       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4250     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4251       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4252           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4253         DeclaresAnything = false;
4254 
4255   if (!DS.isMissingDeclaratorOk()) {
4256     // Customize diagnostic for a typedef missing a name.
4257     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4258       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4259         << DS.getSourceRange();
4260     else
4261       DeclaresAnything = false;
4262   }
4263 
4264   if (DS.isModulePrivateSpecified() &&
4265       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4266     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4267       << Tag->getTagKind()
4268       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4269 
4270   ActOnDocumentableDecl(TagD);
4271 
4272   // C 6.7/2:
4273   //   A declaration [...] shall declare at least a declarator [...], a tag,
4274   //   or the members of an enumeration.
4275   // C++ [dcl.dcl]p3:
4276   //   [If there are no declarators], and except for the declaration of an
4277   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4278   //   names into the program, or shall redeclare a name introduced by a
4279   //   previous declaration.
4280   if (!DeclaresAnything) {
4281     // In C, we allow this as a (popular) extension / bug. Don't bother
4282     // producing further diagnostics for redundant qualifiers after this.
4283     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4284     return TagD;
4285   }
4286 
4287   // C++ [dcl.stc]p1:
4288   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4289   //   init-declarator-list of the declaration shall not be empty.
4290   // C++ [dcl.fct.spec]p1:
4291   //   If a cv-qualifier appears in a decl-specifier-seq, the
4292   //   init-declarator-list of the declaration shall not be empty.
4293   //
4294   // Spurious qualifiers here appear to be valid in C.
4295   unsigned DiagID = diag::warn_standalone_specifier;
4296   if (getLangOpts().CPlusPlus)
4297     DiagID = diag::ext_standalone_specifier;
4298 
4299   // Note that a linkage-specification sets a storage class, but
4300   // 'extern "C" struct foo;' is actually valid and not theoretically
4301   // useless.
4302   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4303     if (SCS == DeclSpec::SCS_mutable)
4304       // Since mutable is not a viable storage class specifier in C, there is
4305       // no reason to treat it as an extension. Instead, diagnose as an error.
4306       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4307     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4308       Diag(DS.getStorageClassSpecLoc(), DiagID)
4309         << DeclSpec::getSpecifierName(SCS);
4310   }
4311 
4312   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4313     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4314       << DeclSpec::getSpecifierName(TSCS);
4315   if (DS.getTypeQualifiers()) {
4316     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4317       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4318     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4319       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4320     // Restrict is covered above.
4321     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4322       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4323     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4324       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4325   }
4326 
4327   // Warn about ignored type attributes, for example:
4328   // __attribute__((aligned)) struct A;
4329   // Attributes should be placed after tag to apply to type declaration.
4330   if (!DS.getAttributes().empty()) {
4331     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4332     if (TypeSpecType == DeclSpec::TST_class ||
4333         TypeSpecType == DeclSpec::TST_struct ||
4334         TypeSpecType == DeclSpec::TST_interface ||
4335         TypeSpecType == DeclSpec::TST_union ||
4336         TypeSpecType == DeclSpec::TST_enum) {
4337       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4338            attrs = attrs->getNext())
4339         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4340             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4341     }
4342   }
4343 
4344   return TagD;
4345 }
4346 
4347 /// We are trying to inject an anonymous member into the given scope;
4348 /// check if there's an existing declaration that can't be overloaded.
4349 ///
4350 /// \return true if this is a forbidden redeclaration
4351 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4352                                          Scope *S,
4353                                          DeclContext *Owner,
4354                                          DeclarationName Name,
4355                                          SourceLocation NameLoc,
4356                                          bool IsUnion) {
4357   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4358                  Sema::ForRedeclaration);
4359   if (!SemaRef.LookupName(R, S)) return false;
4360 
4361   // Pick a representative declaration.
4362   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4363   assert(PrevDecl && "Expected a non-null Decl");
4364 
4365   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4366     return false;
4367 
4368   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4369     << IsUnion << Name;
4370   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4371 
4372   return true;
4373 }
4374 
4375 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4376 /// anonymous struct or union AnonRecord into the owning context Owner
4377 /// and scope S. This routine will be invoked just after we realize
4378 /// that an unnamed union or struct is actually an anonymous union or
4379 /// struct, e.g.,
4380 ///
4381 /// @code
4382 /// union {
4383 ///   int i;
4384 ///   float f;
4385 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4386 ///    // f into the surrounding scope.x
4387 /// @endcode
4388 ///
4389 /// This routine is recursive, injecting the names of nested anonymous
4390 /// structs/unions into the owning context and scope as well.
4391 static bool
4392 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4393                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4394                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4395   bool Invalid = false;
4396 
4397   // Look every FieldDecl and IndirectFieldDecl with a name.
4398   for (auto *D : AnonRecord->decls()) {
4399     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4400         cast<NamedDecl>(D)->getDeclName()) {
4401       ValueDecl *VD = cast<ValueDecl>(D);
4402       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4403                                        VD->getLocation(),
4404                                        AnonRecord->isUnion())) {
4405         // C++ [class.union]p2:
4406         //   The names of the members of an anonymous union shall be
4407         //   distinct from the names of any other entity in the
4408         //   scope in which the anonymous union is declared.
4409         Invalid = true;
4410       } else {
4411         // C++ [class.union]p2:
4412         //   For the purpose of name lookup, after the anonymous union
4413         //   definition, the members of the anonymous union are
4414         //   considered to have been defined in the scope in which the
4415         //   anonymous union is declared.
4416         unsigned OldChainingSize = Chaining.size();
4417         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4418           Chaining.append(IF->chain_begin(), IF->chain_end());
4419         else
4420           Chaining.push_back(VD);
4421 
4422         assert(Chaining.size() >= 2);
4423         NamedDecl **NamedChain =
4424           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4425         for (unsigned i = 0; i < Chaining.size(); i++)
4426           NamedChain[i] = Chaining[i];
4427 
4428         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4429             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4430             VD->getType(), {NamedChain, Chaining.size()});
4431 
4432         for (const auto *Attr : VD->attrs())
4433           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4434 
4435         IndirectField->setAccess(AS);
4436         IndirectField->setImplicit();
4437         SemaRef.PushOnScopeChains(IndirectField, S);
4438 
4439         // That includes picking up the appropriate access specifier.
4440         if (AS != AS_none) IndirectField->setAccess(AS);
4441 
4442         Chaining.resize(OldChainingSize);
4443       }
4444     }
4445   }
4446 
4447   return Invalid;
4448 }
4449 
4450 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4451 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4452 /// illegal input values are mapped to SC_None.
4453 static StorageClass
4454 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4455   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4456   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4457          "Parser allowed 'typedef' as storage class VarDecl.");
4458   switch (StorageClassSpec) {
4459   case DeclSpec::SCS_unspecified:    return SC_None;
4460   case DeclSpec::SCS_extern:
4461     if (DS.isExternInLinkageSpec())
4462       return SC_None;
4463     return SC_Extern;
4464   case DeclSpec::SCS_static:         return SC_Static;
4465   case DeclSpec::SCS_auto:           return SC_Auto;
4466   case DeclSpec::SCS_register:       return SC_Register;
4467   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4468     // Illegal SCSs map to None: error reporting is up to the caller.
4469   case DeclSpec::SCS_mutable:        // Fall through.
4470   case DeclSpec::SCS_typedef:        return SC_None;
4471   }
4472   llvm_unreachable("unknown storage class specifier");
4473 }
4474 
4475 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4476   assert(Record->hasInClassInitializer());
4477 
4478   for (const auto *I : Record->decls()) {
4479     const auto *FD = dyn_cast<FieldDecl>(I);
4480     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4481       FD = IFD->getAnonField();
4482     if (FD && FD->hasInClassInitializer())
4483       return FD->getLocation();
4484   }
4485 
4486   llvm_unreachable("couldn't find in-class initializer");
4487 }
4488 
4489 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4490                                       SourceLocation DefaultInitLoc) {
4491   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4492     return;
4493 
4494   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4495   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4496 }
4497 
4498 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4499                                       CXXRecordDecl *AnonUnion) {
4500   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4501     return;
4502 
4503   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4504 }
4505 
4506 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4507 /// anonymous structure or union. Anonymous unions are a C++ feature
4508 /// (C++ [class.union]) and a C11 feature; anonymous structures
4509 /// are a C11 feature and GNU C++ extension.
4510 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4511                                         AccessSpecifier AS,
4512                                         RecordDecl *Record,
4513                                         const PrintingPolicy &Policy) {
4514   DeclContext *Owner = Record->getDeclContext();
4515 
4516   // Diagnose whether this anonymous struct/union is an extension.
4517   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4518     Diag(Record->getLocation(), diag::ext_anonymous_union);
4519   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4520     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4521   else if (!Record->isUnion() && !getLangOpts().C11)
4522     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4523 
4524   // C and C++ require different kinds of checks for anonymous
4525   // structs/unions.
4526   bool Invalid = false;
4527   if (getLangOpts().CPlusPlus) {
4528     const char *PrevSpec = nullptr;
4529     unsigned DiagID;
4530     if (Record->isUnion()) {
4531       // C++ [class.union]p6:
4532       //   Anonymous unions declared in a named namespace or in the
4533       //   global namespace shall be declared static.
4534       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4535           (isa<TranslationUnitDecl>(Owner) ||
4536            (isa<NamespaceDecl>(Owner) &&
4537             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4538         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4539           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4540 
4541         // Recover by adding 'static'.
4542         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4543                                PrevSpec, DiagID, Policy);
4544       }
4545       // C++ [class.union]p6:
4546       //   A storage class is not allowed in a declaration of an
4547       //   anonymous union in a class scope.
4548       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4549                isa<RecordDecl>(Owner)) {
4550         Diag(DS.getStorageClassSpecLoc(),
4551              diag::err_anonymous_union_with_storage_spec)
4552           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4553 
4554         // Recover by removing the storage specifier.
4555         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4556                                SourceLocation(),
4557                                PrevSpec, DiagID, Context.getPrintingPolicy());
4558       }
4559     }
4560 
4561     // Ignore const/volatile/restrict qualifiers.
4562     if (DS.getTypeQualifiers()) {
4563       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4564         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4565           << Record->isUnion() << "const"
4566           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4567       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4568         Diag(DS.getVolatileSpecLoc(),
4569              diag::ext_anonymous_struct_union_qualified)
4570           << Record->isUnion() << "volatile"
4571           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4572       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4573         Diag(DS.getRestrictSpecLoc(),
4574              diag::ext_anonymous_struct_union_qualified)
4575           << Record->isUnion() << "restrict"
4576           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4577       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4578         Diag(DS.getAtomicSpecLoc(),
4579              diag::ext_anonymous_struct_union_qualified)
4580           << Record->isUnion() << "_Atomic"
4581           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4582       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4583         Diag(DS.getUnalignedSpecLoc(),
4584              diag::ext_anonymous_struct_union_qualified)
4585           << Record->isUnion() << "__unaligned"
4586           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4587 
4588       DS.ClearTypeQualifiers();
4589     }
4590 
4591     // C++ [class.union]p2:
4592     //   The member-specification of an anonymous union shall only
4593     //   define non-static data members. [Note: nested types and
4594     //   functions cannot be declared within an anonymous union. ]
4595     for (auto *Mem : Record->decls()) {
4596       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4597         // C++ [class.union]p3:
4598         //   An anonymous union shall not have private or protected
4599         //   members (clause 11).
4600         assert(FD->getAccess() != AS_none);
4601         if (FD->getAccess() != AS_public) {
4602           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4603             << Record->isUnion() << (FD->getAccess() == AS_protected);
4604           Invalid = true;
4605         }
4606 
4607         // C++ [class.union]p1
4608         //   An object of a class with a non-trivial constructor, a non-trivial
4609         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4610         //   assignment operator cannot be a member of a union, nor can an
4611         //   array of such objects.
4612         if (CheckNontrivialField(FD))
4613           Invalid = true;
4614       } else if (Mem->isImplicit()) {
4615         // Any implicit members are fine.
4616       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4617         // This is a type that showed up in an
4618         // elaborated-type-specifier inside the anonymous struct or
4619         // union, but which actually declares a type outside of the
4620         // anonymous struct or union. It's okay.
4621       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4622         if (!MemRecord->isAnonymousStructOrUnion() &&
4623             MemRecord->getDeclName()) {
4624           // Visual C++ allows type definition in anonymous struct or union.
4625           if (getLangOpts().MicrosoftExt)
4626             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4627               << Record->isUnion();
4628           else {
4629             // This is a nested type declaration.
4630             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4631               << Record->isUnion();
4632             Invalid = true;
4633           }
4634         } else {
4635           // This is an anonymous type definition within another anonymous type.
4636           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4637           // not part of standard C++.
4638           Diag(MemRecord->getLocation(),
4639                diag::ext_anonymous_record_with_anonymous_type)
4640             << Record->isUnion();
4641         }
4642       } else if (isa<AccessSpecDecl>(Mem)) {
4643         // Any access specifier is fine.
4644       } else if (isa<StaticAssertDecl>(Mem)) {
4645         // In C++1z, static_assert declarations are also fine.
4646       } else {
4647         // We have something that isn't a non-static data
4648         // member. Complain about it.
4649         unsigned DK = diag::err_anonymous_record_bad_member;
4650         if (isa<TypeDecl>(Mem))
4651           DK = diag::err_anonymous_record_with_type;
4652         else if (isa<FunctionDecl>(Mem))
4653           DK = diag::err_anonymous_record_with_function;
4654         else if (isa<VarDecl>(Mem))
4655           DK = diag::err_anonymous_record_with_static;
4656 
4657         // Visual C++ allows type definition in anonymous struct or union.
4658         if (getLangOpts().MicrosoftExt &&
4659             DK == diag::err_anonymous_record_with_type)
4660           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4661             << Record->isUnion();
4662         else {
4663           Diag(Mem->getLocation(), DK) << Record->isUnion();
4664           Invalid = true;
4665         }
4666       }
4667     }
4668 
4669     // C++11 [class.union]p8 (DR1460):
4670     //   At most one variant member of a union may have a
4671     //   brace-or-equal-initializer.
4672     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4673         Owner->isRecord())
4674       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4675                                 cast<CXXRecordDecl>(Record));
4676   }
4677 
4678   if (!Record->isUnion() && !Owner->isRecord()) {
4679     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4680       << getLangOpts().CPlusPlus;
4681     Invalid = true;
4682   }
4683 
4684   // Mock up a declarator.
4685   Declarator Dc(DS, Declarator::MemberContext);
4686   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4687   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4688 
4689   // Create a declaration for this anonymous struct/union.
4690   NamedDecl *Anon = nullptr;
4691   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4692     Anon = FieldDecl::Create(Context, OwningClass,
4693                              DS.getLocStart(),
4694                              Record->getLocation(),
4695                              /*IdentifierInfo=*/nullptr,
4696                              Context.getTypeDeclType(Record),
4697                              TInfo,
4698                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4699                              /*InitStyle=*/ICIS_NoInit);
4700     Anon->setAccess(AS);
4701     if (getLangOpts().CPlusPlus)
4702       FieldCollector->Add(cast<FieldDecl>(Anon));
4703   } else {
4704     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4705     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4706     if (SCSpec == DeclSpec::SCS_mutable) {
4707       // mutable can only appear on non-static class members, so it's always
4708       // an error here
4709       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4710       Invalid = true;
4711       SC = SC_None;
4712     }
4713 
4714     Anon = VarDecl::Create(Context, Owner,
4715                            DS.getLocStart(),
4716                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4717                            Context.getTypeDeclType(Record),
4718                            TInfo, SC);
4719 
4720     // Default-initialize the implicit variable. This initialization will be
4721     // trivial in almost all cases, except if a union member has an in-class
4722     // initializer:
4723     //   union { int n = 0; };
4724     ActOnUninitializedDecl(Anon);
4725   }
4726   Anon->setImplicit();
4727 
4728   // Mark this as an anonymous struct/union type.
4729   Record->setAnonymousStructOrUnion(true);
4730 
4731   // Add the anonymous struct/union object to the current
4732   // context. We'll be referencing this object when we refer to one of
4733   // its members.
4734   Owner->addDecl(Anon);
4735 
4736   // Inject the members of the anonymous struct/union into the owning
4737   // context and into the identifier resolver chain for name lookup
4738   // purposes.
4739   SmallVector<NamedDecl*, 2> Chain;
4740   Chain.push_back(Anon);
4741 
4742   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4743     Invalid = true;
4744 
4745   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4746     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4747       Decl *ManglingContextDecl;
4748       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4749               NewVD->getDeclContext(), ManglingContextDecl)) {
4750         Context.setManglingNumber(
4751             NewVD, MCtx->getManglingNumber(
4752                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4753         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4754       }
4755     }
4756   }
4757 
4758   if (Invalid)
4759     Anon->setInvalidDecl();
4760 
4761   return Anon;
4762 }
4763 
4764 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4765 /// Microsoft C anonymous structure.
4766 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4767 /// Example:
4768 ///
4769 /// struct A { int a; };
4770 /// struct B { struct A; int b; };
4771 ///
4772 /// void foo() {
4773 ///   B var;
4774 ///   var.a = 3;
4775 /// }
4776 ///
4777 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4778                                            RecordDecl *Record) {
4779   assert(Record && "expected a record!");
4780 
4781   // Mock up a declarator.
4782   Declarator Dc(DS, Declarator::TypeNameContext);
4783   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4784   assert(TInfo && "couldn't build declarator info for anonymous struct");
4785 
4786   auto *ParentDecl = cast<RecordDecl>(CurContext);
4787   QualType RecTy = Context.getTypeDeclType(Record);
4788 
4789   // Create a declaration for this anonymous struct.
4790   NamedDecl *Anon = FieldDecl::Create(Context,
4791                              ParentDecl,
4792                              DS.getLocStart(),
4793                              DS.getLocStart(),
4794                              /*IdentifierInfo=*/nullptr,
4795                              RecTy,
4796                              TInfo,
4797                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4798                              /*InitStyle=*/ICIS_NoInit);
4799   Anon->setImplicit();
4800 
4801   // Add the anonymous struct object to the current context.
4802   CurContext->addDecl(Anon);
4803 
4804   // Inject the members of the anonymous struct into the current
4805   // context and into the identifier resolver chain for name lookup
4806   // purposes.
4807   SmallVector<NamedDecl*, 2> Chain;
4808   Chain.push_back(Anon);
4809 
4810   RecordDecl *RecordDef = Record->getDefinition();
4811   if (RequireCompleteType(Anon->getLocation(), RecTy,
4812                           diag::err_field_incomplete) ||
4813       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4814                                           AS_none, Chain)) {
4815     Anon->setInvalidDecl();
4816     ParentDecl->setInvalidDecl();
4817   }
4818 
4819   return Anon;
4820 }
4821 
4822 /// GetNameForDeclarator - Determine the full declaration name for the
4823 /// given Declarator.
4824 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4825   return GetNameFromUnqualifiedId(D.getName());
4826 }
4827 
4828 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4829 DeclarationNameInfo
4830 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4831   DeclarationNameInfo NameInfo;
4832   NameInfo.setLoc(Name.StartLocation);
4833 
4834   switch (Name.getKind()) {
4835 
4836   case UnqualifiedId::IK_ImplicitSelfParam:
4837   case UnqualifiedId::IK_Identifier:
4838     NameInfo.setName(Name.Identifier);
4839     NameInfo.setLoc(Name.StartLocation);
4840     return NameInfo;
4841 
4842   case UnqualifiedId::IK_DeductionGuideName: {
4843     // C++ [temp.deduct.guide]p3:
4844     //   The simple-template-id shall name a class template specialization.
4845     //   The template-name shall be the same identifier as the template-name
4846     //   of the simple-template-id.
4847     // These together intend to imply that the template-name shall name a
4848     // class template.
4849     // FIXME: template<typename T> struct X {};
4850     //        template<typename T> using Y = X<T>;
4851     //        Y(int) -> Y<int>;
4852     //   satisfies these rules but does not name a class template.
4853     TemplateName TN = Name.TemplateName.get().get();
4854     auto *Template = TN.getAsTemplateDecl();
4855     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4856       Diag(Name.StartLocation,
4857            diag::err_deduction_guide_name_not_class_template)
4858         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4859       if (Template)
4860         Diag(Template->getLocation(), diag::note_template_decl_here);
4861       return DeclarationNameInfo();
4862     }
4863 
4864     NameInfo.setName(
4865         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4866     NameInfo.setLoc(Name.StartLocation);
4867     return NameInfo;
4868   }
4869 
4870   case UnqualifiedId::IK_OperatorFunctionId:
4871     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4872                                            Name.OperatorFunctionId.Operator));
4873     NameInfo.setLoc(Name.StartLocation);
4874     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4875       = Name.OperatorFunctionId.SymbolLocations[0];
4876     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4877       = Name.EndLocation.getRawEncoding();
4878     return NameInfo;
4879 
4880   case UnqualifiedId::IK_LiteralOperatorId:
4881     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4882                                                            Name.Identifier));
4883     NameInfo.setLoc(Name.StartLocation);
4884     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4885     return NameInfo;
4886 
4887   case UnqualifiedId::IK_ConversionFunctionId: {
4888     TypeSourceInfo *TInfo;
4889     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4890     if (Ty.isNull())
4891       return DeclarationNameInfo();
4892     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4893                                                Context.getCanonicalType(Ty)));
4894     NameInfo.setLoc(Name.StartLocation);
4895     NameInfo.setNamedTypeInfo(TInfo);
4896     return NameInfo;
4897   }
4898 
4899   case UnqualifiedId::IK_ConstructorName: {
4900     TypeSourceInfo *TInfo;
4901     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4902     if (Ty.isNull())
4903       return DeclarationNameInfo();
4904     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4905                                               Context.getCanonicalType(Ty)));
4906     NameInfo.setLoc(Name.StartLocation);
4907     NameInfo.setNamedTypeInfo(TInfo);
4908     return NameInfo;
4909   }
4910 
4911   case UnqualifiedId::IK_ConstructorTemplateId: {
4912     // In well-formed code, we can only have a constructor
4913     // template-id that refers to the current context, so go there
4914     // to find the actual type being constructed.
4915     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4916     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4917       return DeclarationNameInfo();
4918 
4919     // Determine the type of the class being constructed.
4920     QualType CurClassType = Context.getTypeDeclType(CurClass);
4921 
4922     // FIXME: Check two things: that the template-id names the same type as
4923     // CurClassType, and that the template-id does not occur when the name
4924     // was qualified.
4925 
4926     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4927                                     Context.getCanonicalType(CurClassType)));
4928     NameInfo.setLoc(Name.StartLocation);
4929     // FIXME: should we retrieve TypeSourceInfo?
4930     NameInfo.setNamedTypeInfo(nullptr);
4931     return NameInfo;
4932   }
4933 
4934   case UnqualifiedId::IK_DestructorName: {
4935     TypeSourceInfo *TInfo;
4936     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4937     if (Ty.isNull())
4938       return DeclarationNameInfo();
4939     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4940                                               Context.getCanonicalType(Ty)));
4941     NameInfo.setLoc(Name.StartLocation);
4942     NameInfo.setNamedTypeInfo(TInfo);
4943     return NameInfo;
4944   }
4945 
4946   case UnqualifiedId::IK_TemplateId: {
4947     TemplateName TName = Name.TemplateId->Template.get();
4948     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4949     return Context.getNameForTemplate(TName, TNameLoc);
4950   }
4951 
4952   } // switch (Name.getKind())
4953 
4954   llvm_unreachable("Unknown name kind");
4955 }
4956 
4957 static QualType getCoreType(QualType Ty) {
4958   do {
4959     if (Ty->isPointerType() || Ty->isReferenceType())
4960       Ty = Ty->getPointeeType();
4961     else if (Ty->isArrayType())
4962       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4963     else
4964       return Ty.withoutLocalFastQualifiers();
4965   } while (true);
4966 }
4967 
4968 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4969 /// and Definition have "nearly" matching parameters. This heuristic is
4970 /// used to improve diagnostics in the case where an out-of-line function
4971 /// definition doesn't match any declaration within the class or namespace.
4972 /// Also sets Params to the list of indices to the parameters that differ
4973 /// between the declaration and the definition. If hasSimilarParameters
4974 /// returns true and Params is empty, then all of the parameters match.
4975 static bool hasSimilarParameters(ASTContext &Context,
4976                                      FunctionDecl *Declaration,
4977                                      FunctionDecl *Definition,
4978                                      SmallVectorImpl<unsigned> &Params) {
4979   Params.clear();
4980   if (Declaration->param_size() != Definition->param_size())
4981     return false;
4982   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4983     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4984     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4985 
4986     // The parameter types are identical
4987     if (Context.hasSameType(DefParamTy, DeclParamTy))
4988       continue;
4989 
4990     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4991     QualType DefParamBaseTy = getCoreType(DefParamTy);
4992     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4993     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4994 
4995     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4996         (DeclTyName && DeclTyName == DefTyName))
4997       Params.push_back(Idx);
4998     else  // The two parameters aren't even close
4999       return false;
5000   }
5001 
5002   return true;
5003 }
5004 
5005 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5006 /// declarator needs to be rebuilt in the current instantiation.
5007 /// Any bits of declarator which appear before the name are valid for
5008 /// consideration here.  That's specifically the type in the decl spec
5009 /// and the base type in any member-pointer chunks.
5010 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5011                                                     DeclarationName Name) {
5012   // The types we specifically need to rebuild are:
5013   //   - typenames, typeofs, and decltypes
5014   //   - types which will become injected class names
5015   // Of course, we also need to rebuild any type referencing such a
5016   // type.  It's safest to just say "dependent", but we call out a
5017   // few cases here.
5018 
5019   DeclSpec &DS = D.getMutableDeclSpec();
5020   switch (DS.getTypeSpecType()) {
5021   case DeclSpec::TST_typename:
5022   case DeclSpec::TST_typeofType:
5023   case DeclSpec::TST_underlyingType:
5024   case DeclSpec::TST_atomic: {
5025     // Grab the type from the parser.
5026     TypeSourceInfo *TSI = nullptr;
5027     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5028     if (T.isNull() || !T->isDependentType()) break;
5029 
5030     // Make sure there's a type source info.  This isn't really much
5031     // of a waste; most dependent types should have type source info
5032     // attached already.
5033     if (!TSI)
5034       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5035 
5036     // Rebuild the type in the current instantiation.
5037     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5038     if (!TSI) return true;
5039 
5040     // Store the new type back in the decl spec.
5041     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5042     DS.UpdateTypeRep(LocType);
5043     break;
5044   }
5045 
5046   case DeclSpec::TST_decltype:
5047   case DeclSpec::TST_typeofExpr: {
5048     Expr *E = DS.getRepAsExpr();
5049     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5050     if (Result.isInvalid()) return true;
5051     DS.UpdateExprRep(Result.get());
5052     break;
5053   }
5054 
5055   default:
5056     // Nothing to do for these decl specs.
5057     break;
5058   }
5059 
5060   // It doesn't matter what order we do this in.
5061   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5062     DeclaratorChunk &Chunk = D.getTypeObject(I);
5063 
5064     // The only type information in the declarator which can come
5065     // before the declaration name is the base type of a member
5066     // pointer.
5067     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5068       continue;
5069 
5070     // Rebuild the scope specifier in-place.
5071     CXXScopeSpec &SS = Chunk.Mem.Scope();
5072     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5073       return true;
5074   }
5075 
5076   return false;
5077 }
5078 
5079 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5080   D.setFunctionDefinitionKind(FDK_Declaration);
5081   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5082 
5083   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5084       Dcl && Dcl->getDeclContext()->isFileContext())
5085     Dcl->setTopLevelDeclInObjCContainer();
5086 
5087   if (getLangOpts().OpenCL)
5088     setCurrentOpenCLExtensionForDecl(Dcl);
5089 
5090   return Dcl;
5091 }
5092 
5093 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5094 ///   If T is the name of a class, then each of the following shall have a
5095 ///   name different from T:
5096 ///     - every static data member of class T;
5097 ///     - every member function of class T
5098 ///     - every member of class T that is itself a type;
5099 /// \returns true if the declaration name violates these rules.
5100 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5101                                    DeclarationNameInfo NameInfo) {
5102   DeclarationName Name = NameInfo.getName();
5103 
5104   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5105   while (Record && Record->isAnonymousStructOrUnion())
5106     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5107   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5108     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5109     return true;
5110   }
5111 
5112   return false;
5113 }
5114 
5115 /// \brief Diagnose a declaration whose declarator-id has the given
5116 /// nested-name-specifier.
5117 ///
5118 /// \param SS The nested-name-specifier of the declarator-id.
5119 ///
5120 /// \param DC The declaration context to which the nested-name-specifier
5121 /// resolves.
5122 ///
5123 /// \param Name The name of the entity being declared.
5124 ///
5125 /// \param Loc The location of the name of the entity being declared.
5126 ///
5127 /// \returns true if we cannot safely recover from this error, false otherwise.
5128 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5129                                         DeclarationName Name,
5130                                         SourceLocation Loc) {
5131   DeclContext *Cur = CurContext;
5132   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5133     Cur = Cur->getParent();
5134 
5135   // If the user provided a superfluous scope specifier that refers back to the
5136   // class in which the entity is already declared, diagnose and ignore it.
5137   //
5138   // class X {
5139   //   void X::f();
5140   // };
5141   //
5142   // Note, it was once ill-formed to give redundant qualification in all
5143   // contexts, but that rule was removed by DR482.
5144   if (Cur->Equals(DC)) {
5145     if (Cur->isRecord()) {
5146       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5147                                       : diag::err_member_extra_qualification)
5148         << Name << FixItHint::CreateRemoval(SS.getRange());
5149       SS.clear();
5150     } else {
5151       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5152     }
5153     return false;
5154   }
5155 
5156   // Check whether the qualifying scope encloses the scope of the original
5157   // declaration.
5158   if (!Cur->Encloses(DC)) {
5159     if (Cur->isRecord())
5160       Diag(Loc, diag::err_member_qualification)
5161         << Name << SS.getRange();
5162     else if (isa<TranslationUnitDecl>(DC))
5163       Diag(Loc, diag::err_invalid_declarator_global_scope)
5164         << Name << SS.getRange();
5165     else if (isa<FunctionDecl>(Cur))
5166       Diag(Loc, diag::err_invalid_declarator_in_function)
5167         << Name << SS.getRange();
5168     else if (isa<BlockDecl>(Cur))
5169       Diag(Loc, diag::err_invalid_declarator_in_block)
5170         << Name << SS.getRange();
5171     else
5172       Diag(Loc, diag::err_invalid_declarator_scope)
5173       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5174 
5175     return true;
5176   }
5177 
5178   if (Cur->isRecord()) {
5179     // Cannot qualify members within a class.
5180     Diag(Loc, diag::err_member_qualification)
5181       << Name << SS.getRange();
5182     SS.clear();
5183 
5184     // C++ constructors and destructors with incorrect scopes can break
5185     // our AST invariants by having the wrong underlying types. If
5186     // that's the case, then drop this declaration entirely.
5187     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5188          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5189         !Context.hasSameType(Name.getCXXNameType(),
5190                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5191       return true;
5192 
5193     return false;
5194   }
5195 
5196   // C++11 [dcl.meaning]p1:
5197   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5198   //   not begin with a decltype-specifer"
5199   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5200   while (SpecLoc.getPrefix())
5201     SpecLoc = SpecLoc.getPrefix();
5202   if (dyn_cast_or_null<DecltypeType>(
5203         SpecLoc.getNestedNameSpecifier()->getAsType()))
5204     Diag(Loc, diag::err_decltype_in_declarator)
5205       << SpecLoc.getTypeLoc().getSourceRange();
5206 
5207   return false;
5208 }
5209 
5210 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5211                                   MultiTemplateParamsArg TemplateParamLists) {
5212   // TODO: consider using NameInfo for diagnostic.
5213   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5214   DeclarationName Name = NameInfo.getName();
5215 
5216   // All of these full declarators require an identifier.  If it doesn't have
5217   // one, the ParsedFreeStandingDeclSpec action should be used.
5218   if (D.isDecompositionDeclarator()) {
5219     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5220   } else if (!Name) {
5221     if (!D.isInvalidType())  // Reject this if we think it is valid.
5222       Diag(D.getDeclSpec().getLocStart(),
5223            diag::err_declarator_need_ident)
5224         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5225     return nullptr;
5226   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5227     return nullptr;
5228 
5229   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5230   // we find one that is.
5231   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5232          (S->getFlags() & Scope::TemplateParamScope) != 0)
5233     S = S->getParent();
5234 
5235   DeclContext *DC = CurContext;
5236   if (D.getCXXScopeSpec().isInvalid())
5237     D.setInvalidType();
5238   else if (D.getCXXScopeSpec().isSet()) {
5239     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5240                                         UPPC_DeclarationQualifier))
5241       return nullptr;
5242 
5243     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5244     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5245     if (!DC || isa<EnumDecl>(DC)) {
5246       // If we could not compute the declaration context, it's because the
5247       // declaration context is dependent but does not refer to a class,
5248       // class template, or class template partial specialization. Complain
5249       // and return early, to avoid the coming semantic disaster.
5250       Diag(D.getIdentifierLoc(),
5251            diag::err_template_qualified_declarator_no_match)
5252         << D.getCXXScopeSpec().getScopeRep()
5253         << D.getCXXScopeSpec().getRange();
5254       return nullptr;
5255     }
5256     bool IsDependentContext = DC->isDependentContext();
5257 
5258     if (!IsDependentContext &&
5259         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5260       return nullptr;
5261 
5262     // If a class is incomplete, do not parse entities inside it.
5263     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5264       Diag(D.getIdentifierLoc(),
5265            diag::err_member_def_undefined_record)
5266         << Name << DC << D.getCXXScopeSpec().getRange();
5267       return nullptr;
5268     }
5269     if (!D.getDeclSpec().isFriendSpecified()) {
5270       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5271                                       Name, D.getIdentifierLoc())) {
5272         if (DC->isRecord())
5273           return nullptr;
5274 
5275         D.setInvalidType();
5276       }
5277     }
5278 
5279     // Check whether we need to rebuild the type of the given
5280     // declaration in the current instantiation.
5281     if (EnteringContext && IsDependentContext &&
5282         TemplateParamLists.size() != 0) {
5283       ContextRAII SavedContext(*this, DC);
5284       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5285         D.setInvalidType();
5286     }
5287   }
5288 
5289   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5290   QualType R = TInfo->getType();
5291 
5292   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5293                                       UPPC_DeclarationType))
5294     D.setInvalidType();
5295 
5296   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5297                         ForRedeclaration);
5298 
5299   // See if this is a redefinition of a variable in the same scope.
5300   if (!D.getCXXScopeSpec().isSet()) {
5301     bool IsLinkageLookup = false;
5302     bool CreateBuiltins = false;
5303 
5304     // If the declaration we're planning to build will be a function
5305     // or object with linkage, then look for another declaration with
5306     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5307     //
5308     // If the declaration we're planning to build will be declared with
5309     // external linkage in the translation unit, create any builtin with
5310     // the same name.
5311     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5312       /* Do nothing*/;
5313     else if (CurContext->isFunctionOrMethod() &&
5314              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5315               R->isFunctionType())) {
5316       IsLinkageLookup = true;
5317       CreateBuiltins =
5318           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5319     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5320                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5321       CreateBuiltins = true;
5322 
5323     if (IsLinkageLookup)
5324       Previous.clear(LookupRedeclarationWithLinkage);
5325 
5326     LookupName(Previous, S, CreateBuiltins);
5327   } else { // Something like "int foo::x;"
5328     LookupQualifiedName(Previous, DC);
5329 
5330     // C++ [dcl.meaning]p1:
5331     //   When the declarator-id is qualified, the declaration shall refer to a
5332     //  previously declared member of the class or namespace to which the
5333     //  qualifier refers (or, in the case of a namespace, of an element of the
5334     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5335     //  thereof; [...]
5336     //
5337     // Note that we already checked the context above, and that we do not have
5338     // enough information to make sure that Previous contains the declaration
5339     // we want to match. For example, given:
5340     //
5341     //   class X {
5342     //     void f();
5343     //     void f(float);
5344     //   };
5345     //
5346     //   void X::f(int) { } // ill-formed
5347     //
5348     // In this case, Previous will point to the overload set
5349     // containing the two f's declared in X, but neither of them
5350     // matches.
5351 
5352     // C++ [dcl.meaning]p1:
5353     //   [...] the member shall not merely have been introduced by a
5354     //   using-declaration in the scope of the class or namespace nominated by
5355     //   the nested-name-specifier of the declarator-id.
5356     RemoveUsingDecls(Previous);
5357   }
5358 
5359   if (Previous.isSingleResult() &&
5360       Previous.getFoundDecl()->isTemplateParameter()) {
5361     // Maybe we will complain about the shadowed template parameter.
5362     if (!D.isInvalidType())
5363       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5364                                       Previous.getFoundDecl());
5365 
5366     // Just pretend that we didn't see the previous declaration.
5367     Previous.clear();
5368   }
5369 
5370   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5371     // Forget that the previous declaration is the injected-class-name.
5372     Previous.clear();
5373 
5374   // In C++, the previous declaration we find might be a tag type
5375   // (class or enum). In this case, the new declaration will hide the
5376   // tag type. Note that this applies to functions, function templates, and
5377   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5378   if (Previous.isSingleTagDecl() &&
5379       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5380       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5381     Previous.clear();
5382 
5383   // Check that there are no default arguments other than in the parameters
5384   // of a function declaration (C++ only).
5385   if (getLangOpts().CPlusPlus)
5386     CheckExtraCXXDefaultArguments(D);
5387 
5388   if (D.getDeclSpec().isConceptSpecified()) {
5389     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5390     // applied only to the definition of a function template or variable
5391     // template, declared in namespace scope
5392     if (!TemplateParamLists.size()) {
5393       Diag(D.getDeclSpec().getConceptSpecLoc(),
5394            diag:: err_concept_wrong_decl_kind);
5395       return nullptr;
5396     }
5397 
5398     if (!DC->getRedeclContext()->isFileContext()) {
5399       Diag(D.getIdentifierLoc(),
5400            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5401       return nullptr;
5402     }
5403   }
5404 
5405   NamedDecl *New;
5406 
5407   bool AddToScope = true;
5408   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5409     if (TemplateParamLists.size()) {
5410       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5411       return nullptr;
5412     }
5413 
5414     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5415   } else if (R->isFunctionType()) {
5416     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5417                                   TemplateParamLists,
5418                                   AddToScope);
5419   } else {
5420     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5421                                   AddToScope);
5422   }
5423 
5424   if (!New)
5425     return nullptr;
5426 
5427   // If this has an identifier and is not a function template specialization,
5428   // add it to the scope stack.
5429   if (New->getDeclName() && AddToScope) {
5430     // Only make a locally-scoped extern declaration visible if it is the first
5431     // declaration of this entity. Qualified lookup for such an entity should
5432     // only find this declaration if there is no visible declaration of it.
5433     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5434     PushOnScopeChains(New, S, AddToContext);
5435     if (!AddToContext)
5436       CurContext->addHiddenDecl(New);
5437   }
5438 
5439   if (isInOpenMPDeclareTargetContext())
5440     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5441 
5442   return New;
5443 }
5444 
5445 /// Helper method to turn variable array types into constant array
5446 /// types in certain situations which would otherwise be errors (for
5447 /// GCC compatibility).
5448 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5449                                                     ASTContext &Context,
5450                                                     bool &SizeIsNegative,
5451                                                     llvm::APSInt &Oversized) {
5452   // This method tries to turn a variable array into a constant
5453   // array even when the size isn't an ICE.  This is necessary
5454   // for compatibility with code that depends on gcc's buggy
5455   // constant expression folding, like struct {char x[(int)(char*)2];}
5456   SizeIsNegative = false;
5457   Oversized = 0;
5458 
5459   if (T->isDependentType())
5460     return QualType();
5461 
5462   QualifierCollector Qs;
5463   const Type *Ty = Qs.strip(T);
5464 
5465   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5466     QualType Pointee = PTy->getPointeeType();
5467     QualType FixedType =
5468         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5469                                             Oversized);
5470     if (FixedType.isNull()) return FixedType;
5471     FixedType = Context.getPointerType(FixedType);
5472     return Qs.apply(Context, FixedType);
5473   }
5474   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5475     QualType Inner = PTy->getInnerType();
5476     QualType FixedType =
5477         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5478                                             Oversized);
5479     if (FixedType.isNull()) return FixedType;
5480     FixedType = Context.getParenType(FixedType);
5481     return Qs.apply(Context, FixedType);
5482   }
5483 
5484   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5485   if (!VLATy)
5486     return QualType();
5487   // FIXME: We should probably handle this case
5488   if (VLATy->getElementType()->isVariablyModifiedType())
5489     return QualType();
5490 
5491   llvm::APSInt Res;
5492   if (!VLATy->getSizeExpr() ||
5493       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5494     return QualType();
5495 
5496   // Check whether the array size is negative.
5497   if (Res.isSigned() && Res.isNegative()) {
5498     SizeIsNegative = true;
5499     return QualType();
5500   }
5501 
5502   // Check whether the array is too large to be addressed.
5503   unsigned ActiveSizeBits
5504     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5505                                               Res);
5506   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5507     Oversized = Res;
5508     return QualType();
5509   }
5510 
5511   return Context.getConstantArrayType(VLATy->getElementType(),
5512                                       Res, ArrayType::Normal, 0);
5513 }
5514 
5515 static void
5516 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5517   SrcTL = SrcTL.getUnqualifiedLoc();
5518   DstTL = DstTL.getUnqualifiedLoc();
5519   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5520     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5521     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5522                                       DstPTL.getPointeeLoc());
5523     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5524     return;
5525   }
5526   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5527     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5528     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5529                                       DstPTL.getInnerLoc());
5530     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5531     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5532     return;
5533   }
5534   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5535   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5536   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5537   TypeLoc DstElemTL = DstATL.getElementLoc();
5538   DstElemTL.initializeFullCopy(SrcElemTL);
5539   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5540   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5541   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5542 }
5543 
5544 /// Helper method to turn variable array types into constant array
5545 /// types in certain situations which would otherwise be errors (for
5546 /// GCC compatibility).
5547 static TypeSourceInfo*
5548 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5549                                               ASTContext &Context,
5550                                               bool &SizeIsNegative,
5551                                               llvm::APSInt &Oversized) {
5552   QualType FixedTy
5553     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5554                                           SizeIsNegative, Oversized);
5555   if (FixedTy.isNull())
5556     return nullptr;
5557   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5558   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5559                                     FixedTInfo->getTypeLoc());
5560   return FixedTInfo;
5561 }
5562 
5563 /// \brief Register the given locally-scoped extern "C" declaration so
5564 /// that it can be found later for redeclarations. We include any extern "C"
5565 /// declaration that is not visible in the translation unit here, not just
5566 /// function-scope declarations.
5567 void
5568 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5569   if (!getLangOpts().CPlusPlus &&
5570       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5571     // Don't need to track declarations in the TU in C.
5572     return;
5573 
5574   // Note that we have a locally-scoped external with this name.
5575   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5576 }
5577 
5578 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5579   // FIXME: We can have multiple results via __attribute__((overloadable)).
5580   auto Result = Context.getExternCContextDecl()->lookup(Name);
5581   return Result.empty() ? nullptr : *Result.begin();
5582 }
5583 
5584 /// \brief Diagnose function specifiers on a declaration of an identifier that
5585 /// does not identify a function.
5586 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5587   // FIXME: We should probably indicate the identifier in question to avoid
5588   // confusion for constructs like "virtual int a(), b;"
5589   if (DS.isVirtualSpecified())
5590     Diag(DS.getVirtualSpecLoc(),
5591          diag::err_virtual_non_function);
5592 
5593   if (DS.isExplicitSpecified())
5594     Diag(DS.getExplicitSpecLoc(),
5595          diag::err_explicit_non_function);
5596 
5597   if (DS.isNoreturnSpecified())
5598     Diag(DS.getNoreturnSpecLoc(),
5599          diag::err_noreturn_non_function);
5600 }
5601 
5602 NamedDecl*
5603 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5604                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5605   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5606   if (D.getCXXScopeSpec().isSet()) {
5607     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5608       << D.getCXXScopeSpec().getRange();
5609     D.setInvalidType();
5610     // Pretend we didn't see the scope specifier.
5611     DC = CurContext;
5612     Previous.clear();
5613   }
5614 
5615   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5616 
5617   if (D.getDeclSpec().isInlineSpecified())
5618     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5619         << getLangOpts().CPlusPlus1z;
5620   if (D.getDeclSpec().isConstexprSpecified())
5621     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5622       << 1;
5623   if (D.getDeclSpec().isConceptSpecified())
5624     Diag(D.getDeclSpec().getConceptSpecLoc(),
5625          diag::err_concept_wrong_decl_kind);
5626 
5627   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5628     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5629       Diag(D.getName().StartLocation,
5630            diag::err_deduction_guide_invalid_specifier)
5631           << "typedef";
5632     else
5633       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5634           << D.getName().getSourceRange();
5635     return nullptr;
5636   }
5637 
5638   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5639   if (!NewTD) return nullptr;
5640 
5641   // Handle attributes prior to checking for duplicates in MergeVarDecl
5642   ProcessDeclAttributes(S, NewTD, D);
5643 
5644   CheckTypedefForVariablyModifiedType(S, NewTD);
5645 
5646   bool Redeclaration = D.isRedeclaration();
5647   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5648   D.setRedeclaration(Redeclaration);
5649   return ND;
5650 }
5651 
5652 void
5653 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5654   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5655   // then it shall have block scope.
5656   // Note that variably modified types must be fixed before merging the decl so
5657   // that redeclarations will match.
5658   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5659   QualType T = TInfo->getType();
5660   if (T->isVariablyModifiedType()) {
5661     getCurFunction()->setHasBranchProtectedScope();
5662 
5663     if (S->getFnParent() == nullptr) {
5664       bool SizeIsNegative;
5665       llvm::APSInt Oversized;
5666       TypeSourceInfo *FixedTInfo =
5667         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5668                                                       SizeIsNegative,
5669                                                       Oversized);
5670       if (FixedTInfo) {
5671         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5672         NewTD->setTypeSourceInfo(FixedTInfo);
5673       } else {
5674         if (SizeIsNegative)
5675           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5676         else if (T->isVariableArrayType())
5677           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5678         else if (Oversized.getBoolValue())
5679           Diag(NewTD->getLocation(), diag::err_array_too_large)
5680             << Oversized.toString(10);
5681         else
5682           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5683         NewTD->setInvalidDecl();
5684       }
5685     }
5686   }
5687 }
5688 
5689 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5690 /// declares a typedef-name, either using the 'typedef' type specifier or via
5691 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5692 NamedDecl*
5693 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5694                            LookupResult &Previous, bool &Redeclaration) {
5695 
5696   // Find the shadowed declaration before filtering for scope.
5697   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5698 
5699   // Merge the decl with the existing one if appropriate. If the decl is
5700   // in an outer scope, it isn't the same thing.
5701   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5702                        /*AllowInlineNamespace*/false);
5703   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5704   if (!Previous.empty()) {
5705     Redeclaration = true;
5706     MergeTypedefNameDecl(S, NewTD, Previous);
5707   }
5708 
5709   if (ShadowedDecl && !Redeclaration)
5710     CheckShadow(NewTD, ShadowedDecl, Previous);
5711 
5712   // If this is the C FILE type, notify the AST context.
5713   if (IdentifierInfo *II = NewTD->getIdentifier())
5714     if (!NewTD->isInvalidDecl() &&
5715         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5716       if (II->isStr("FILE"))
5717         Context.setFILEDecl(NewTD);
5718       else if (II->isStr("jmp_buf"))
5719         Context.setjmp_bufDecl(NewTD);
5720       else if (II->isStr("sigjmp_buf"))
5721         Context.setsigjmp_bufDecl(NewTD);
5722       else if (II->isStr("ucontext_t"))
5723         Context.setucontext_tDecl(NewTD);
5724     }
5725 
5726   return NewTD;
5727 }
5728 
5729 /// \brief Determines whether the given declaration is an out-of-scope
5730 /// previous declaration.
5731 ///
5732 /// This routine should be invoked when name lookup has found a
5733 /// previous declaration (PrevDecl) that is not in the scope where a
5734 /// new declaration by the same name is being introduced. If the new
5735 /// declaration occurs in a local scope, previous declarations with
5736 /// linkage may still be considered previous declarations (C99
5737 /// 6.2.2p4-5, C++ [basic.link]p6).
5738 ///
5739 /// \param PrevDecl the previous declaration found by name
5740 /// lookup
5741 ///
5742 /// \param DC the context in which the new declaration is being
5743 /// declared.
5744 ///
5745 /// \returns true if PrevDecl is an out-of-scope previous declaration
5746 /// for a new delcaration with the same name.
5747 static bool
5748 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5749                                 ASTContext &Context) {
5750   if (!PrevDecl)
5751     return false;
5752 
5753   if (!PrevDecl->hasLinkage())
5754     return false;
5755 
5756   if (Context.getLangOpts().CPlusPlus) {
5757     // C++ [basic.link]p6:
5758     //   If there is a visible declaration of an entity with linkage
5759     //   having the same name and type, ignoring entities declared
5760     //   outside the innermost enclosing namespace scope, the block
5761     //   scope declaration declares that same entity and receives the
5762     //   linkage of the previous declaration.
5763     DeclContext *OuterContext = DC->getRedeclContext();
5764     if (!OuterContext->isFunctionOrMethod())
5765       // This rule only applies to block-scope declarations.
5766       return false;
5767 
5768     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5769     if (PrevOuterContext->isRecord())
5770       // We found a member function: ignore it.
5771       return false;
5772 
5773     // Find the innermost enclosing namespace for the new and
5774     // previous declarations.
5775     OuterContext = OuterContext->getEnclosingNamespaceContext();
5776     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5777 
5778     // The previous declaration is in a different namespace, so it
5779     // isn't the same function.
5780     if (!OuterContext->Equals(PrevOuterContext))
5781       return false;
5782   }
5783 
5784   return true;
5785 }
5786 
5787 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5788   CXXScopeSpec &SS = D.getCXXScopeSpec();
5789   if (!SS.isSet()) return;
5790   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5791 }
5792 
5793 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5794   QualType type = decl->getType();
5795   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5796   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5797     // Various kinds of declaration aren't allowed to be __autoreleasing.
5798     unsigned kind = -1U;
5799     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5800       if (var->hasAttr<BlocksAttr>())
5801         kind = 0; // __block
5802       else if (!var->hasLocalStorage())
5803         kind = 1; // global
5804     } else if (isa<ObjCIvarDecl>(decl)) {
5805       kind = 3; // ivar
5806     } else if (isa<FieldDecl>(decl)) {
5807       kind = 2; // field
5808     }
5809 
5810     if (kind != -1U) {
5811       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5812         << kind;
5813     }
5814   } else if (lifetime == Qualifiers::OCL_None) {
5815     // Try to infer lifetime.
5816     if (!type->isObjCLifetimeType())
5817       return false;
5818 
5819     lifetime = type->getObjCARCImplicitLifetime();
5820     type = Context.getLifetimeQualifiedType(type, lifetime);
5821     decl->setType(type);
5822   }
5823 
5824   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5825     // Thread-local variables cannot have lifetime.
5826     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5827         var->getTLSKind()) {
5828       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5829         << var->getType();
5830       return true;
5831     }
5832   }
5833 
5834   return false;
5835 }
5836 
5837 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5838   // Ensure that an auto decl is deduced otherwise the checks below might cache
5839   // the wrong linkage.
5840   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5841 
5842   // 'weak' only applies to declarations with external linkage.
5843   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5844     if (!ND.isExternallyVisible()) {
5845       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5846       ND.dropAttr<WeakAttr>();
5847     }
5848   }
5849   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5850     if (ND.isExternallyVisible()) {
5851       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5852       ND.dropAttr<WeakRefAttr>();
5853       ND.dropAttr<AliasAttr>();
5854     }
5855   }
5856 
5857   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5858     if (VD->hasInit()) {
5859       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5860         assert(VD->isThisDeclarationADefinition() &&
5861                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5862         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5863         VD->dropAttr<AliasAttr>();
5864       }
5865     }
5866   }
5867 
5868   // 'selectany' only applies to externally visible variable declarations.
5869   // It does not apply to functions.
5870   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5871     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5872       S.Diag(Attr->getLocation(),
5873              diag::err_attribute_selectany_non_extern_data);
5874       ND.dropAttr<SelectAnyAttr>();
5875     }
5876   }
5877 
5878   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5879     // dll attributes require external linkage. Static locals may have external
5880     // linkage but still cannot be explicitly imported or exported.
5881     auto *VD = dyn_cast<VarDecl>(&ND);
5882     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5883       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5884         << &ND << Attr;
5885       ND.setInvalidDecl();
5886     }
5887   }
5888 
5889   // Virtual functions cannot be marked as 'notail'.
5890   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5891     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5892       if (MD->isVirtual()) {
5893         S.Diag(ND.getLocation(),
5894                diag::err_invalid_attribute_on_virtual_function)
5895             << Attr;
5896         ND.dropAttr<NotTailCalledAttr>();
5897       }
5898 }
5899 
5900 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5901                                            NamedDecl *NewDecl,
5902                                            bool IsSpecialization,
5903                                            bool IsDefinition) {
5904   if (OldDecl->isInvalidDecl())
5905     return;
5906 
5907   bool IsTemplate = false;
5908   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5909     OldDecl = OldTD->getTemplatedDecl();
5910     IsTemplate = true;
5911     if (!IsSpecialization)
5912       IsDefinition = false;
5913   }
5914   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5915     NewDecl = NewTD->getTemplatedDecl();
5916     IsTemplate = true;
5917   }
5918 
5919   if (!OldDecl || !NewDecl)
5920     return;
5921 
5922   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5923   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5924   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5925   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5926 
5927   // dllimport and dllexport are inheritable attributes so we have to exclude
5928   // inherited attribute instances.
5929   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5930                     (NewExportAttr && !NewExportAttr->isInherited());
5931 
5932   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5933   // the only exception being explicit specializations.
5934   // Implicitly generated declarations are also excluded for now because there
5935   // is no other way to switch these to use dllimport or dllexport.
5936   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5937 
5938   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5939     // Allow with a warning for free functions and global variables.
5940     bool JustWarn = false;
5941     if (!OldDecl->isCXXClassMember()) {
5942       auto *VD = dyn_cast<VarDecl>(OldDecl);
5943       if (VD && !VD->getDescribedVarTemplate())
5944         JustWarn = true;
5945       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5946       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5947         JustWarn = true;
5948     }
5949 
5950     // We cannot change a declaration that's been used because IR has already
5951     // been emitted. Dllimported functions will still work though (modulo
5952     // address equality) as they can use the thunk.
5953     if (OldDecl->isUsed())
5954       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5955         JustWarn = false;
5956 
5957     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5958                                : diag::err_attribute_dll_redeclaration;
5959     S.Diag(NewDecl->getLocation(), DiagID)
5960         << NewDecl
5961         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5962     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5963     if (!JustWarn) {
5964       NewDecl->setInvalidDecl();
5965       return;
5966     }
5967   }
5968 
5969   // A redeclaration is not allowed to drop a dllimport attribute, the only
5970   // exceptions being inline function definitions (except for function
5971   // templates), local extern declarations, qualified friend declarations or
5972   // special MSVC extension: in the last case, the declaration is treated as if
5973   // it were marked dllexport.
5974   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5975   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5976   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5977     // Ignore static data because out-of-line definitions are diagnosed
5978     // separately.
5979     IsStaticDataMember = VD->isStaticDataMember();
5980     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5981                    VarDecl::DeclarationOnly;
5982   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5983     IsInline = FD->isInlined();
5984     IsQualifiedFriend = FD->getQualifier() &&
5985                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5986   }
5987 
5988   if (OldImportAttr && !HasNewAttr &&
5989       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5990       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5991     if (IsMicrosoft && IsDefinition) {
5992       S.Diag(NewDecl->getLocation(),
5993              diag::warn_redeclaration_without_import_attribute)
5994           << NewDecl;
5995       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5996       NewDecl->dropAttr<DLLImportAttr>();
5997       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5998           NewImportAttr->getRange(), S.Context,
5999           NewImportAttr->getSpellingListIndex()));
6000     } else {
6001       S.Diag(NewDecl->getLocation(),
6002              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6003           << NewDecl << OldImportAttr;
6004       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6005       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6006       OldDecl->dropAttr<DLLImportAttr>();
6007       NewDecl->dropAttr<DLLImportAttr>();
6008     }
6009   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6010     // In MinGW, seeing a function declared inline drops the dllimport attribute.
6011     OldDecl->dropAttr<DLLImportAttr>();
6012     NewDecl->dropAttr<DLLImportAttr>();
6013     S.Diag(NewDecl->getLocation(),
6014            diag::warn_dllimport_dropped_from_inline_function)
6015         << NewDecl << OldImportAttr;
6016   }
6017 }
6018 
6019 /// Given that we are within the definition of the given function,
6020 /// will that definition behave like C99's 'inline', where the
6021 /// definition is discarded except for optimization purposes?
6022 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6023   // Try to avoid calling GetGVALinkageForFunction.
6024 
6025   // All cases of this require the 'inline' keyword.
6026   if (!FD->isInlined()) return false;
6027 
6028   // This is only possible in C++ with the gnu_inline attribute.
6029   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6030     return false;
6031 
6032   // Okay, go ahead and call the relatively-more-expensive function.
6033   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6034 }
6035 
6036 /// Determine whether a variable is extern "C" prior to attaching
6037 /// an initializer. We can't just call isExternC() here, because that
6038 /// will also compute and cache whether the declaration is externally
6039 /// visible, which might change when we attach the initializer.
6040 ///
6041 /// This can only be used if the declaration is known to not be a
6042 /// redeclaration of an internal linkage declaration.
6043 ///
6044 /// For instance:
6045 ///
6046 ///   auto x = []{};
6047 ///
6048 /// Attaching the initializer here makes this declaration not externally
6049 /// visible, because its type has internal linkage.
6050 ///
6051 /// FIXME: This is a hack.
6052 template<typename T>
6053 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6054   if (S.getLangOpts().CPlusPlus) {
6055     // In C++, the overloadable attribute negates the effects of extern "C".
6056     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6057       return false;
6058 
6059     // So do CUDA's host/device attributes.
6060     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6061                                  D->template hasAttr<CUDAHostAttr>()))
6062       return false;
6063   }
6064   return D->isExternC();
6065 }
6066 
6067 static bool shouldConsiderLinkage(const VarDecl *VD) {
6068   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6069   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6070     return VD->hasExternalStorage();
6071   if (DC->isFileContext())
6072     return true;
6073   if (DC->isRecord())
6074     return false;
6075   llvm_unreachable("Unexpected context");
6076 }
6077 
6078 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6079   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6080   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6081       isa<OMPDeclareReductionDecl>(DC))
6082     return true;
6083   if (DC->isRecord())
6084     return false;
6085   llvm_unreachable("Unexpected context");
6086 }
6087 
6088 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6089                           AttributeList::Kind Kind) {
6090   for (const AttributeList *L = AttrList; L; L = L->getNext())
6091     if (L->getKind() == Kind)
6092       return true;
6093   return false;
6094 }
6095 
6096 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6097                           AttributeList::Kind Kind) {
6098   // Check decl attributes on the DeclSpec.
6099   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6100     return true;
6101 
6102   // Walk the declarator structure, checking decl attributes that were in a type
6103   // position to the decl itself.
6104   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6105     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6106       return true;
6107   }
6108 
6109   // Finally, check attributes on the decl itself.
6110   return hasParsedAttr(S, PD.getAttributes(), Kind);
6111 }
6112 
6113 /// Adjust the \c DeclContext for a function or variable that might be a
6114 /// function-local external declaration.
6115 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6116   if (!DC->isFunctionOrMethod())
6117     return false;
6118 
6119   // If this is a local extern function or variable declared within a function
6120   // template, don't add it into the enclosing namespace scope until it is
6121   // instantiated; it might have a dependent type right now.
6122   if (DC->isDependentContext())
6123     return true;
6124 
6125   // C++11 [basic.link]p7:
6126   //   When a block scope declaration of an entity with linkage is not found to
6127   //   refer to some other declaration, then that entity is a member of the
6128   //   innermost enclosing namespace.
6129   //
6130   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6131   // semantically-enclosing namespace, not a lexically-enclosing one.
6132   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6133     DC = DC->getParent();
6134   return true;
6135 }
6136 
6137 /// \brief Returns true if given declaration has external C language linkage.
6138 static bool isDeclExternC(const Decl *D) {
6139   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6140     return FD->isExternC();
6141   if (const auto *VD = dyn_cast<VarDecl>(D))
6142     return VD->isExternC();
6143 
6144   llvm_unreachable("Unknown type of decl!");
6145 }
6146 
6147 NamedDecl *Sema::ActOnVariableDeclarator(
6148     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6149     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6150     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6151   QualType R = TInfo->getType();
6152   DeclarationName Name = GetNameForDeclarator(D).getName();
6153 
6154   IdentifierInfo *II = Name.getAsIdentifierInfo();
6155 
6156   if (D.isDecompositionDeclarator()) {
6157     AddToScope = false;
6158     // Take the name of the first declarator as our name for diagnostic
6159     // purposes.
6160     auto &Decomp = D.getDecompositionDeclarator();
6161     if (!Decomp.bindings().empty()) {
6162       II = Decomp.bindings()[0].Name;
6163       Name = II;
6164     }
6165   } else if (!II) {
6166     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6167     return nullptr;
6168   }
6169 
6170   if (getLangOpts().OpenCL) {
6171     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6172     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6173     // argument.
6174     if (R->isImageType() || R->isPipeType()) {
6175       Diag(D.getIdentifierLoc(),
6176            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6177           << R;
6178       D.setInvalidType();
6179       return nullptr;
6180     }
6181 
6182     // OpenCL v1.2 s6.9.r:
6183     // The event type cannot be used to declare a program scope variable.
6184     // OpenCL v2.0 s6.9.q:
6185     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6186     if (NULL == S->getParent()) {
6187       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6188         Diag(D.getIdentifierLoc(),
6189              diag::err_invalid_type_for_program_scope_var) << R;
6190         D.setInvalidType();
6191         return nullptr;
6192       }
6193     }
6194 
6195     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6196     QualType NR = R;
6197     while (NR->isPointerType()) {
6198       if (NR->isFunctionPointerType()) {
6199         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6200         D.setInvalidType();
6201         break;
6202       }
6203       NR = NR->getPointeeType();
6204     }
6205 
6206     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6207       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6208       // half array type (unless the cl_khr_fp16 extension is enabled).
6209       if (Context.getBaseElementType(R)->isHalfType()) {
6210         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6211         D.setInvalidType();
6212       }
6213     }
6214 
6215     if (R->isSamplerT()) {
6216       // OpenCL v1.2 s6.9.b p4:
6217       // The sampler type cannot be used with the __local and __global address
6218       // space qualifiers.
6219       if (R.getAddressSpace() == LangAS::opencl_local ||
6220           R.getAddressSpace() == LangAS::opencl_global) {
6221         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6222       }
6223 
6224       // OpenCL v1.2 s6.12.14.1:
6225       // A global sampler must be declared with either the constant address
6226       // space qualifier or with the const qualifier.
6227       if (DC->isTranslationUnit() &&
6228           !(R.getAddressSpace() == LangAS::opencl_constant ||
6229           R.isConstQualified())) {
6230         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6231         D.setInvalidType();
6232       }
6233     }
6234 
6235     // OpenCL v1.2 s6.9.r:
6236     // The event type cannot be used with the __local, __constant and __global
6237     // address space qualifiers.
6238     if (R->isEventT()) {
6239       if (R.getAddressSpace()) {
6240         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6241         D.setInvalidType();
6242       }
6243     }
6244   }
6245 
6246   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6247   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6248 
6249   // dllimport globals without explicit storage class are treated as extern. We
6250   // have to change the storage class this early to get the right DeclContext.
6251   if (SC == SC_None && !DC->isRecord() &&
6252       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6253       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6254     SC = SC_Extern;
6255 
6256   DeclContext *OriginalDC = DC;
6257   bool IsLocalExternDecl = SC == SC_Extern &&
6258                            adjustContextForLocalExternDecl(DC);
6259 
6260   if (SCSpec == DeclSpec::SCS_mutable) {
6261     // mutable can only appear on non-static class members, so it's always
6262     // an error here
6263     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6264     D.setInvalidType();
6265     SC = SC_None;
6266   }
6267 
6268   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6269       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6270                               D.getDeclSpec().getStorageClassSpecLoc())) {
6271     // In C++11, the 'register' storage class specifier is deprecated.
6272     // Suppress the warning in system macros, it's used in macros in some
6273     // popular C system headers, such as in glibc's htonl() macro.
6274     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6275          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6276                                    : diag::warn_deprecated_register)
6277       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6278   }
6279 
6280   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6281 
6282   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6283     // C99 6.9p2: The storage-class specifiers auto and register shall not
6284     // appear in the declaration specifiers in an external declaration.
6285     // Global Register+Asm is a GNU extension we support.
6286     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6287       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6288       D.setInvalidType();
6289     }
6290   }
6291 
6292   bool IsMemberSpecialization = false;
6293   bool IsVariableTemplateSpecialization = false;
6294   bool IsPartialSpecialization = false;
6295   bool IsVariableTemplate = false;
6296   VarDecl *NewVD = nullptr;
6297   VarTemplateDecl *NewTemplate = nullptr;
6298   TemplateParameterList *TemplateParams = nullptr;
6299   if (!getLangOpts().CPlusPlus) {
6300     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6301                             D.getIdentifierLoc(), II,
6302                             R, TInfo, SC);
6303 
6304     if (R->getContainedDeducedType())
6305       ParsingInitForAutoVars.insert(NewVD);
6306 
6307     if (D.isInvalidType())
6308       NewVD->setInvalidDecl();
6309   } else {
6310     bool Invalid = false;
6311 
6312     if (DC->isRecord() && !CurContext->isRecord()) {
6313       // This is an out-of-line definition of a static data member.
6314       switch (SC) {
6315       case SC_None:
6316         break;
6317       case SC_Static:
6318         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6319              diag::err_static_out_of_line)
6320           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6321         break;
6322       case SC_Auto:
6323       case SC_Register:
6324       case SC_Extern:
6325         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6326         // to names of variables declared in a block or to function parameters.
6327         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6328         // of class members
6329 
6330         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6331              diag::err_storage_class_for_static_member)
6332           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6333         break;
6334       case SC_PrivateExtern:
6335         llvm_unreachable("C storage class in c++!");
6336       }
6337     }
6338 
6339     if (SC == SC_Static && CurContext->isRecord()) {
6340       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6341         if (RD->isLocalClass())
6342           Diag(D.getIdentifierLoc(),
6343                diag::err_static_data_member_not_allowed_in_local_class)
6344             << Name << RD->getDeclName();
6345 
6346         // C++98 [class.union]p1: If a union contains a static data member,
6347         // the program is ill-formed. C++11 drops this restriction.
6348         if (RD->isUnion())
6349           Diag(D.getIdentifierLoc(),
6350                getLangOpts().CPlusPlus11
6351                  ? diag::warn_cxx98_compat_static_data_member_in_union
6352                  : diag::ext_static_data_member_in_union) << Name;
6353         // We conservatively disallow static data members in anonymous structs.
6354         else if (!RD->getDeclName())
6355           Diag(D.getIdentifierLoc(),
6356                diag::err_static_data_member_not_allowed_in_anon_struct)
6357             << Name << RD->isUnion();
6358       }
6359     }
6360 
6361     // Match up the template parameter lists with the scope specifier, then
6362     // determine whether we have a template or a template specialization.
6363     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6364         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6365         D.getCXXScopeSpec(),
6366         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6367             ? D.getName().TemplateId
6368             : nullptr,
6369         TemplateParamLists,
6370         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6371 
6372     if (TemplateParams) {
6373       if (!TemplateParams->size() &&
6374           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6375         // There is an extraneous 'template<>' for this variable. Complain
6376         // about it, but allow the declaration of the variable.
6377         Diag(TemplateParams->getTemplateLoc(),
6378              diag::err_template_variable_noparams)
6379           << II
6380           << SourceRange(TemplateParams->getTemplateLoc(),
6381                          TemplateParams->getRAngleLoc());
6382         TemplateParams = nullptr;
6383       } else {
6384         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6385           // This is an explicit specialization or a partial specialization.
6386           // FIXME: Check that we can declare a specialization here.
6387           IsVariableTemplateSpecialization = true;
6388           IsPartialSpecialization = TemplateParams->size() > 0;
6389         } else { // if (TemplateParams->size() > 0)
6390           // This is a template declaration.
6391           IsVariableTemplate = true;
6392 
6393           // Check that we can declare a template here.
6394           if (CheckTemplateDeclScope(S, TemplateParams))
6395             return nullptr;
6396 
6397           // Only C++1y supports variable templates (N3651).
6398           Diag(D.getIdentifierLoc(),
6399                getLangOpts().CPlusPlus14
6400                    ? diag::warn_cxx11_compat_variable_template
6401                    : diag::ext_variable_template);
6402         }
6403       }
6404     } else {
6405       assert(
6406           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6407           "should have a 'template<>' for this decl");
6408     }
6409 
6410     if (IsVariableTemplateSpecialization) {
6411       SourceLocation TemplateKWLoc =
6412           TemplateParamLists.size() > 0
6413               ? TemplateParamLists[0]->getTemplateLoc()
6414               : SourceLocation();
6415       DeclResult Res = ActOnVarTemplateSpecialization(
6416           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6417           IsPartialSpecialization);
6418       if (Res.isInvalid())
6419         return nullptr;
6420       NewVD = cast<VarDecl>(Res.get());
6421       AddToScope = false;
6422     } else if (D.isDecompositionDeclarator()) {
6423       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6424                                         D.getIdentifierLoc(), R, TInfo, SC,
6425                                         Bindings);
6426     } else
6427       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6428                               D.getIdentifierLoc(), II, R, TInfo, SC);
6429 
6430     // If this is supposed to be a variable template, create it as such.
6431     if (IsVariableTemplate) {
6432       NewTemplate =
6433           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6434                                   TemplateParams, NewVD);
6435       NewVD->setDescribedVarTemplate(NewTemplate);
6436     }
6437 
6438     // If this decl has an auto type in need of deduction, make a note of the
6439     // Decl so we can diagnose uses of it in its own initializer.
6440     if (R->getContainedDeducedType())
6441       ParsingInitForAutoVars.insert(NewVD);
6442 
6443     if (D.isInvalidType() || Invalid) {
6444       NewVD->setInvalidDecl();
6445       if (NewTemplate)
6446         NewTemplate->setInvalidDecl();
6447     }
6448 
6449     SetNestedNameSpecifier(NewVD, D);
6450 
6451     // If we have any template parameter lists that don't directly belong to
6452     // the variable (matching the scope specifier), store them.
6453     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6454     if (TemplateParamLists.size() > VDTemplateParamLists)
6455       NewVD->setTemplateParameterListsInfo(
6456           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6457 
6458     if (D.getDeclSpec().isConstexprSpecified()) {
6459       NewVD->setConstexpr(true);
6460       // C++1z [dcl.spec.constexpr]p1:
6461       //   A static data member declared with the constexpr specifier is
6462       //   implicitly an inline variable.
6463       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6464         NewVD->setImplicitlyInline();
6465     }
6466 
6467     if (D.getDeclSpec().isConceptSpecified()) {
6468       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6469         VTD->setConcept();
6470 
6471       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6472       // be declared with the thread_local, inline, friend, or constexpr
6473       // specifiers, [...]
6474       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6475         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6476              diag::err_concept_decl_invalid_specifiers)
6477             << 0 << 0;
6478         NewVD->setInvalidDecl(true);
6479       }
6480 
6481       if (D.getDeclSpec().isConstexprSpecified()) {
6482         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6483              diag::err_concept_decl_invalid_specifiers)
6484             << 0 << 3;
6485         NewVD->setInvalidDecl(true);
6486       }
6487 
6488       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6489       // applied only to the definition of a function template or variable
6490       // template, declared in namespace scope.
6491       if (IsVariableTemplateSpecialization) {
6492         Diag(D.getDeclSpec().getConceptSpecLoc(),
6493              diag::err_concept_specified_specialization)
6494             << (IsPartialSpecialization ? 2 : 1);
6495       }
6496 
6497       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6498       // following restrictions:
6499       // - The declared type shall have the type bool.
6500       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6501           !NewVD->isInvalidDecl()) {
6502         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6503         NewVD->setInvalidDecl(true);
6504       }
6505     }
6506   }
6507 
6508   if (D.getDeclSpec().isInlineSpecified()) {
6509     if (!getLangOpts().CPlusPlus) {
6510       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6511           << 0;
6512     } else if (CurContext->isFunctionOrMethod()) {
6513       // 'inline' is not allowed on block scope variable declaration.
6514       Diag(D.getDeclSpec().getInlineSpecLoc(),
6515            diag::err_inline_declaration_block_scope) << Name
6516         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6517     } else {
6518       Diag(D.getDeclSpec().getInlineSpecLoc(),
6519            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6520                                      : diag::ext_inline_variable);
6521       NewVD->setInlineSpecified();
6522     }
6523   }
6524 
6525   // Set the lexical context. If the declarator has a C++ scope specifier, the
6526   // lexical context will be different from the semantic context.
6527   NewVD->setLexicalDeclContext(CurContext);
6528   if (NewTemplate)
6529     NewTemplate->setLexicalDeclContext(CurContext);
6530 
6531   if (IsLocalExternDecl) {
6532     if (D.isDecompositionDeclarator())
6533       for (auto *B : Bindings)
6534         B->setLocalExternDecl();
6535     else
6536       NewVD->setLocalExternDecl();
6537   }
6538 
6539   bool EmitTLSUnsupportedError = false;
6540   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6541     // C++11 [dcl.stc]p4:
6542     //   When thread_local is applied to a variable of block scope the
6543     //   storage-class-specifier static is implied if it does not appear
6544     //   explicitly.
6545     // Core issue: 'static' is not implied if the variable is declared
6546     //   'extern'.
6547     if (NewVD->hasLocalStorage() &&
6548         (SCSpec != DeclSpec::SCS_unspecified ||
6549          TSCS != DeclSpec::TSCS_thread_local ||
6550          !DC->isFunctionOrMethod()))
6551       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6552            diag::err_thread_non_global)
6553         << DeclSpec::getSpecifierName(TSCS);
6554     else if (!Context.getTargetInfo().isTLSSupported()) {
6555       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6556         // Postpone error emission until we've collected attributes required to
6557         // figure out whether it's a host or device variable and whether the
6558         // error should be ignored.
6559         EmitTLSUnsupportedError = true;
6560         // We still need to mark the variable as TLS so it shows up in AST with
6561         // proper storage class for other tools to use even if we're not going
6562         // to emit any code for it.
6563         NewVD->setTSCSpec(TSCS);
6564       } else
6565         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6566              diag::err_thread_unsupported);
6567     } else
6568       NewVD->setTSCSpec(TSCS);
6569   }
6570 
6571   // C99 6.7.4p3
6572   //   An inline definition of a function with external linkage shall
6573   //   not contain a definition of a modifiable object with static or
6574   //   thread storage duration...
6575   // We only apply this when the function is required to be defined
6576   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6577   // that a local variable with thread storage duration still has to
6578   // be marked 'static'.  Also note that it's possible to get these
6579   // semantics in C++ using __attribute__((gnu_inline)).
6580   if (SC == SC_Static && S->getFnParent() != nullptr &&
6581       !NewVD->getType().isConstQualified()) {
6582     FunctionDecl *CurFD = getCurFunctionDecl();
6583     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6584       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6585            diag::warn_static_local_in_extern_inline);
6586       MaybeSuggestAddingStaticToDecl(CurFD);
6587     }
6588   }
6589 
6590   if (D.getDeclSpec().isModulePrivateSpecified()) {
6591     if (IsVariableTemplateSpecialization)
6592       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6593           << (IsPartialSpecialization ? 1 : 0)
6594           << FixItHint::CreateRemoval(
6595                  D.getDeclSpec().getModulePrivateSpecLoc());
6596     else if (IsMemberSpecialization)
6597       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6598         << 2
6599         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6600     else if (NewVD->hasLocalStorage())
6601       Diag(NewVD->getLocation(), diag::err_module_private_local)
6602         << 0 << NewVD->getDeclName()
6603         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6604         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6605     else {
6606       NewVD->setModulePrivate();
6607       if (NewTemplate)
6608         NewTemplate->setModulePrivate();
6609       for (auto *B : Bindings)
6610         B->setModulePrivate();
6611     }
6612   }
6613 
6614   // Handle attributes prior to checking for duplicates in MergeVarDecl
6615   ProcessDeclAttributes(S, NewVD, D);
6616 
6617   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6618     if (EmitTLSUnsupportedError &&
6619         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6620          (getLangOpts().OpenMPIsDevice &&
6621           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6622       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6623            diag::err_thread_unsupported);
6624     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6625     // storage [duration]."
6626     if (SC == SC_None && S->getFnParent() != nullptr &&
6627         (NewVD->hasAttr<CUDASharedAttr>() ||
6628          NewVD->hasAttr<CUDAConstantAttr>())) {
6629       NewVD->setStorageClass(SC_Static);
6630     }
6631   }
6632 
6633   // Ensure that dllimport globals without explicit storage class are treated as
6634   // extern. The storage class is set above using parsed attributes. Now we can
6635   // check the VarDecl itself.
6636   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6637          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6638          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6639 
6640   // In auto-retain/release, infer strong retension for variables of
6641   // retainable type.
6642   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6643     NewVD->setInvalidDecl();
6644 
6645   // Handle GNU asm-label extension (encoded as an attribute).
6646   if (Expr *E = (Expr*)D.getAsmLabel()) {
6647     // The parser guarantees this is a string.
6648     StringLiteral *SE = cast<StringLiteral>(E);
6649     StringRef Label = SE->getString();
6650     if (S->getFnParent() != nullptr) {
6651       switch (SC) {
6652       case SC_None:
6653       case SC_Auto:
6654         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6655         break;
6656       case SC_Register:
6657         // Local Named register
6658         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6659             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6660           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6661         break;
6662       case SC_Static:
6663       case SC_Extern:
6664       case SC_PrivateExtern:
6665         break;
6666       }
6667     } else if (SC == SC_Register) {
6668       // Global Named register
6669       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6670         const auto &TI = Context.getTargetInfo();
6671         bool HasSizeMismatch;
6672 
6673         if (!TI.isValidGCCRegisterName(Label))
6674           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6675         else if (!TI.validateGlobalRegisterVariable(Label,
6676                                                     Context.getTypeSize(R),
6677                                                     HasSizeMismatch))
6678           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6679         else if (HasSizeMismatch)
6680           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6681       }
6682 
6683       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6684         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6685         NewVD->setInvalidDecl(true);
6686       }
6687     }
6688 
6689     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6690                                                 Context, Label, 0));
6691   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6692     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6693       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6694     if (I != ExtnameUndeclaredIdentifiers.end()) {
6695       if (isDeclExternC(NewVD)) {
6696         NewVD->addAttr(I->second);
6697         ExtnameUndeclaredIdentifiers.erase(I);
6698       } else
6699         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6700             << /*Variable*/1 << NewVD;
6701     }
6702   }
6703 
6704   // Find the shadowed declaration before filtering for scope.
6705   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6706                                 ? getShadowedDeclaration(NewVD, Previous)
6707                                 : nullptr;
6708 
6709   // Don't consider existing declarations that are in a different
6710   // scope and are out-of-semantic-context declarations (if the new
6711   // declaration has linkage).
6712   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6713                        D.getCXXScopeSpec().isNotEmpty() ||
6714                        IsMemberSpecialization ||
6715                        IsVariableTemplateSpecialization);
6716 
6717   // Check whether the previous declaration is in the same block scope. This
6718   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6719   if (getLangOpts().CPlusPlus &&
6720       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6721     NewVD->setPreviousDeclInSameBlockScope(
6722         Previous.isSingleResult() && !Previous.isShadowed() &&
6723         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6724 
6725   if (!getLangOpts().CPlusPlus) {
6726     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6727   } else {
6728     // If this is an explicit specialization of a static data member, check it.
6729     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6730         CheckMemberSpecialization(NewVD, Previous))
6731       NewVD->setInvalidDecl();
6732 
6733     // Merge the decl with the existing one if appropriate.
6734     if (!Previous.empty()) {
6735       if (Previous.isSingleResult() &&
6736           isa<FieldDecl>(Previous.getFoundDecl()) &&
6737           D.getCXXScopeSpec().isSet()) {
6738         // The user tried to define a non-static data member
6739         // out-of-line (C++ [dcl.meaning]p1).
6740         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6741           << D.getCXXScopeSpec().getRange();
6742         Previous.clear();
6743         NewVD->setInvalidDecl();
6744       }
6745     } else if (D.getCXXScopeSpec().isSet()) {
6746       // No previous declaration in the qualifying scope.
6747       Diag(D.getIdentifierLoc(), diag::err_no_member)
6748         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6749         << D.getCXXScopeSpec().getRange();
6750       NewVD->setInvalidDecl();
6751     }
6752 
6753     if (!IsVariableTemplateSpecialization)
6754       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6755 
6756     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6757     // an explicit specialization (14.8.3) or a partial specialization of a
6758     // concept definition.
6759     if (IsVariableTemplateSpecialization &&
6760         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6761         Previous.isSingleResult()) {
6762       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6763       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6764         if (VarTmpl->isConcept()) {
6765           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6766               << 1                            /*variable*/
6767               << (IsPartialSpecialization ? 2 /*partially specialized*/
6768                                           : 1 /*explicitly specialized*/);
6769           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6770           NewVD->setInvalidDecl();
6771         }
6772       }
6773     }
6774 
6775     if (NewTemplate) {
6776       VarTemplateDecl *PrevVarTemplate =
6777           NewVD->getPreviousDecl()
6778               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6779               : nullptr;
6780 
6781       // Check the template parameter list of this declaration, possibly
6782       // merging in the template parameter list from the previous variable
6783       // template declaration.
6784       if (CheckTemplateParameterList(
6785               TemplateParams,
6786               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6787                               : nullptr,
6788               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6789                DC->isDependentContext())
6790                   ? TPC_ClassTemplateMember
6791                   : TPC_VarTemplate))
6792         NewVD->setInvalidDecl();
6793 
6794       // If we are providing an explicit specialization of a static variable
6795       // template, make a note of that.
6796       if (PrevVarTemplate &&
6797           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6798         PrevVarTemplate->setMemberSpecialization();
6799     }
6800   }
6801 
6802   // Diagnose shadowed variables iff this isn't a redeclaration.
6803   if (ShadowedDecl && !D.isRedeclaration())
6804     CheckShadow(NewVD, ShadowedDecl, Previous);
6805 
6806   ProcessPragmaWeak(S, NewVD);
6807 
6808   // If this is the first declaration of an extern C variable, update
6809   // the map of such variables.
6810   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6811       isIncompleteDeclExternC(*this, NewVD))
6812     RegisterLocallyScopedExternCDecl(NewVD, S);
6813 
6814   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6815     Decl *ManglingContextDecl;
6816     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6817             NewVD->getDeclContext(), ManglingContextDecl)) {
6818       Context.setManglingNumber(
6819           NewVD, MCtx->getManglingNumber(
6820                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6821       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6822     }
6823   }
6824 
6825   // Special handling of variable named 'main'.
6826   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6827       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6828       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6829 
6830     // C++ [basic.start.main]p3
6831     // A program that declares a variable main at global scope is ill-formed.
6832     if (getLangOpts().CPlusPlus)
6833       Diag(D.getLocStart(), diag::err_main_global_variable);
6834 
6835     // In C, and external-linkage variable named main results in undefined
6836     // behavior.
6837     else if (NewVD->hasExternalFormalLinkage())
6838       Diag(D.getLocStart(), diag::warn_main_redefined);
6839   }
6840 
6841   if (D.isRedeclaration() && !Previous.empty()) {
6842     checkDLLAttributeRedeclaration(
6843         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6844         IsMemberSpecialization, D.isFunctionDefinition());
6845   }
6846 
6847   if (NewTemplate) {
6848     if (NewVD->isInvalidDecl())
6849       NewTemplate->setInvalidDecl();
6850     ActOnDocumentableDecl(NewTemplate);
6851     return NewTemplate;
6852   }
6853 
6854   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6855     CompleteMemberSpecialization(NewVD, Previous);
6856 
6857   return NewVD;
6858 }
6859 
6860 /// Enum describing the %select options in diag::warn_decl_shadow.
6861 enum ShadowedDeclKind {
6862   SDK_Local,
6863   SDK_Global,
6864   SDK_StaticMember,
6865   SDK_Field,
6866   SDK_Typedef,
6867   SDK_Using
6868 };
6869 
6870 /// Determine what kind of declaration we're shadowing.
6871 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6872                                                 const DeclContext *OldDC) {
6873   if (isa<TypeAliasDecl>(ShadowedDecl))
6874     return SDK_Using;
6875   else if (isa<TypedefDecl>(ShadowedDecl))
6876     return SDK_Typedef;
6877   else if (isa<RecordDecl>(OldDC))
6878     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6879 
6880   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6881 }
6882 
6883 /// Return the location of the capture if the given lambda captures the given
6884 /// variable \p VD, or an invalid source location otherwise.
6885 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6886                                          const VarDecl *VD) {
6887   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6888     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6889       return Capture.getLocation();
6890   }
6891   return SourceLocation();
6892 }
6893 
6894 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6895                                      const LookupResult &R) {
6896   // Only diagnose if we're shadowing an unambiguous field or variable.
6897   if (R.getResultKind() != LookupResult::Found)
6898     return false;
6899 
6900   // Return false if warning is ignored.
6901   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6902 }
6903 
6904 /// \brief Return the declaration shadowed by the given variable \p D, or null
6905 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6906 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6907                                         const LookupResult &R) {
6908   if (!shouldWarnIfShadowedDecl(Diags, R))
6909     return nullptr;
6910 
6911   // Don't diagnose declarations at file scope.
6912   if (D->hasGlobalStorage())
6913     return nullptr;
6914 
6915   NamedDecl *ShadowedDecl = R.getFoundDecl();
6916   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6917              ? ShadowedDecl
6918              : nullptr;
6919 }
6920 
6921 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6922 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6923 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6924                                         const LookupResult &R) {
6925   // Don't warn if typedef declaration is part of a class
6926   if (D->getDeclContext()->isRecord())
6927     return nullptr;
6928 
6929   if (!shouldWarnIfShadowedDecl(Diags, R))
6930     return nullptr;
6931 
6932   NamedDecl *ShadowedDecl = R.getFoundDecl();
6933   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6934 }
6935 
6936 /// \brief Diagnose variable or built-in function shadowing.  Implements
6937 /// -Wshadow.
6938 ///
6939 /// This method is called whenever a VarDecl is added to a "useful"
6940 /// scope.
6941 ///
6942 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6943 /// \param R the lookup of the name
6944 ///
6945 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6946                        const LookupResult &R) {
6947   DeclContext *NewDC = D->getDeclContext();
6948 
6949   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6950     // Fields are not shadowed by variables in C++ static methods.
6951     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6952       if (MD->isStatic())
6953         return;
6954 
6955     // Fields shadowed by constructor parameters are a special case. Usually
6956     // the constructor initializes the field with the parameter.
6957     if (isa<CXXConstructorDecl>(NewDC))
6958       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6959         // Remember that this was shadowed so we can either warn about its
6960         // modification or its existence depending on warning settings.
6961         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6962         return;
6963       }
6964   }
6965 
6966   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6967     if (shadowedVar->isExternC()) {
6968       // For shadowing external vars, make sure that we point to the global
6969       // declaration, not a locally scoped extern declaration.
6970       for (auto I : shadowedVar->redecls())
6971         if (I->isFileVarDecl()) {
6972           ShadowedDecl = I;
6973           break;
6974         }
6975     }
6976 
6977   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6978 
6979   unsigned WarningDiag = diag::warn_decl_shadow;
6980   SourceLocation CaptureLoc;
6981   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6982       isa<CXXMethodDecl>(NewDC)) {
6983     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6984       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6985         if (RD->getLambdaCaptureDefault() == LCD_None) {
6986           // Try to avoid warnings for lambdas with an explicit capture list.
6987           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6988           // Warn only when the lambda captures the shadowed decl explicitly.
6989           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6990           if (CaptureLoc.isInvalid())
6991             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6992         } else {
6993           // Remember that this was shadowed so we can avoid the warning if the
6994           // shadowed decl isn't captured and the warning settings allow it.
6995           cast<LambdaScopeInfo>(getCurFunction())
6996               ->ShadowingDecls.push_back(
6997                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6998           return;
6999         }
7000       }
7001 
7002       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7003         // A variable can't shadow a local variable in an enclosing scope, if
7004         // they are separated by a non-capturing declaration context.
7005         for (DeclContext *ParentDC = NewDC;
7006              ParentDC && !ParentDC->Equals(OldDC);
7007              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7008           // Only block literals, captured statements, and lambda expressions
7009           // can capture; other scopes don't.
7010           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7011               !isLambdaCallOperator(ParentDC)) {
7012             return;
7013           }
7014         }
7015       }
7016     }
7017   }
7018 
7019   // Only warn about certain kinds of shadowing for class members.
7020   if (NewDC && NewDC->isRecord()) {
7021     // In particular, don't warn about shadowing non-class members.
7022     if (!OldDC->isRecord())
7023       return;
7024 
7025     // TODO: should we warn about static data members shadowing
7026     // static data members from base classes?
7027 
7028     // TODO: don't diagnose for inaccessible shadowed members.
7029     // This is hard to do perfectly because we might friend the
7030     // shadowing context, but that's just a false negative.
7031   }
7032 
7033 
7034   DeclarationName Name = R.getLookupName();
7035 
7036   // Emit warning and note.
7037   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7038     return;
7039   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7040   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7041   if (!CaptureLoc.isInvalid())
7042     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7043         << Name << /*explicitly*/ 1;
7044   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7045 }
7046 
7047 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7048 /// when these variables are captured by the lambda.
7049 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7050   for (const auto &Shadow : LSI->ShadowingDecls) {
7051     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7052     // Try to avoid the warning when the shadowed decl isn't captured.
7053     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7054     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7055     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7056                                        ? diag::warn_decl_shadow_uncaptured_local
7057                                        : diag::warn_decl_shadow)
7058         << Shadow.VD->getDeclName()
7059         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7060     if (!CaptureLoc.isInvalid())
7061       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7062           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7063     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7064   }
7065 }
7066 
7067 /// \brief Check -Wshadow without the advantage of a previous lookup.
7068 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7069   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7070     return;
7071 
7072   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7073                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7074   LookupName(R, S);
7075   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7076     CheckShadow(D, ShadowedDecl, R);
7077 }
7078 
7079 /// Check if 'E', which is an expression that is about to be modified, refers
7080 /// to a constructor parameter that shadows a field.
7081 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7082   // Quickly ignore expressions that can't be shadowing ctor parameters.
7083   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7084     return;
7085   E = E->IgnoreParenImpCasts();
7086   auto *DRE = dyn_cast<DeclRefExpr>(E);
7087   if (!DRE)
7088     return;
7089   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7090   auto I = ShadowingDecls.find(D);
7091   if (I == ShadowingDecls.end())
7092     return;
7093   const NamedDecl *ShadowedDecl = I->second;
7094   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7095   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7096   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7097   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7098 
7099   // Avoid issuing multiple warnings about the same decl.
7100   ShadowingDecls.erase(I);
7101 }
7102 
7103 /// Check for conflict between this global or extern "C" declaration and
7104 /// previous global or extern "C" declarations. This is only used in C++.
7105 template<typename T>
7106 static bool checkGlobalOrExternCConflict(
7107     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7108   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7109   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7110 
7111   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7112     // The common case: this global doesn't conflict with any extern "C"
7113     // declaration.
7114     return false;
7115   }
7116 
7117   if (Prev) {
7118     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7119       // Both the old and new declarations have C language linkage. This is a
7120       // redeclaration.
7121       Previous.clear();
7122       Previous.addDecl(Prev);
7123       return true;
7124     }
7125 
7126     // This is a global, non-extern "C" declaration, and there is a previous
7127     // non-global extern "C" declaration. Diagnose if this is a variable
7128     // declaration.
7129     if (!isa<VarDecl>(ND))
7130       return false;
7131   } else {
7132     // The declaration is extern "C". Check for any declaration in the
7133     // translation unit which might conflict.
7134     if (IsGlobal) {
7135       // We have already performed the lookup into the translation unit.
7136       IsGlobal = false;
7137       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7138            I != E; ++I) {
7139         if (isa<VarDecl>(*I)) {
7140           Prev = *I;
7141           break;
7142         }
7143       }
7144     } else {
7145       DeclContext::lookup_result R =
7146           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7147       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7148            I != E; ++I) {
7149         if (isa<VarDecl>(*I)) {
7150           Prev = *I;
7151           break;
7152         }
7153         // FIXME: If we have any other entity with this name in global scope,
7154         // the declaration is ill-formed, but that is a defect: it breaks the
7155         // 'stat' hack, for instance. Only variables can have mangled name
7156         // clashes with extern "C" declarations, so only they deserve a
7157         // diagnostic.
7158       }
7159     }
7160 
7161     if (!Prev)
7162       return false;
7163   }
7164 
7165   // Use the first declaration's location to ensure we point at something which
7166   // is lexically inside an extern "C" linkage-spec.
7167   assert(Prev && "should have found a previous declaration to diagnose");
7168   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7169     Prev = FD->getFirstDecl();
7170   else
7171     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7172 
7173   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7174     << IsGlobal << ND;
7175   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7176     << IsGlobal;
7177   return false;
7178 }
7179 
7180 /// Apply special rules for handling extern "C" declarations. Returns \c true
7181 /// if we have found that this is a redeclaration of some prior entity.
7182 ///
7183 /// Per C++ [dcl.link]p6:
7184 ///   Two declarations [for a function or variable] with C language linkage
7185 ///   with the same name that appear in different scopes refer to the same
7186 ///   [entity]. An entity with C language linkage shall not be declared with
7187 ///   the same name as an entity in global scope.
7188 template<typename T>
7189 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7190                                                   LookupResult &Previous) {
7191   if (!S.getLangOpts().CPlusPlus) {
7192     // In C, when declaring a global variable, look for a corresponding 'extern'
7193     // variable declared in function scope. We don't need this in C++, because
7194     // we find local extern decls in the surrounding file-scope DeclContext.
7195     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7196       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7197         Previous.clear();
7198         Previous.addDecl(Prev);
7199         return true;
7200       }
7201     }
7202     return false;
7203   }
7204 
7205   // A declaration in the translation unit can conflict with an extern "C"
7206   // declaration.
7207   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7208     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7209 
7210   // An extern "C" declaration can conflict with a declaration in the
7211   // translation unit or can be a redeclaration of an extern "C" declaration
7212   // in another scope.
7213   if (isIncompleteDeclExternC(S,ND))
7214     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7215 
7216   // Neither global nor extern "C": nothing to do.
7217   return false;
7218 }
7219 
7220 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7221   // If the decl is already known invalid, don't check it.
7222   if (NewVD->isInvalidDecl())
7223     return;
7224 
7225   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7226   QualType T = TInfo->getType();
7227 
7228   // Defer checking an 'auto' type until its initializer is attached.
7229   if (T->isUndeducedType())
7230     return;
7231 
7232   if (NewVD->hasAttrs())
7233     CheckAlignasUnderalignment(NewVD);
7234 
7235   if (T->isObjCObjectType()) {
7236     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7237       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7238     T = Context.getObjCObjectPointerType(T);
7239     NewVD->setType(T);
7240   }
7241 
7242   // Emit an error if an address space was applied to decl with local storage.
7243   // This includes arrays of objects with address space qualifiers, but not
7244   // automatic variables that point to other address spaces.
7245   // ISO/IEC TR 18037 S5.1.2
7246   if (!getLangOpts().OpenCL
7247       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7248     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7249     NewVD->setInvalidDecl();
7250     return;
7251   }
7252 
7253   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7254   // scope.
7255   if (getLangOpts().OpenCLVersion == 120 &&
7256       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7257       NewVD->isStaticLocal()) {
7258     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7259     NewVD->setInvalidDecl();
7260     return;
7261   }
7262 
7263   if (getLangOpts().OpenCL) {
7264     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7265     if (NewVD->hasAttr<BlocksAttr>()) {
7266       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7267       return;
7268     }
7269 
7270     if (T->isBlockPointerType()) {
7271       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7272       // can't use 'extern' storage class.
7273       if (!T.isConstQualified()) {
7274         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7275             << 0 /*const*/;
7276         NewVD->setInvalidDecl();
7277         return;
7278       }
7279       if (NewVD->hasExternalStorage()) {
7280         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7281         NewVD->setInvalidDecl();
7282         return;
7283       }
7284     }
7285     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7286     // __constant address space.
7287     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7288     // variables inside a function can also be declared in the global
7289     // address space.
7290     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7291         NewVD->hasExternalStorage()) {
7292       if (!T->isSamplerT() &&
7293           !(T.getAddressSpace() == LangAS::opencl_constant ||
7294             (T.getAddressSpace() == LangAS::opencl_global &&
7295              getLangOpts().OpenCLVersion == 200))) {
7296         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7297         if (getLangOpts().OpenCLVersion == 200)
7298           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7299               << Scope << "global or constant";
7300         else
7301           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7302               << Scope << "constant";
7303         NewVD->setInvalidDecl();
7304         return;
7305       }
7306     } else {
7307       if (T.getAddressSpace() == LangAS::opencl_global) {
7308         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7309             << 1 /*is any function*/ << "global";
7310         NewVD->setInvalidDecl();
7311         return;
7312       }
7313       if (T.getAddressSpace() == LangAS::opencl_constant ||
7314           T.getAddressSpace() == LangAS::opencl_local) {
7315         FunctionDecl *FD = getCurFunctionDecl();
7316         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7317         // in functions.
7318         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7319           if (T.getAddressSpace() == LangAS::opencl_constant)
7320             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7321                 << 0 /*non-kernel only*/ << "constant";
7322           else
7323             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7324                 << 0 /*non-kernel only*/ << "local";
7325           NewVD->setInvalidDecl();
7326           return;
7327         }
7328         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7329         // in the outermost scope of a kernel function.
7330         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7331           if (!getCurScope()->isFunctionScope()) {
7332             if (T.getAddressSpace() == LangAS::opencl_constant)
7333               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7334                   << "constant";
7335             else
7336               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7337                   << "local";
7338             NewVD->setInvalidDecl();
7339             return;
7340           }
7341         }
7342       } else if (T.getAddressSpace() != LangAS::Default) {
7343         // Do not allow other address spaces on automatic variable.
7344         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7345         NewVD->setInvalidDecl();
7346         return;
7347       }
7348     }
7349   }
7350 
7351   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7352       && !NewVD->hasAttr<BlocksAttr>()) {
7353     if (getLangOpts().getGC() != LangOptions::NonGC)
7354       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7355     else {
7356       assert(!getLangOpts().ObjCAutoRefCount);
7357       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7358     }
7359   }
7360 
7361   bool isVM = T->isVariablyModifiedType();
7362   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7363       NewVD->hasAttr<BlocksAttr>())
7364     getCurFunction()->setHasBranchProtectedScope();
7365 
7366   if ((isVM && NewVD->hasLinkage()) ||
7367       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7368     bool SizeIsNegative;
7369     llvm::APSInt Oversized;
7370     TypeSourceInfo *FixedTInfo =
7371       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7372                                                     SizeIsNegative, Oversized);
7373     if (!FixedTInfo && T->isVariableArrayType()) {
7374       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7375       // FIXME: This won't give the correct result for
7376       // int a[10][n];
7377       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7378 
7379       if (NewVD->isFileVarDecl())
7380         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7381         << SizeRange;
7382       else if (NewVD->isStaticLocal())
7383         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7384         << SizeRange;
7385       else
7386         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7387         << SizeRange;
7388       NewVD->setInvalidDecl();
7389       return;
7390     }
7391 
7392     if (!FixedTInfo) {
7393       if (NewVD->isFileVarDecl())
7394         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7395       else
7396         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7397       NewVD->setInvalidDecl();
7398       return;
7399     }
7400 
7401     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7402     NewVD->setType(FixedTInfo->getType());
7403     NewVD->setTypeSourceInfo(FixedTInfo);
7404   }
7405 
7406   if (T->isVoidType()) {
7407     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7408     //                    of objects and functions.
7409     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7410       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7411         << T;
7412       NewVD->setInvalidDecl();
7413       return;
7414     }
7415   }
7416 
7417   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7418     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7419     NewVD->setInvalidDecl();
7420     return;
7421   }
7422 
7423   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7424     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7425     NewVD->setInvalidDecl();
7426     return;
7427   }
7428 
7429   if (NewVD->isConstexpr() && !T->isDependentType() &&
7430       RequireLiteralType(NewVD->getLocation(), T,
7431                          diag::err_constexpr_var_non_literal)) {
7432     NewVD->setInvalidDecl();
7433     return;
7434   }
7435 }
7436 
7437 /// \brief Perform semantic checking on a newly-created variable
7438 /// declaration.
7439 ///
7440 /// This routine performs all of the type-checking required for a
7441 /// variable declaration once it has been built. It is used both to
7442 /// check variables after they have been parsed and their declarators
7443 /// have been translated into a declaration, and to check variables
7444 /// that have been instantiated from a template.
7445 ///
7446 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7447 ///
7448 /// Returns true if the variable declaration is a redeclaration.
7449 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7450   CheckVariableDeclarationType(NewVD);
7451 
7452   // If the decl is already known invalid, don't check it.
7453   if (NewVD->isInvalidDecl())
7454     return false;
7455 
7456   // If we did not find anything by this name, look for a non-visible
7457   // extern "C" declaration with the same name.
7458   if (Previous.empty() &&
7459       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7460     Previous.setShadowed();
7461 
7462   if (!Previous.empty()) {
7463     MergeVarDecl(NewVD, Previous);
7464     return true;
7465   }
7466   return false;
7467 }
7468 
7469 namespace {
7470 struct FindOverriddenMethod {
7471   Sema *S;
7472   CXXMethodDecl *Method;
7473 
7474   /// Member lookup function that determines whether a given C++
7475   /// method overrides a method in a base class, to be used with
7476   /// CXXRecordDecl::lookupInBases().
7477   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7478     RecordDecl *BaseRecord =
7479         Specifier->getType()->getAs<RecordType>()->getDecl();
7480 
7481     DeclarationName Name = Method->getDeclName();
7482 
7483     // FIXME: Do we care about other names here too?
7484     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7485       // We really want to find the base class destructor here.
7486       QualType T = S->Context.getTypeDeclType(BaseRecord);
7487       CanQualType CT = S->Context.getCanonicalType(T);
7488 
7489       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7490     }
7491 
7492     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7493          Path.Decls = Path.Decls.slice(1)) {
7494       NamedDecl *D = Path.Decls.front();
7495       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7496         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7497           return true;
7498       }
7499     }
7500 
7501     return false;
7502   }
7503 };
7504 
7505 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7506 } // end anonymous namespace
7507 
7508 /// \brief Report an error regarding overriding, along with any relevant
7509 /// overriden methods.
7510 ///
7511 /// \param DiagID the primary error to report.
7512 /// \param MD the overriding method.
7513 /// \param OEK which overrides to include as notes.
7514 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7515                             OverrideErrorKind OEK = OEK_All) {
7516   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7517   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7518                                       E = MD->end_overridden_methods();
7519        I != E; ++I) {
7520     // This check (& the OEK parameter) could be replaced by a predicate, but
7521     // without lambdas that would be overkill. This is still nicer than writing
7522     // out the diag loop 3 times.
7523     if ((OEK == OEK_All) ||
7524         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7525         (OEK == OEK_Deleted && (*I)->isDeleted()))
7526       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7527   }
7528 }
7529 
7530 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7531 /// and if so, check that it's a valid override and remember it.
7532 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7533   // Look for methods in base classes that this method might override.
7534   CXXBasePaths Paths;
7535   FindOverriddenMethod FOM;
7536   FOM.Method = MD;
7537   FOM.S = this;
7538   bool hasDeletedOverridenMethods = false;
7539   bool hasNonDeletedOverridenMethods = false;
7540   bool AddedAny = false;
7541   if (DC->lookupInBases(FOM, Paths)) {
7542     for (auto *I : Paths.found_decls()) {
7543       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7544         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7545         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7546             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7547             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7548             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7549           hasDeletedOverridenMethods |= OldMD->isDeleted();
7550           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7551           AddedAny = true;
7552         }
7553       }
7554     }
7555   }
7556 
7557   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7558     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7559   }
7560   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7561     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7562   }
7563 
7564   return AddedAny;
7565 }
7566 
7567 namespace {
7568   // Struct for holding all of the extra arguments needed by
7569   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7570   struct ActOnFDArgs {
7571     Scope *S;
7572     Declarator &D;
7573     MultiTemplateParamsArg TemplateParamLists;
7574     bool AddToScope;
7575   };
7576 } // end anonymous namespace
7577 
7578 namespace {
7579 
7580 // Callback to only accept typo corrections that have a non-zero edit distance.
7581 // Also only accept corrections that have the same parent decl.
7582 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7583  public:
7584   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7585                             CXXRecordDecl *Parent)
7586       : Context(Context), OriginalFD(TypoFD),
7587         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7588 
7589   bool ValidateCandidate(const TypoCorrection &candidate) override {
7590     if (candidate.getEditDistance() == 0)
7591       return false;
7592 
7593     SmallVector<unsigned, 1> MismatchedParams;
7594     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7595                                           CDeclEnd = candidate.end();
7596          CDecl != CDeclEnd; ++CDecl) {
7597       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7598 
7599       if (FD && !FD->hasBody() &&
7600           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7601         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7602           CXXRecordDecl *Parent = MD->getParent();
7603           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7604             return true;
7605         } else if (!ExpectedParent) {
7606           return true;
7607         }
7608       }
7609     }
7610 
7611     return false;
7612   }
7613 
7614  private:
7615   ASTContext &Context;
7616   FunctionDecl *OriginalFD;
7617   CXXRecordDecl *ExpectedParent;
7618 };
7619 
7620 } // end anonymous namespace
7621 
7622 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7623   TypoCorrectedFunctionDefinitions.insert(F);
7624 }
7625 
7626 /// \brief Generate diagnostics for an invalid function redeclaration.
7627 ///
7628 /// This routine handles generating the diagnostic messages for an invalid
7629 /// function redeclaration, including finding possible similar declarations
7630 /// or performing typo correction if there are no previous declarations with
7631 /// the same name.
7632 ///
7633 /// Returns a NamedDecl iff typo correction was performed and substituting in
7634 /// the new declaration name does not cause new errors.
7635 static NamedDecl *DiagnoseInvalidRedeclaration(
7636     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7637     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7638   DeclarationName Name = NewFD->getDeclName();
7639   DeclContext *NewDC = NewFD->getDeclContext();
7640   SmallVector<unsigned, 1> MismatchedParams;
7641   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7642   TypoCorrection Correction;
7643   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7644   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7645                                    : diag::err_member_decl_does_not_match;
7646   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7647                     IsLocalFriend ? Sema::LookupLocalFriendName
7648                                   : Sema::LookupOrdinaryName,
7649                     Sema::ForRedeclaration);
7650 
7651   NewFD->setInvalidDecl();
7652   if (IsLocalFriend)
7653     SemaRef.LookupName(Prev, S);
7654   else
7655     SemaRef.LookupQualifiedName(Prev, NewDC);
7656   assert(!Prev.isAmbiguous() &&
7657          "Cannot have an ambiguity in previous-declaration lookup");
7658   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7659   if (!Prev.empty()) {
7660     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7661          Func != FuncEnd; ++Func) {
7662       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7663       if (FD &&
7664           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7665         // Add 1 to the index so that 0 can mean the mismatch didn't
7666         // involve a parameter
7667         unsigned ParamNum =
7668             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7669         NearMatches.push_back(std::make_pair(FD, ParamNum));
7670       }
7671     }
7672   // If the qualified name lookup yielded nothing, try typo correction
7673   } else if ((Correction = SemaRef.CorrectTypo(
7674                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7675                   &ExtraArgs.D.getCXXScopeSpec(),
7676                   llvm::make_unique<DifferentNameValidatorCCC>(
7677                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7678                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7679     // Set up everything for the call to ActOnFunctionDeclarator
7680     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7681                               ExtraArgs.D.getIdentifierLoc());
7682     Previous.clear();
7683     Previous.setLookupName(Correction.getCorrection());
7684     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7685                                     CDeclEnd = Correction.end();
7686          CDecl != CDeclEnd; ++CDecl) {
7687       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7688       if (FD && !FD->hasBody() &&
7689           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7690         Previous.addDecl(FD);
7691       }
7692     }
7693     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7694 
7695     NamedDecl *Result;
7696     // Retry building the function declaration with the new previous
7697     // declarations, and with errors suppressed.
7698     {
7699       // Trap errors.
7700       Sema::SFINAETrap Trap(SemaRef);
7701 
7702       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7703       // pieces need to verify the typo-corrected C++ declaration and hopefully
7704       // eliminate the need for the parameter pack ExtraArgs.
7705       Result = SemaRef.ActOnFunctionDeclarator(
7706           ExtraArgs.S, ExtraArgs.D,
7707           Correction.getCorrectionDecl()->getDeclContext(),
7708           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7709           ExtraArgs.AddToScope);
7710 
7711       if (Trap.hasErrorOccurred())
7712         Result = nullptr;
7713     }
7714 
7715     if (Result) {
7716       // Determine which correction we picked.
7717       Decl *Canonical = Result->getCanonicalDecl();
7718       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7719            I != E; ++I)
7720         if ((*I)->getCanonicalDecl() == Canonical)
7721           Correction.setCorrectionDecl(*I);
7722 
7723       // Let Sema know about the correction.
7724       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7725       SemaRef.diagnoseTypo(
7726           Correction,
7727           SemaRef.PDiag(IsLocalFriend
7728                           ? diag::err_no_matching_local_friend_suggest
7729                           : diag::err_member_decl_does_not_match_suggest)
7730             << Name << NewDC << IsDefinition);
7731       return Result;
7732     }
7733 
7734     // Pretend the typo correction never occurred
7735     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7736                               ExtraArgs.D.getIdentifierLoc());
7737     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7738     Previous.clear();
7739     Previous.setLookupName(Name);
7740   }
7741 
7742   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7743       << Name << NewDC << IsDefinition << NewFD->getLocation();
7744 
7745   bool NewFDisConst = false;
7746   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7747     NewFDisConst = NewMD->isConst();
7748 
7749   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7750        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7751        NearMatch != NearMatchEnd; ++NearMatch) {
7752     FunctionDecl *FD = NearMatch->first;
7753     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7754     bool FDisConst = MD && MD->isConst();
7755     bool IsMember = MD || !IsLocalFriend;
7756 
7757     // FIXME: These notes are poorly worded for the local friend case.
7758     if (unsigned Idx = NearMatch->second) {
7759       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7760       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7761       if (Loc.isInvalid()) Loc = FD->getLocation();
7762       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7763                                  : diag::note_local_decl_close_param_match)
7764         << Idx << FDParam->getType()
7765         << NewFD->getParamDecl(Idx - 1)->getType();
7766     } else if (FDisConst != NewFDisConst) {
7767       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7768           << NewFDisConst << FD->getSourceRange().getEnd();
7769     } else
7770       SemaRef.Diag(FD->getLocation(),
7771                    IsMember ? diag::note_member_def_close_match
7772                             : diag::note_local_decl_close_match);
7773   }
7774   return nullptr;
7775 }
7776 
7777 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7778   switch (D.getDeclSpec().getStorageClassSpec()) {
7779   default: llvm_unreachable("Unknown storage class!");
7780   case DeclSpec::SCS_auto:
7781   case DeclSpec::SCS_register:
7782   case DeclSpec::SCS_mutable:
7783     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7784                  diag::err_typecheck_sclass_func);
7785     D.getMutableDeclSpec().ClearStorageClassSpecs();
7786     D.setInvalidType();
7787     break;
7788   case DeclSpec::SCS_unspecified: break;
7789   case DeclSpec::SCS_extern:
7790     if (D.getDeclSpec().isExternInLinkageSpec())
7791       return SC_None;
7792     return SC_Extern;
7793   case DeclSpec::SCS_static: {
7794     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7795       // C99 6.7.1p5:
7796       //   The declaration of an identifier for a function that has
7797       //   block scope shall have no explicit storage-class specifier
7798       //   other than extern
7799       // See also (C++ [dcl.stc]p4).
7800       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7801                    diag::err_static_block_func);
7802       break;
7803     } else
7804       return SC_Static;
7805   }
7806   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7807   }
7808 
7809   // No explicit storage class has already been returned
7810   return SC_None;
7811 }
7812 
7813 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7814                                            DeclContext *DC, QualType &R,
7815                                            TypeSourceInfo *TInfo,
7816                                            StorageClass SC,
7817                                            bool &IsVirtualOkay) {
7818   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7819   DeclarationName Name = NameInfo.getName();
7820 
7821   FunctionDecl *NewFD = nullptr;
7822   bool isInline = D.getDeclSpec().isInlineSpecified();
7823 
7824   if (!SemaRef.getLangOpts().CPlusPlus) {
7825     // Determine whether the function was written with a
7826     // prototype. This true when:
7827     //   - there is a prototype in the declarator, or
7828     //   - the type R of the function is some kind of typedef or other non-
7829     //     attributed reference to a type name (which eventually refers to a
7830     //     function type).
7831     bool HasPrototype =
7832       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7833       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7834 
7835     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7836                                  D.getLocStart(), NameInfo, R,
7837                                  TInfo, SC, isInline,
7838                                  HasPrototype, false);
7839     if (D.isInvalidType())
7840       NewFD->setInvalidDecl();
7841 
7842     return NewFD;
7843   }
7844 
7845   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7846   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7847 
7848   // Check that the return type is not an abstract class type.
7849   // For record types, this is done by the AbstractClassUsageDiagnoser once
7850   // the class has been completely parsed.
7851   if (!DC->isRecord() &&
7852       SemaRef.RequireNonAbstractType(
7853           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7854           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7855     D.setInvalidType();
7856 
7857   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7858     // This is a C++ constructor declaration.
7859     assert(DC->isRecord() &&
7860            "Constructors can only be declared in a member context");
7861 
7862     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7863     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7864                                       D.getLocStart(), NameInfo,
7865                                       R, TInfo, isExplicit, isInline,
7866                                       /*isImplicitlyDeclared=*/false,
7867                                       isConstexpr);
7868 
7869   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7870     // This is a C++ destructor declaration.
7871     if (DC->isRecord()) {
7872       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7873       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7874       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7875                                         SemaRef.Context, Record,
7876                                         D.getLocStart(),
7877                                         NameInfo, R, TInfo, isInline,
7878                                         /*isImplicitlyDeclared=*/false);
7879 
7880       // If the class is complete, then we now create the implicit exception
7881       // specification. If the class is incomplete or dependent, we can't do
7882       // it yet.
7883       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7884           Record->getDefinition() && !Record->isBeingDefined() &&
7885           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7886         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7887       }
7888 
7889       IsVirtualOkay = true;
7890       return NewDD;
7891 
7892     } else {
7893       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7894       D.setInvalidType();
7895 
7896       // Create a FunctionDecl to satisfy the function definition parsing
7897       // code path.
7898       return FunctionDecl::Create(SemaRef.Context, DC,
7899                                   D.getLocStart(),
7900                                   D.getIdentifierLoc(), Name, R, TInfo,
7901                                   SC, isInline,
7902                                   /*hasPrototype=*/true, isConstexpr);
7903     }
7904 
7905   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7906     if (!DC->isRecord()) {
7907       SemaRef.Diag(D.getIdentifierLoc(),
7908            diag::err_conv_function_not_member);
7909       return nullptr;
7910     }
7911 
7912     SemaRef.CheckConversionDeclarator(D, R, SC);
7913     IsVirtualOkay = true;
7914     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7915                                      D.getLocStart(), NameInfo,
7916                                      R, TInfo, isInline, isExplicit,
7917                                      isConstexpr, SourceLocation());
7918 
7919   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7920     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7921 
7922     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7923                                          isExplicit, NameInfo, R, TInfo,
7924                                          D.getLocEnd());
7925   } else if (DC->isRecord()) {
7926     // If the name of the function is the same as the name of the record,
7927     // then this must be an invalid constructor that has a return type.
7928     // (The parser checks for a return type and makes the declarator a
7929     // constructor if it has no return type).
7930     if (Name.getAsIdentifierInfo() &&
7931         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7932       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7933         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7934         << SourceRange(D.getIdentifierLoc());
7935       return nullptr;
7936     }
7937 
7938     // This is a C++ method declaration.
7939     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7940                                                cast<CXXRecordDecl>(DC),
7941                                                D.getLocStart(), NameInfo, R,
7942                                                TInfo, SC, isInline,
7943                                                isConstexpr, SourceLocation());
7944     IsVirtualOkay = !Ret->isStatic();
7945     return Ret;
7946   } else {
7947     bool isFriend =
7948         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7949     if (!isFriend && SemaRef.CurContext->isRecord())
7950       return nullptr;
7951 
7952     // Determine whether the function was written with a
7953     // prototype. This true when:
7954     //   - we're in C++ (where every function has a prototype),
7955     return FunctionDecl::Create(SemaRef.Context, DC,
7956                                 D.getLocStart(),
7957                                 NameInfo, R, TInfo, SC, isInline,
7958                                 true/*HasPrototype*/, isConstexpr);
7959   }
7960 }
7961 
7962 enum OpenCLParamType {
7963   ValidKernelParam,
7964   PtrPtrKernelParam,
7965   PtrKernelParam,
7966   InvalidAddrSpacePtrKernelParam,
7967   InvalidKernelParam,
7968   RecordKernelParam
7969 };
7970 
7971 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7972   if (PT->isPointerType()) {
7973     QualType PointeeType = PT->getPointeeType();
7974     if (PointeeType->isPointerType())
7975       return PtrPtrKernelParam;
7976     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7977         PointeeType.getAddressSpace() == 0)
7978       return InvalidAddrSpacePtrKernelParam;
7979     return PtrKernelParam;
7980   }
7981 
7982   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7983   // be used as builtin types.
7984 
7985   if (PT->isImageType())
7986     return PtrKernelParam;
7987 
7988   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7989     return InvalidKernelParam;
7990 
7991   // OpenCL extension spec v1.2 s9.5:
7992   // This extension adds support for half scalar and vector types as built-in
7993   // types that can be used for arithmetic operations, conversions etc.
7994   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7995     return InvalidKernelParam;
7996 
7997   if (PT->isRecordType())
7998     return RecordKernelParam;
7999 
8000   return ValidKernelParam;
8001 }
8002 
8003 static void checkIsValidOpenCLKernelParameter(
8004   Sema &S,
8005   Declarator &D,
8006   ParmVarDecl *Param,
8007   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8008   QualType PT = Param->getType();
8009 
8010   // Cache the valid types we encounter to avoid rechecking structs that are
8011   // used again
8012   if (ValidTypes.count(PT.getTypePtr()))
8013     return;
8014 
8015   switch (getOpenCLKernelParameterType(S, PT)) {
8016   case PtrPtrKernelParam:
8017     // OpenCL v1.2 s6.9.a:
8018     // A kernel function argument cannot be declared as a
8019     // pointer to a pointer type.
8020     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8021     D.setInvalidType();
8022     return;
8023 
8024   case InvalidAddrSpacePtrKernelParam:
8025     // OpenCL v1.0 s6.5:
8026     // __kernel function arguments declared to be a pointer of a type can point
8027     // to one of the following address spaces only : __global, __local or
8028     // __constant.
8029     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8030     D.setInvalidType();
8031     return;
8032 
8033     // OpenCL v1.2 s6.9.k:
8034     // Arguments to kernel functions in a program cannot be declared with the
8035     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8036     // uintptr_t or a struct and/or union that contain fields declared to be
8037     // one of these built-in scalar types.
8038 
8039   case InvalidKernelParam:
8040     // OpenCL v1.2 s6.8 n:
8041     // A kernel function argument cannot be declared
8042     // of event_t type.
8043     // Do not diagnose half type since it is diagnosed as invalid argument
8044     // type for any function elsewhere.
8045     if (!PT->isHalfType())
8046       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8047     D.setInvalidType();
8048     return;
8049 
8050   case PtrKernelParam:
8051   case ValidKernelParam:
8052     ValidTypes.insert(PT.getTypePtr());
8053     return;
8054 
8055   case RecordKernelParam:
8056     break;
8057   }
8058 
8059   // Track nested structs we will inspect
8060   SmallVector<const Decl *, 4> VisitStack;
8061 
8062   // Track where we are in the nested structs. Items will migrate from
8063   // VisitStack to HistoryStack as we do the DFS for bad field.
8064   SmallVector<const FieldDecl *, 4> HistoryStack;
8065   HistoryStack.push_back(nullptr);
8066 
8067   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8068   VisitStack.push_back(PD);
8069 
8070   assert(VisitStack.back() && "First decl null?");
8071 
8072   do {
8073     const Decl *Next = VisitStack.pop_back_val();
8074     if (!Next) {
8075       assert(!HistoryStack.empty());
8076       // Found a marker, we have gone up a level
8077       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8078         ValidTypes.insert(Hist->getType().getTypePtr());
8079 
8080       continue;
8081     }
8082 
8083     // Adds everything except the original parameter declaration (which is not a
8084     // field itself) to the history stack.
8085     const RecordDecl *RD;
8086     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8087       HistoryStack.push_back(Field);
8088       RD = Field->getType()->castAs<RecordType>()->getDecl();
8089     } else {
8090       RD = cast<RecordDecl>(Next);
8091     }
8092 
8093     // Add a null marker so we know when we've gone back up a level
8094     VisitStack.push_back(nullptr);
8095 
8096     for (const auto *FD : RD->fields()) {
8097       QualType QT = FD->getType();
8098 
8099       if (ValidTypes.count(QT.getTypePtr()))
8100         continue;
8101 
8102       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8103       if (ParamType == ValidKernelParam)
8104         continue;
8105 
8106       if (ParamType == RecordKernelParam) {
8107         VisitStack.push_back(FD);
8108         continue;
8109       }
8110 
8111       // OpenCL v1.2 s6.9.p:
8112       // Arguments to kernel functions that are declared to be a struct or union
8113       // do not allow OpenCL objects to be passed as elements of the struct or
8114       // union.
8115       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8116           ParamType == InvalidAddrSpacePtrKernelParam) {
8117         S.Diag(Param->getLocation(),
8118                diag::err_record_with_pointers_kernel_param)
8119           << PT->isUnionType()
8120           << PT;
8121       } else {
8122         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8123       }
8124 
8125       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8126         << PD->getDeclName();
8127 
8128       // We have an error, now let's go back up through history and show where
8129       // the offending field came from
8130       for (ArrayRef<const FieldDecl *>::const_iterator
8131                I = HistoryStack.begin() + 1,
8132                E = HistoryStack.end();
8133            I != E; ++I) {
8134         const FieldDecl *OuterField = *I;
8135         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8136           << OuterField->getType();
8137       }
8138 
8139       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8140         << QT->isPointerType()
8141         << QT;
8142       D.setInvalidType();
8143       return;
8144     }
8145   } while (!VisitStack.empty());
8146 }
8147 
8148 /// Find the DeclContext in which a tag is implicitly declared if we see an
8149 /// elaborated type specifier in the specified context, and lookup finds
8150 /// nothing.
8151 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8152   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8153     DC = DC->getParent();
8154   return DC;
8155 }
8156 
8157 /// Find the Scope in which a tag is implicitly declared if we see an
8158 /// elaborated type specifier in the specified context, and lookup finds
8159 /// nothing.
8160 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8161   while (S->isClassScope() ||
8162          (LangOpts.CPlusPlus &&
8163           S->isFunctionPrototypeScope()) ||
8164          ((S->getFlags() & Scope::DeclScope) == 0) ||
8165          (S->getEntity() && S->getEntity()->isTransparentContext()))
8166     S = S->getParent();
8167   return S;
8168 }
8169 
8170 NamedDecl*
8171 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8172                               TypeSourceInfo *TInfo, LookupResult &Previous,
8173                               MultiTemplateParamsArg TemplateParamLists,
8174                               bool &AddToScope) {
8175   QualType R = TInfo->getType();
8176 
8177   assert(R.getTypePtr()->isFunctionType());
8178 
8179   // TODO: consider using NameInfo for diagnostic.
8180   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8181   DeclarationName Name = NameInfo.getName();
8182   StorageClass SC = getFunctionStorageClass(*this, D);
8183 
8184   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8185     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8186          diag::err_invalid_thread)
8187       << DeclSpec::getSpecifierName(TSCS);
8188 
8189   if (D.isFirstDeclarationOfMember())
8190     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8191                            D.getIdentifierLoc());
8192 
8193   bool isFriend = false;
8194   FunctionTemplateDecl *FunctionTemplate = nullptr;
8195   bool isMemberSpecialization = false;
8196   bool isFunctionTemplateSpecialization = false;
8197 
8198   bool isDependentClassScopeExplicitSpecialization = false;
8199   bool HasExplicitTemplateArgs = false;
8200   TemplateArgumentListInfo TemplateArgs;
8201 
8202   bool isVirtualOkay = false;
8203 
8204   DeclContext *OriginalDC = DC;
8205   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8206 
8207   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8208                                               isVirtualOkay);
8209   if (!NewFD) return nullptr;
8210 
8211   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8212     NewFD->setTopLevelDeclInObjCContainer();
8213 
8214   // Set the lexical context. If this is a function-scope declaration, or has a
8215   // C++ scope specifier, or is the object of a friend declaration, the lexical
8216   // context will be different from the semantic context.
8217   NewFD->setLexicalDeclContext(CurContext);
8218 
8219   if (IsLocalExternDecl)
8220     NewFD->setLocalExternDecl();
8221 
8222   if (getLangOpts().CPlusPlus) {
8223     bool isInline = D.getDeclSpec().isInlineSpecified();
8224     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8225     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8226     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8227     bool isConcept = D.getDeclSpec().isConceptSpecified();
8228     isFriend = D.getDeclSpec().isFriendSpecified();
8229     if (isFriend && !isInline && D.isFunctionDefinition()) {
8230       // C++ [class.friend]p5
8231       //   A function can be defined in a friend declaration of a
8232       //   class . . . . Such a function is implicitly inline.
8233       NewFD->setImplicitlyInline();
8234     }
8235 
8236     // If this is a method defined in an __interface, and is not a constructor
8237     // or an overloaded operator, then set the pure flag (isVirtual will already
8238     // return true).
8239     if (const CXXRecordDecl *Parent =
8240           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8241       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8242         NewFD->setPure(true);
8243 
8244       // C++ [class.union]p2
8245       //   A union can have member functions, but not virtual functions.
8246       if (isVirtual && Parent->isUnion())
8247         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8248     }
8249 
8250     SetNestedNameSpecifier(NewFD, D);
8251     isMemberSpecialization = false;
8252     isFunctionTemplateSpecialization = false;
8253     if (D.isInvalidType())
8254       NewFD->setInvalidDecl();
8255 
8256     // Match up the template parameter lists with the scope specifier, then
8257     // determine whether we have a template or a template specialization.
8258     bool Invalid = false;
8259     if (TemplateParameterList *TemplateParams =
8260             MatchTemplateParametersToScopeSpecifier(
8261                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8262                 D.getCXXScopeSpec(),
8263                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8264                     ? D.getName().TemplateId
8265                     : nullptr,
8266                 TemplateParamLists, isFriend, isMemberSpecialization,
8267                 Invalid)) {
8268       if (TemplateParams->size() > 0) {
8269         // This is a function template
8270 
8271         // Check that we can declare a template here.
8272         if (CheckTemplateDeclScope(S, TemplateParams))
8273           NewFD->setInvalidDecl();
8274 
8275         // A destructor cannot be a template.
8276         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8277           Diag(NewFD->getLocation(), diag::err_destructor_template);
8278           NewFD->setInvalidDecl();
8279         }
8280 
8281         // If we're adding a template to a dependent context, we may need to
8282         // rebuilding some of the types used within the template parameter list,
8283         // now that we know what the current instantiation is.
8284         if (DC->isDependentContext()) {
8285           ContextRAII SavedContext(*this, DC);
8286           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8287             Invalid = true;
8288         }
8289 
8290         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8291                                                         NewFD->getLocation(),
8292                                                         Name, TemplateParams,
8293                                                         NewFD);
8294         FunctionTemplate->setLexicalDeclContext(CurContext);
8295         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8296 
8297         // For source fidelity, store the other template param lists.
8298         if (TemplateParamLists.size() > 1) {
8299           NewFD->setTemplateParameterListsInfo(Context,
8300                                                TemplateParamLists.drop_back(1));
8301         }
8302       } else {
8303         // This is a function template specialization.
8304         isFunctionTemplateSpecialization = true;
8305         // For source fidelity, store all the template param lists.
8306         if (TemplateParamLists.size() > 0)
8307           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8308 
8309         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8310         if (isFriend) {
8311           // We want to remove the "template<>", found here.
8312           SourceRange RemoveRange = TemplateParams->getSourceRange();
8313 
8314           // If we remove the template<> and the name is not a
8315           // template-id, we're actually silently creating a problem:
8316           // the friend declaration will refer to an untemplated decl,
8317           // and clearly the user wants a template specialization.  So
8318           // we need to insert '<>' after the name.
8319           SourceLocation InsertLoc;
8320           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8321             InsertLoc = D.getName().getSourceRange().getEnd();
8322             InsertLoc = getLocForEndOfToken(InsertLoc);
8323           }
8324 
8325           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8326             << Name << RemoveRange
8327             << FixItHint::CreateRemoval(RemoveRange)
8328             << FixItHint::CreateInsertion(InsertLoc, "<>");
8329         }
8330       }
8331     }
8332     else {
8333       // All template param lists were matched against the scope specifier:
8334       // this is NOT (an explicit specialization of) a template.
8335       if (TemplateParamLists.size() > 0)
8336         // For source fidelity, store all the template param lists.
8337         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8338     }
8339 
8340     if (Invalid) {
8341       NewFD->setInvalidDecl();
8342       if (FunctionTemplate)
8343         FunctionTemplate->setInvalidDecl();
8344     }
8345 
8346     // C++ [dcl.fct.spec]p5:
8347     //   The virtual specifier shall only be used in declarations of
8348     //   nonstatic class member functions that appear within a
8349     //   member-specification of a class declaration; see 10.3.
8350     //
8351     if (isVirtual && !NewFD->isInvalidDecl()) {
8352       if (!isVirtualOkay) {
8353         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8354              diag::err_virtual_non_function);
8355       } else if (!CurContext->isRecord()) {
8356         // 'virtual' was specified outside of the class.
8357         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8358              diag::err_virtual_out_of_class)
8359           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8360       } else if (NewFD->getDescribedFunctionTemplate()) {
8361         // C++ [temp.mem]p3:
8362         //  A member function template shall not be virtual.
8363         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8364              diag::err_virtual_member_function_template)
8365           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8366       } else {
8367         // Okay: Add virtual to the method.
8368         NewFD->setVirtualAsWritten(true);
8369       }
8370 
8371       if (getLangOpts().CPlusPlus14 &&
8372           NewFD->getReturnType()->isUndeducedType())
8373         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8374     }
8375 
8376     if (getLangOpts().CPlusPlus14 &&
8377         (NewFD->isDependentContext() ||
8378          (isFriend && CurContext->isDependentContext())) &&
8379         NewFD->getReturnType()->isUndeducedType()) {
8380       // If the function template is referenced directly (for instance, as a
8381       // member of the current instantiation), pretend it has a dependent type.
8382       // This is not really justified by the standard, but is the only sane
8383       // thing to do.
8384       // FIXME: For a friend function, we have not marked the function as being
8385       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8386       const FunctionProtoType *FPT =
8387           NewFD->getType()->castAs<FunctionProtoType>();
8388       QualType Result =
8389           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8390       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8391                                              FPT->getExtProtoInfo()));
8392     }
8393 
8394     // C++ [dcl.fct.spec]p3:
8395     //  The inline specifier shall not appear on a block scope function
8396     //  declaration.
8397     if (isInline && !NewFD->isInvalidDecl()) {
8398       if (CurContext->isFunctionOrMethod()) {
8399         // 'inline' is not allowed on block scope function declaration.
8400         Diag(D.getDeclSpec().getInlineSpecLoc(),
8401              diag::err_inline_declaration_block_scope) << Name
8402           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8403       }
8404     }
8405 
8406     // C++ [dcl.fct.spec]p6:
8407     //  The explicit specifier shall be used only in the declaration of a
8408     //  constructor or conversion function within its class definition;
8409     //  see 12.3.1 and 12.3.2.
8410     if (isExplicit && !NewFD->isInvalidDecl() &&
8411         !isa<CXXDeductionGuideDecl>(NewFD)) {
8412       if (!CurContext->isRecord()) {
8413         // 'explicit' was specified outside of the class.
8414         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8415              diag::err_explicit_out_of_class)
8416           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8417       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8418                  !isa<CXXConversionDecl>(NewFD)) {
8419         // 'explicit' was specified on a function that wasn't a constructor
8420         // or conversion function.
8421         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8422              diag::err_explicit_non_ctor_or_conv_function)
8423           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8424       }
8425     }
8426 
8427     if (isConstexpr) {
8428       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8429       // are implicitly inline.
8430       NewFD->setImplicitlyInline();
8431 
8432       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8433       // be either constructors or to return a literal type. Therefore,
8434       // destructors cannot be declared constexpr.
8435       if (isa<CXXDestructorDecl>(NewFD))
8436         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8437     }
8438 
8439     if (isConcept) {
8440       // This is a function concept.
8441       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8442         FTD->setConcept();
8443 
8444       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8445       // applied only to the definition of a function template [...]
8446       if (!D.isFunctionDefinition()) {
8447         Diag(D.getDeclSpec().getConceptSpecLoc(),
8448              diag::err_function_concept_not_defined);
8449         NewFD->setInvalidDecl();
8450       }
8451 
8452       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8453       // have no exception-specification and is treated as if it were specified
8454       // with noexcept(true) (15.4). [...]
8455       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8456         if (FPT->hasExceptionSpec()) {
8457           SourceRange Range;
8458           if (D.isFunctionDeclarator())
8459             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8460           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8461               << FixItHint::CreateRemoval(Range);
8462           NewFD->setInvalidDecl();
8463         } else {
8464           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8465         }
8466 
8467         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8468         // following restrictions:
8469         // - The declared return type shall have the type bool.
8470         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8471           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8472           NewFD->setInvalidDecl();
8473         }
8474 
8475         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8476         // following restrictions:
8477         // - The declaration's parameter list shall be equivalent to an empty
8478         //   parameter list.
8479         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8480           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8481       }
8482 
8483       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8484       // implicity defined to be a constexpr declaration (implicitly inline)
8485       NewFD->setImplicitlyInline();
8486 
8487       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8488       // be declared with the thread_local, inline, friend, or constexpr
8489       // specifiers, [...]
8490       if (isInline) {
8491         Diag(D.getDeclSpec().getInlineSpecLoc(),
8492              diag::err_concept_decl_invalid_specifiers)
8493             << 1 << 1;
8494         NewFD->setInvalidDecl(true);
8495       }
8496 
8497       if (isFriend) {
8498         Diag(D.getDeclSpec().getFriendSpecLoc(),
8499              diag::err_concept_decl_invalid_specifiers)
8500             << 1 << 2;
8501         NewFD->setInvalidDecl(true);
8502       }
8503 
8504       if (isConstexpr) {
8505         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8506              diag::err_concept_decl_invalid_specifiers)
8507             << 1 << 3;
8508         NewFD->setInvalidDecl(true);
8509       }
8510 
8511       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8512       // applied only to the definition of a function template or variable
8513       // template, declared in namespace scope.
8514       if (isFunctionTemplateSpecialization) {
8515         Diag(D.getDeclSpec().getConceptSpecLoc(),
8516              diag::err_concept_specified_specialization) << 1;
8517         NewFD->setInvalidDecl(true);
8518         return NewFD;
8519       }
8520     }
8521 
8522     // If __module_private__ was specified, mark the function accordingly.
8523     if (D.getDeclSpec().isModulePrivateSpecified()) {
8524       if (isFunctionTemplateSpecialization) {
8525         SourceLocation ModulePrivateLoc
8526           = D.getDeclSpec().getModulePrivateSpecLoc();
8527         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8528           << 0
8529           << FixItHint::CreateRemoval(ModulePrivateLoc);
8530       } else {
8531         NewFD->setModulePrivate();
8532         if (FunctionTemplate)
8533           FunctionTemplate->setModulePrivate();
8534       }
8535     }
8536 
8537     if (isFriend) {
8538       if (FunctionTemplate) {
8539         FunctionTemplate->setObjectOfFriendDecl();
8540         FunctionTemplate->setAccess(AS_public);
8541       }
8542       NewFD->setObjectOfFriendDecl();
8543       NewFD->setAccess(AS_public);
8544     }
8545 
8546     // If a function is defined as defaulted or deleted, mark it as such now.
8547     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8548     // definition kind to FDK_Definition.
8549     switch (D.getFunctionDefinitionKind()) {
8550       case FDK_Declaration:
8551       case FDK_Definition:
8552         break;
8553 
8554       case FDK_Defaulted:
8555         NewFD->setDefaulted();
8556         break;
8557 
8558       case FDK_Deleted:
8559         NewFD->setDeletedAsWritten();
8560         break;
8561     }
8562 
8563     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8564         D.isFunctionDefinition()) {
8565       // C++ [class.mfct]p2:
8566       //   A member function may be defined (8.4) in its class definition, in
8567       //   which case it is an inline member function (7.1.2)
8568       NewFD->setImplicitlyInline();
8569     }
8570 
8571     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8572         !CurContext->isRecord()) {
8573       // C++ [class.static]p1:
8574       //   A data or function member of a class may be declared static
8575       //   in a class definition, in which case it is a static member of
8576       //   the class.
8577 
8578       // Complain about the 'static' specifier if it's on an out-of-line
8579       // member function definition.
8580       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8581            diag::err_static_out_of_line)
8582         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8583     }
8584 
8585     // C++11 [except.spec]p15:
8586     //   A deallocation function with no exception-specification is treated
8587     //   as if it were specified with noexcept(true).
8588     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8589     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8590          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8591         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8592       NewFD->setType(Context.getFunctionType(
8593           FPT->getReturnType(), FPT->getParamTypes(),
8594           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8595   }
8596 
8597   // Filter out previous declarations that don't match the scope.
8598   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8599                        D.getCXXScopeSpec().isNotEmpty() ||
8600                        isMemberSpecialization ||
8601                        isFunctionTemplateSpecialization);
8602 
8603   // Handle GNU asm-label extension (encoded as an attribute).
8604   if (Expr *E = (Expr*) D.getAsmLabel()) {
8605     // The parser guarantees this is a string.
8606     StringLiteral *SE = cast<StringLiteral>(E);
8607     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8608                                                 SE->getString(), 0));
8609   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8610     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8611       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8612     if (I != ExtnameUndeclaredIdentifiers.end()) {
8613       if (isDeclExternC(NewFD)) {
8614         NewFD->addAttr(I->second);
8615         ExtnameUndeclaredIdentifiers.erase(I);
8616       } else
8617         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8618             << /*Variable*/0 << NewFD;
8619     }
8620   }
8621 
8622   // Copy the parameter declarations from the declarator D to the function
8623   // declaration NewFD, if they are available.  First scavenge them into Params.
8624   SmallVector<ParmVarDecl*, 16> Params;
8625   unsigned FTIIdx;
8626   if (D.isFunctionDeclarator(FTIIdx)) {
8627     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8628 
8629     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8630     // function that takes no arguments, not a function that takes a
8631     // single void argument.
8632     // We let through "const void" here because Sema::GetTypeForDeclarator
8633     // already checks for that case.
8634     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8635       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8636         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8637         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8638         Param->setDeclContext(NewFD);
8639         Params.push_back(Param);
8640 
8641         if (Param->isInvalidDecl())
8642           NewFD->setInvalidDecl();
8643       }
8644     }
8645 
8646     if (!getLangOpts().CPlusPlus) {
8647       // In C, find all the tag declarations from the prototype and move them
8648       // into the function DeclContext. Remove them from the surrounding tag
8649       // injection context of the function, which is typically but not always
8650       // the TU.
8651       DeclContext *PrototypeTagContext =
8652           getTagInjectionContext(NewFD->getLexicalDeclContext());
8653       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8654         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8655 
8656         // We don't want to reparent enumerators. Look at their parent enum
8657         // instead.
8658         if (!TD) {
8659           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8660             TD = cast<EnumDecl>(ECD->getDeclContext());
8661         }
8662         if (!TD)
8663           continue;
8664         DeclContext *TagDC = TD->getLexicalDeclContext();
8665         if (!TagDC->containsDecl(TD))
8666           continue;
8667         TagDC->removeDecl(TD);
8668         TD->setDeclContext(NewFD);
8669         NewFD->addDecl(TD);
8670 
8671         // Preserve the lexical DeclContext if it is not the surrounding tag
8672         // injection context of the FD. In this example, the semantic context of
8673         // E will be f and the lexical context will be S, while both the
8674         // semantic and lexical contexts of S will be f:
8675         //   void f(struct S { enum E { a } f; } s);
8676         if (TagDC != PrototypeTagContext)
8677           TD->setLexicalDeclContext(TagDC);
8678       }
8679     }
8680   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8681     // When we're declaring a function with a typedef, typeof, etc as in the
8682     // following example, we'll need to synthesize (unnamed)
8683     // parameters for use in the declaration.
8684     //
8685     // @code
8686     // typedef void fn(int);
8687     // fn f;
8688     // @endcode
8689 
8690     // Synthesize a parameter for each argument type.
8691     for (const auto &AI : FT->param_types()) {
8692       ParmVarDecl *Param =
8693           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8694       Param->setScopeInfo(0, Params.size());
8695       Params.push_back(Param);
8696     }
8697   } else {
8698     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8699            "Should not need args for typedef of non-prototype fn");
8700   }
8701 
8702   // Finally, we know we have the right number of parameters, install them.
8703   NewFD->setParams(Params);
8704 
8705   if (D.getDeclSpec().isNoreturnSpecified())
8706     NewFD->addAttr(
8707         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8708                                        Context, 0));
8709 
8710   // Functions returning a variably modified type violate C99 6.7.5.2p2
8711   // because all functions have linkage.
8712   if (!NewFD->isInvalidDecl() &&
8713       NewFD->getReturnType()->isVariablyModifiedType()) {
8714     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8715     NewFD->setInvalidDecl();
8716   }
8717 
8718   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8719   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8720       !NewFD->hasAttr<SectionAttr>()) {
8721     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8722                                                  PragmaClangTextSection.SectionName,
8723                                                  PragmaClangTextSection.PragmaLocation));
8724   }
8725 
8726   // Apply an implicit SectionAttr if #pragma code_seg is active.
8727   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8728       !NewFD->hasAttr<SectionAttr>()) {
8729     NewFD->addAttr(
8730         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8731                                     CodeSegStack.CurrentValue->getString(),
8732                                     CodeSegStack.CurrentPragmaLocation));
8733     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8734                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8735                          ASTContext::PSF_Read,
8736                      NewFD))
8737       NewFD->dropAttr<SectionAttr>();
8738   }
8739 
8740   // Handle attributes.
8741   ProcessDeclAttributes(S, NewFD, D);
8742 
8743   if (getLangOpts().OpenCL) {
8744     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8745     // type declaration will generate a compilation error.
8746     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8747     if (AddressSpace == LangAS::opencl_local ||
8748         AddressSpace == LangAS::opencl_global ||
8749         AddressSpace == LangAS::opencl_constant) {
8750       Diag(NewFD->getLocation(),
8751            diag::err_opencl_return_value_with_address_space);
8752       NewFD->setInvalidDecl();
8753     }
8754   }
8755 
8756   if (!getLangOpts().CPlusPlus) {
8757     // Perform semantic checking on the function declaration.
8758     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8759       CheckMain(NewFD, D.getDeclSpec());
8760 
8761     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8762       CheckMSVCRTEntryPoint(NewFD);
8763 
8764     if (!NewFD->isInvalidDecl())
8765       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8766                                                   isMemberSpecialization));
8767     else if (!Previous.empty())
8768       // Recover gracefully from an invalid redeclaration.
8769       D.setRedeclaration(true);
8770     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8771             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8772            "previous declaration set still overloaded");
8773 
8774     // Diagnose no-prototype function declarations with calling conventions that
8775     // don't support variadic calls. Only do this in C and do it after merging
8776     // possibly prototyped redeclarations.
8777     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8778     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8779       CallingConv CC = FT->getExtInfo().getCC();
8780       if (!supportsVariadicCall(CC)) {
8781         // Windows system headers sometimes accidentally use stdcall without
8782         // (void) parameters, so we relax this to a warning.
8783         int DiagID =
8784             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8785         Diag(NewFD->getLocation(), DiagID)
8786             << FunctionType::getNameForCallConv(CC);
8787       }
8788     }
8789   } else {
8790     // C++11 [replacement.functions]p3:
8791     //  The program's definitions shall not be specified as inline.
8792     //
8793     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8794     //
8795     // Suppress the diagnostic if the function is __attribute__((used)), since
8796     // that forces an external definition to be emitted.
8797     if (D.getDeclSpec().isInlineSpecified() &&
8798         NewFD->isReplaceableGlobalAllocationFunction() &&
8799         !NewFD->hasAttr<UsedAttr>())
8800       Diag(D.getDeclSpec().getInlineSpecLoc(),
8801            diag::ext_operator_new_delete_declared_inline)
8802         << NewFD->getDeclName();
8803 
8804     // If the declarator is a template-id, translate the parser's template
8805     // argument list into our AST format.
8806     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8807       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8808       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8809       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8810       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8811                                          TemplateId->NumArgs);
8812       translateTemplateArguments(TemplateArgsPtr,
8813                                  TemplateArgs);
8814 
8815       HasExplicitTemplateArgs = true;
8816 
8817       if (NewFD->isInvalidDecl()) {
8818         HasExplicitTemplateArgs = false;
8819       } else if (FunctionTemplate) {
8820         // Function template with explicit template arguments.
8821         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8822           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8823 
8824         HasExplicitTemplateArgs = false;
8825       } else {
8826         assert((isFunctionTemplateSpecialization ||
8827                 D.getDeclSpec().isFriendSpecified()) &&
8828                "should have a 'template<>' for this decl");
8829         // "friend void foo<>(int);" is an implicit specialization decl.
8830         isFunctionTemplateSpecialization = true;
8831       }
8832     } else if (isFriend && isFunctionTemplateSpecialization) {
8833       // This combination is only possible in a recovery case;  the user
8834       // wrote something like:
8835       //   template <> friend void foo(int);
8836       // which we're recovering from as if the user had written:
8837       //   friend void foo<>(int);
8838       // Go ahead and fake up a template id.
8839       HasExplicitTemplateArgs = true;
8840       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8841       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8842     }
8843 
8844     // We do not add HD attributes to specializations here because
8845     // they may have different constexpr-ness compared to their
8846     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8847     // may end up with different effective targets. Instead, a
8848     // specialization inherits its target attributes from its template
8849     // in the CheckFunctionTemplateSpecialization() call below.
8850     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8851       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8852 
8853     // If it's a friend (and only if it's a friend), it's possible
8854     // that either the specialized function type or the specialized
8855     // template is dependent, and therefore matching will fail.  In
8856     // this case, don't check the specialization yet.
8857     bool InstantiationDependent = false;
8858     if (isFunctionTemplateSpecialization && isFriend &&
8859         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8860          TemplateSpecializationType::anyDependentTemplateArguments(
8861             TemplateArgs,
8862             InstantiationDependent))) {
8863       assert(HasExplicitTemplateArgs &&
8864              "friend function specialization without template args");
8865       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8866                                                        Previous))
8867         NewFD->setInvalidDecl();
8868     } else if (isFunctionTemplateSpecialization) {
8869       if (CurContext->isDependentContext() && CurContext->isRecord()
8870           && !isFriend) {
8871         isDependentClassScopeExplicitSpecialization = true;
8872         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8873           diag::ext_function_specialization_in_class :
8874           diag::err_function_specialization_in_class)
8875           << NewFD->getDeclName();
8876       } else if (CheckFunctionTemplateSpecialization(NewFD,
8877                                   (HasExplicitTemplateArgs ? &TemplateArgs
8878                                                            : nullptr),
8879                                                      Previous))
8880         NewFD->setInvalidDecl();
8881 
8882       // C++ [dcl.stc]p1:
8883       //   A storage-class-specifier shall not be specified in an explicit
8884       //   specialization (14.7.3)
8885       FunctionTemplateSpecializationInfo *Info =
8886           NewFD->getTemplateSpecializationInfo();
8887       if (Info && SC != SC_None) {
8888         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8889           Diag(NewFD->getLocation(),
8890                diag::err_explicit_specialization_inconsistent_storage_class)
8891             << SC
8892             << FixItHint::CreateRemoval(
8893                                       D.getDeclSpec().getStorageClassSpecLoc());
8894 
8895         else
8896           Diag(NewFD->getLocation(),
8897                diag::ext_explicit_specialization_storage_class)
8898             << FixItHint::CreateRemoval(
8899                                       D.getDeclSpec().getStorageClassSpecLoc());
8900       }
8901     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8902       if (CheckMemberSpecialization(NewFD, Previous))
8903           NewFD->setInvalidDecl();
8904     }
8905 
8906     // Perform semantic checking on the function declaration.
8907     if (!isDependentClassScopeExplicitSpecialization) {
8908       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8909         CheckMain(NewFD, D.getDeclSpec());
8910 
8911       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8912         CheckMSVCRTEntryPoint(NewFD);
8913 
8914       if (!NewFD->isInvalidDecl())
8915         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8916                                                     isMemberSpecialization));
8917       else if (!Previous.empty())
8918         // Recover gracefully from an invalid redeclaration.
8919         D.setRedeclaration(true);
8920     }
8921 
8922     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8923             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8924            "previous declaration set still overloaded");
8925 
8926     NamedDecl *PrincipalDecl = (FunctionTemplate
8927                                 ? cast<NamedDecl>(FunctionTemplate)
8928                                 : NewFD);
8929 
8930     if (isFriend && NewFD->getPreviousDecl()) {
8931       AccessSpecifier Access = AS_public;
8932       if (!NewFD->isInvalidDecl())
8933         Access = NewFD->getPreviousDecl()->getAccess();
8934 
8935       NewFD->setAccess(Access);
8936       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8937     }
8938 
8939     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8940         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8941       PrincipalDecl->setNonMemberOperator();
8942 
8943     // If we have a function template, check the template parameter
8944     // list. This will check and merge default template arguments.
8945     if (FunctionTemplate) {
8946       FunctionTemplateDecl *PrevTemplate =
8947                                      FunctionTemplate->getPreviousDecl();
8948       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8949                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8950                                     : nullptr,
8951                             D.getDeclSpec().isFriendSpecified()
8952                               ? (D.isFunctionDefinition()
8953                                    ? TPC_FriendFunctionTemplateDefinition
8954                                    : TPC_FriendFunctionTemplate)
8955                               : (D.getCXXScopeSpec().isSet() &&
8956                                  DC && DC->isRecord() &&
8957                                  DC->isDependentContext())
8958                                   ? TPC_ClassTemplateMember
8959                                   : TPC_FunctionTemplate);
8960     }
8961 
8962     if (NewFD->isInvalidDecl()) {
8963       // Ignore all the rest of this.
8964     } else if (!D.isRedeclaration()) {
8965       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8966                                        AddToScope };
8967       // Fake up an access specifier if it's supposed to be a class member.
8968       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8969         NewFD->setAccess(AS_public);
8970 
8971       // Qualified decls generally require a previous declaration.
8972       if (D.getCXXScopeSpec().isSet()) {
8973         // ...with the major exception of templated-scope or
8974         // dependent-scope friend declarations.
8975 
8976         // TODO: we currently also suppress this check in dependent
8977         // contexts because (1) the parameter depth will be off when
8978         // matching friend templates and (2) we might actually be
8979         // selecting a friend based on a dependent factor.  But there
8980         // are situations where these conditions don't apply and we
8981         // can actually do this check immediately.
8982         if (isFriend &&
8983             (TemplateParamLists.size() ||
8984              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8985              CurContext->isDependentContext())) {
8986           // ignore these
8987         } else {
8988           // The user tried to provide an out-of-line definition for a
8989           // function that is a member of a class or namespace, but there
8990           // was no such member function declared (C++ [class.mfct]p2,
8991           // C++ [namespace.memdef]p2). For example:
8992           //
8993           // class X {
8994           //   void f() const;
8995           // };
8996           //
8997           // void X::f() { } // ill-formed
8998           //
8999           // Complain about this problem, and attempt to suggest close
9000           // matches (e.g., those that differ only in cv-qualifiers and
9001           // whether the parameter types are references).
9002 
9003           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9004                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9005             AddToScope = ExtraArgs.AddToScope;
9006             return Result;
9007           }
9008         }
9009 
9010         // Unqualified local friend declarations are required to resolve
9011         // to something.
9012       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9013         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9014                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9015           AddToScope = ExtraArgs.AddToScope;
9016           return Result;
9017         }
9018       }
9019     } else if (!D.isFunctionDefinition() &&
9020                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9021                !isFriend && !isFunctionTemplateSpecialization &&
9022                !isMemberSpecialization) {
9023       // An out-of-line member function declaration must also be a
9024       // definition (C++ [class.mfct]p2).
9025       // Note that this is not the case for explicit specializations of
9026       // function templates or member functions of class templates, per
9027       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9028       // extension for compatibility with old SWIG code which likes to
9029       // generate them.
9030       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9031         << D.getCXXScopeSpec().getRange();
9032     }
9033   }
9034 
9035   ProcessPragmaWeak(S, NewFD);
9036   checkAttributesAfterMerging(*this, *NewFD);
9037 
9038   AddKnownFunctionAttributes(NewFD);
9039 
9040   if (NewFD->hasAttr<OverloadableAttr>() &&
9041       !NewFD->getType()->getAs<FunctionProtoType>()) {
9042     Diag(NewFD->getLocation(),
9043          diag::err_attribute_overloadable_no_prototype)
9044       << NewFD;
9045 
9046     // Turn this into a variadic function with no parameters.
9047     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9048     FunctionProtoType::ExtProtoInfo EPI(
9049         Context.getDefaultCallingConvention(true, false));
9050     EPI.Variadic = true;
9051     EPI.ExtInfo = FT->getExtInfo();
9052 
9053     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9054     NewFD->setType(R);
9055   }
9056 
9057   // If there's a #pragma GCC visibility in scope, and this isn't a class
9058   // member, set the visibility of this function.
9059   if (!DC->isRecord() && NewFD->isExternallyVisible())
9060     AddPushedVisibilityAttribute(NewFD);
9061 
9062   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9063   // marking the function.
9064   AddCFAuditedAttribute(NewFD);
9065 
9066   // If this is a function definition, check if we have to apply optnone due to
9067   // a pragma.
9068   if(D.isFunctionDefinition())
9069     AddRangeBasedOptnone(NewFD);
9070 
9071   // If this is the first declaration of an extern C variable, update
9072   // the map of such variables.
9073   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9074       isIncompleteDeclExternC(*this, NewFD))
9075     RegisterLocallyScopedExternCDecl(NewFD, S);
9076 
9077   // Set this FunctionDecl's range up to the right paren.
9078   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9079 
9080   if (D.isRedeclaration() && !Previous.empty()) {
9081     checkDLLAttributeRedeclaration(
9082         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9083         isMemberSpecialization || isFunctionTemplateSpecialization,
9084         D.isFunctionDefinition());
9085   }
9086 
9087   if (getLangOpts().CUDA) {
9088     IdentifierInfo *II = NewFD->getIdentifier();
9089     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9090         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9091       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9092         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9093 
9094       Context.setcudaConfigureCallDecl(NewFD);
9095     }
9096 
9097     // Variadic functions, other than a *declaration* of printf, are not allowed
9098     // in device-side CUDA code, unless someone passed
9099     // -fcuda-allow-variadic-functions.
9100     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9101         (NewFD->hasAttr<CUDADeviceAttr>() ||
9102          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9103         !(II && II->isStr("printf") && NewFD->isExternC() &&
9104           !D.isFunctionDefinition())) {
9105       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9106     }
9107   }
9108 
9109   MarkUnusedFileScopedDecl(NewFD);
9110 
9111   if (getLangOpts().CPlusPlus) {
9112     if (FunctionTemplate) {
9113       if (NewFD->isInvalidDecl())
9114         FunctionTemplate->setInvalidDecl();
9115       return FunctionTemplate;
9116     }
9117 
9118     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9119       CompleteMemberSpecialization(NewFD, Previous);
9120   }
9121 
9122   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9123     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9124     if ((getLangOpts().OpenCLVersion >= 120)
9125         && (SC == SC_Static)) {
9126       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9127       D.setInvalidType();
9128     }
9129 
9130     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9131     if (!NewFD->getReturnType()->isVoidType()) {
9132       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9133       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9134           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9135                                 : FixItHint());
9136       D.setInvalidType();
9137     }
9138 
9139     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9140     for (auto Param : NewFD->parameters())
9141       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9142   }
9143   for (const ParmVarDecl *Param : NewFD->parameters()) {
9144     QualType PT = Param->getType();
9145 
9146     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9147     // types.
9148     if (getLangOpts().OpenCLVersion >= 200) {
9149       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9150         QualType ElemTy = PipeTy->getElementType();
9151           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9152             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9153             D.setInvalidType();
9154           }
9155       }
9156     }
9157   }
9158 
9159   // Here we have an function template explicit specialization at class scope.
9160   // The actually specialization will be postponed to template instatiation
9161   // time via the ClassScopeFunctionSpecializationDecl node.
9162   if (isDependentClassScopeExplicitSpecialization) {
9163     ClassScopeFunctionSpecializationDecl *NewSpec =
9164                          ClassScopeFunctionSpecializationDecl::Create(
9165                                 Context, CurContext, SourceLocation(),
9166                                 cast<CXXMethodDecl>(NewFD),
9167                                 HasExplicitTemplateArgs, TemplateArgs);
9168     CurContext->addDecl(NewSpec);
9169     AddToScope = false;
9170   }
9171 
9172   return NewFD;
9173 }
9174 
9175 /// \brief Checks if the new declaration declared in dependent context must be
9176 /// put in the same redeclaration chain as the specified declaration.
9177 ///
9178 /// \param D Declaration that is checked.
9179 /// \param PrevDecl Previous declaration found with proper lookup method for the
9180 ///                 same declaration name.
9181 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9182 ///          belongs to.
9183 ///
9184 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9185   // Any declarations should be put into redeclaration chains except for
9186   // friend declaration in a dependent context that names a function in
9187   // namespace scope.
9188   //
9189   // This allows to compile code like:
9190   //
9191   //       void func();
9192   //       template<typename T> class C1 { friend void func() { } };
9193   //       template<typename T> class C2 { friend void func() { } };
9194   //
9195   // This code snippet is a valid code unless both templates are instantiated.
9196   return !(D->getLexicalDeclContext()->isDependentContext() &&
9197            D->getDeclContext()->isFileContext() &&
9198            D->getFriendObjectKind() != Decl::FOK_None);
9199 }
9200 
9201 /// \brief Perform semantic checking of a new function declaration.
9202 ///
9203 /// Performs semantic analysis of the new function declaration
9204 /// NewFD. This routine performs all semantic checking that does not
9205 /// require the actual declarator involved in the declaration, and is
9206 /// used both for the declaration of functions as they are parsed
9207 /// (called via ActOnDeclarator) and for the declaration of functions
9208 /// that have been instantiated via C++ template instantiation (called
9209 /// via InstantiateDecl).
9210 ///
9211 /// \param IsMemberSpecialization whether this new function declaration is
9212 /// a member specialization (that replaces any definition provided by the
9213 /// previous declaration).
9214 ///
9215 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9216 ///
9217 /// \returns true if the function declaration is a redeclaration.
9218 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9219                                     LookupResult &Previous,
9220                                     bool IsMemberSpecialization) {
9221   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9222          "Variably modified return types are not handled here");
9223 
9224   // Determine whether the type of this function should be merged with
9225   // a previous visible declaration. This never happens for functions in C++,
9226   // and always happens in C if the previous declaration was visible.
9227   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9228                                !Previous.isShadowed();
9229 
9230   bool Redeclaration = false;
9231   NamedDecl *OldDecl = nullptr;
9232   bool MayNeedOverloadableChecks = false;
9233 
9234   // Merge or overload the declaration with an existing declaration of
9235   // the same name, if appropriate.
9236   if (!Previous.empty()) {
9237     // Determine whether NewFD is an overload of PrevDecl or
9238     // a declaration that requires merging. If it's an overload,
9239     // there's no more work to do here; we'll just add the new
9240     // function to the scope.
9241     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9242       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9243       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9244         Redeclaration = true;
9245         OldDecl = Candidate;
9246       }
9247     } else {
9248       MayNeedOverloadableChecks = true;
9249       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9250                             /*NewIsUsingDecl*/ false)) {
9251       case Ovl_Match:
9252         Redeclaration = true;
9253         break;
9254 
9255       case Ovl_NonFunction:
9256         Redeclaration = true;
9257         break;
9258 
9259       case Ovl_Overload:
9260         Redeclaration = false;
9261         break;
9262       }
9263     }
9264   }
9265 
9266   // Check for a previous extern "C" declaration with this name.
9267   if (!Redeclaration &&
9268       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9269     if (!Previous.empty()) {
9270       // This is an extern "C" declaration with the same name as a previous
9271       // declaration, and thus redeclares that entity...
9272       Redeclaration = true;
9273       OldDecl = Previous.getFoundDecl();
9274       MergeTypeWithPrevious = false;
9275 
9276       // ... except in the presence of __attribute__((overloadable)).
9277       if (OldDecl->hasAttr<OverloadableAttr>() ||
9278           NewFD->hasAttr<OverloadableAttr>()) {
9279         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9280           MayNeedOverloadableChecks = true;
9281           Redeclaration = false;
9282           OldDecl = nullptr;
9283         }
9284       }
9285     }
9286   }
9287 
9288   // C++11 [dcl.constexpr]p8:
9289   //   A constexpr specifier for a non-static member function that is not
9290   //   a constructor declares that member function to be const.
9291   //
9292   // This needs to be delayed until we know whether this is an out-of-line
9293   // definition of a static member function.
9294   //
9295   // This rule is not present in C++1y, so we produce a backwards
9296   // compatibility warning whenever it happens in C++11.
9297   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9298   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9299       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9300       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9301     CXXMethodDecl *OldMD = nullptr;
9302     if (OldDecl)
9303       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9304     if (!OldMD || !OldMD->isStatic()) {
9305       const FunctionProtoType *FPT =
9306         MD->getType()->castAs<FunctionProtoType>();
9307       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9308       EPI.TypeQuals |= Qualifiers::Const;
9309       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9310                                           FPT->getParamTypes(), EPI));
9311 
9312       // Warn that we did this, if we're not performing template instantiation.
9313       // In that case, we'll have warned already when the template was defined.
9314       if (!inTemplateInstantiation()) {
9315         SourceLocation AddConstLoc;
9316         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9317                 .IgnoreParens().getAs<FunctionTypeLoc>())
9318           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9319 
9320         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9321           << FixItHint::CreateInsertion(AddConstLoc, " const");
9322       }
9323     }
9324   }
9325 
9326   if (Redeclaration) {
9327     // NewFD and OldDecl represent declarations that need to be
9328     // merged.
9329     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9330       NewFD->setInvalidDecl();
9331       return Redeclaration;
9332     }
9333 
9334     Previous.clear();
9335     Previous.addDecl(OldDecl);
9336 
9337     if (FunctionTemplateDecl *OldTemplateDecl
9338                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9339       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9340       FunctionTemplateDecl *NewTemplateDecl
9341         = NewFD->getDescribedFunctionTemplate();
9342       assert(NewTemplateDecl && "Template/non-template mismatch");
9343       if (CXXMethodDecl *Method
9344             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9345         Method->setAccess(OldTemplateDecl->getAccess());
9346         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9347       }
9348 
9349       // If this is an explicit specialization of a member that is a function
9350       // template, mark it as a member specialization.
9351       if (IsMemberSpecialization &&
9352           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9353         NewTemplateDecl->setMemberSpecialization();
9354         assert(OldTemplateDecl->isMemberSpecialization());
9355         // Explicit specializations of a member template do not inherit deleted
9356         // status from the parent member template that they are specializing.
9357         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9358           FunctionDecl *const OldTemplatedDecl =
9359               OldTemplateDecl->getTemplatedDecl();
9360           // FIXME: This assert will not hold in the presence of modules.
9361           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9362           // FIXME: We need an update record for this AST mutation.
9363           OldTemplatedDecl->setDeletedAsWritten(false);
9364         }
9365       }
9366 
9367     } else {
9368       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9369         // This needs to happen first so that 'inline' propagates.
9370         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9371         if (isa<CXXMethodDecl>(NewFD))
9372           NewFD->setAccess(OldDecl->getAccess());
9373       }
9374     }
9375   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9376              !NewFD->getAttr<OverloadableAttr>()) {
9377     assert((Previous.empty() ||
9378             llvm::any_of(Previous,
9379                          [](const NamedDecl *ND) {
9380                            return ND->hasAttr<OverloadableAttr>();
9381                          })) &&
9382            "Non-redecls shouldn't happen without overloadable present");
9383 
9384     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9385       const auto *FD = dyn_cast<FunctionDecl>(ND);
9386       return FD && !FD->hasAttr<OverloadableAttr>();
9387     });
9388 
9389     if (OtherUnmarkedIter != Previous.end()) {
9390       Diag(NewFD->getLocation(),
9391            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9392       Diag((*OtherUnmarkedIter)->getLocation(),
9393            diag::note_attribute_overloadable_prev_overload)
9394           << false;
9395 
9396       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9397     }
9398   }
9399 
9400   // Semantic checking for this function declaration (in isolation).
9401 
9402   if (getLangOpts().CPlusPlus) {
9403     // C++-specific checks.
9404     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9405       CheckConstructor(Constructor);
9406     } else if (CXXDestructorDecl *Destructor =
9407                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9408       CXXRecordDecl *Record = Destructor->getParent();
9409       QualType ClassType = Context.getTypeDeclType(Record);
9410 
9411       // FIXME: Shouldn't we be able to perform this check even when the class
9412       // type is dependent? Both gcc and edg can handle that.
9413       if (!ClassType->isDependentType()) {
9414         DeclarationName Name
9415           = Context.DeclarationNames.getCXXDestructorName(
9416                                         Context.getCanonicalType(ClassType));
9417         if (NewFD->getDeclName() != Name) {
9418           Diag(NewFD->getLocation(), diag::err_destructor_name);
9419           NewFD->setInvalidDecl();
9420           return Redeclaration;
9421         }
9422       }
9423     } else if (CXXConversionDecl *Conversion
9424                = dyn_cast<CXXConversionDecl>(NewFD)) {
9425       ActOnConversionDeclarator(Conversion);
9426     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9427       if (auto *TD = Guide->getDescribedFunctionTemplate())
9428         CheckDeductionGuideTemplate(TD);
9429 
9430       // A deduction guide is not on the list of entities that can be
9431       // explicitly specialized.
9432       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9433         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9434             << /*explicit specialization*/ 1;
9435     }
9436 
9437     // Find any virtual functions that this function overrides.
9438     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9439       if (!Method->isFunctionTemplateSpecialization() &&
9440           !Method->getDescribedFunctionTemplate() &&
9441           Method->isCanonicalDecl()) {
9442         if (AddOverriddenMethods(Method->getParent(), Method)) {
9443           // If the function was marked as "static", we have a problem.
9444           if (NewFD->getStorageClass() == SC_Static) {
9445             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9446           }
9447         }
9448       }
9449 
9450       if (Method->isStatic())
9451         checkThisInStaticMemberFunctionType(Method);
9452     }
9453 
9454     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9455     if (NewFD->isOverloadedOperator() &&
9456         CheckOverloadedOperatorDeclaration(NewFD)) {
9457       NewFD->setInvalidDecl();
9458       return Redeclaration;
9459     }
9460 
9461     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9462     if (NewFD->getLiteralIdentifier() &&
9463         CheckLiteralOperatorDeclaration(NewFD)) {
9464       NewFD->setInvalidDecl();
9465       return Redeclaration;
9466     }
9467 
9468     // In C++, check default arguments now that we have merged decls. Unless
9469     // the lexical context is the class, because in this case this is done
9470     // during delayed parsing anyway.
9471     if (!CurContext->isRecord())
9472       CheckCXXDefaultArguments(NewFD);
9473 
9474     // If this function declares a builtin function, check the type of this
9475     // declaration against the expected type for the builtin.
9476     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9477       ASTContext::GetBuiltinTypeError Error;
9478       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9479       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9480       // If the type of the builtin differs only in its exception
9481       // specification, that's OK.
9482       // FIXME: If the types do differ in this way, it would be better to
9483       // retain the 'noexcept' form of the type.
9484       if (!T.isNull() &&
9485           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9486                                                             NewFD->getType()))
9487         // The type of this function differs from the type of the builtin,
9488         // so forget about the builtin entirely.
9489         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9490     }
9491 
9492     // If this function is declared as being extern "C", then check to see if
9493     // the function returns a UDT (class, struct, or union type) that is not C
9494     // compatible, and if it does, warn the user.
9495     // But, issue any diagnostic on the first declaration only.
9496     if (Previous.empty() && NewFD->isExternC()) {
9497       QualType R = NewFD->getReturnType();
9498       if (R->isIncompleteType() && !R->isVoidType())
9499         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9500             << NewFD << R;
9501       else if (!R.isPODType(Context) && !R->isVoidType() &&
9502                !R->isObjCObjectPointerType())
9503         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9504     }
9505 
9506     // C++1z [dcl.fct]p6:
9507     //   [...] whether the function has a non-throwing exception-specification
9508     //   [is] part of the function type
9509     //
9510     // This results in an ABI break between C++14 and C++17 for functions whose
9511     // declared type includes an exception-specification in a parameter or
9512     // return type. (Exception specifications on the function itself are OK in
9513     // most cases, and exception specifications are not permitted in most other
9514     // contexts where they could make it into a mangling.)
9515     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9516       auto HasNoexcept = [&](QualType T) -> bool {
9517         // Strip off declarator chunks that could be between us and a function
9518         // type. We don't need to look far, exception specifications are very
9519         // restricted prior to C++17.
9520         if (auto *RT = T->getAs<ReferenceType>())
9521           T = RT->getPointeeType();
9522         else if (T->isAnyPointerType())
9523           T = T->getPointeeType();
9524         else if (auto *MPT = T->getAs<MemberPointerType>())
9525           T = MPT->getPointeeType();
9526         if (auto *FPT = T->getAs<FunctionProtoType>())
9527           if (FPT->isNothrow(Context))
9528             return true;
9529         return false;
9530       };
9531 
9532       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9533       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9534       for (QualType T : FPT->param_types())
9535         AnyNoexcept |= HasNoexcept(T);
9536       if (AnyNoexcept)
9537         Diag(NewFD->getLocation(),
9538              diag::warn_cxx17_compat_exception_spec_in_signature)
9539             << NewFD;
9540     }
9541 
9542     if (!Redeclaration && LangOpts.CUDA)
9543       checkCUDATargetOverload(NewFD, Previous);
9544   }
9545   return Redeclaration;
9546 }
9547 
9548 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9549   // C++11 [basic.start.main]p3:
9550   //   A program that [...] declares main to be inline, static or
9551   //   constexpr is ill-formed.
9552   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9553   //   appear in a declaration of main.
9554   // static main is not an error under C99, but we should warn about it.
9555   // We accept _Noreturn main as an extension.
9556   if (FD->getStorageClass() == SC_Static)
9557     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9558          ? diag::err_static_main : diag::warn_static_main)
9559       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9560   if (FD->isInlineSpecified())
9561     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9562       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9563   if (DS.isNoreturnSpecified()) {
9564     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9565     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9566     Diag(NoreturnLoc, diag::ext_noreturn_main);
9567     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9568       << FixItHint::CreateRemoval(NoreturnRange);
9569   }
9570   if (FD->isConstexpr()) {
9571     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9572       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9573     FD->setConstexpr(false);
9574   }
9575 
9576   if (getLangOpts().OpenCL) {
9577     Diag(FD->getLocation(), diag::err_opencl_no_main)
9578         << FD->hasAttr<OpenCLKernelAttr>();
9579     FD->setInvalidDecl();
9580     return;
9581   }
9582 
9583   QualType T = FD->getType();
9584   assert(T->isFunctionType() && "function decl is not of function type");
9585   const FunctionType* FT = T->castAs<FunctionType>();
9586 
9587   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9588     // In C with GNU extensions we allow main() to have non-integer return
9589     // type, but we should warn about the extension, and we disable the
9590     // implicit-return-zero rule.
9591 
9592     // GCC in C mode accepts qualified 'int'.
9593     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9594       FD->setHasImplicitReturnZero(true);
9595     else {
9596       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9597       SourceRange RTRange = FD->getReturnTypeSourceRange();
9598       if (RTRange.isValid())
9599         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9600             << FixItHint::CreateReplacement(RTRange, "int");
9601     }
9602   } else {
9603     // In C and C++, main magically returns 0 if you fall off the end;
9604     // set the flag which tells us that.
9605     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9606 
9607     // All the standards say that main() should return 'int'.
9608     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9609       FD->setHasImplicitReturnZero(true);
9610     else {
9611       // Otherwise, this is just a flat-out error.
9612       SourceRange RTRange = FD->getReturnTypeSourceRange();
9613       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9614           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9615                                 : FixItHint());
9616       FD->setInvalidDecl(true);
9617     }
9618   }
9619 
9620   // Treat protoless main() as nullary.
9621   if (isa<FunctionNoProtoType>(FT)) return;
9622 
9623   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9624   unsigned nparams = FTP->getNumParams();
9625   assert(FD->getNumParams() == nparams);
9626 
9627   bool HasExtraParameters = (nparams > 3);
9628 
9629   if (FTP->isVariadic()) {
9630     Diag(FD->getLocation(), diag::ext_variadic_main);
9631     // FIXME: if we had information about the location of the ellipsis, we
9632     // could add a FixIt hint to remove it as a parameter.
9633   }
9634 
9635   // Darwin passes an undocumented fourth argument of type char**.  If
9636   // other platforms start sprouting these, the logic below will start
9637   // getting shifty.
9638   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9639     HasExtraParameters = false;
9640 
9641   if (HasExtraParameters) {
9642     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9643     FD->setInvalidDecl(true);
9644     nparams = 3;
9645   }
9646 
9647   // FIXME: a lot of the following diagnostics would be improved
9648   // if we had some location information about types.
9649 
9650   QualType CharPP =
9651     Context.getPointerType(Context.getPointerType(Context.CharTy));
9652   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9653 
9654   for (unsigned i = 0; i < nparams; ++i) {
9655     QualType AT = FTP->getParamType(i);
9656 
9657     bool mismatch = true;
9658 
9659     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9660       mismatch = false;
9661     else if (Expected[i] == CharPP) {
9662       // As an extension, the following forms are okay:
9663       //   char const **
9664       //   char const * const *
9665       //   char * const *
9666 
9667       QualifierCollector qs;
9668       const PointerType* PT;
9669       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9670           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9671           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9672                               Context.CharTy)) {
9673         qs.removeConst();
9674         mismatch = !qs.empty();
9675       }
9676     }
9677 
9678     if (mismatch) {
9679       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9680       // TODO: suggest replacing given type with expected type
9681       FD->setInvalidDecl(true);
9682     }
9683   }
9684 
9685   if (nparams == 1 && !FD->isInvalidDecl()) {
9686     Diag(FD->getLocation(), diag::warn_main_one_arg);
9687   }
9688 
9689   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9690     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9691     FD->setInvalidDecl();
9692   }
9693 }
9694 
9695 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9696   QualType T = FD->getType();
9697   assert(T->isFunctionType() && "function decl is not of function type");
9698   const FunctionType *FT = T->castAs<FunctionType>();
9699 
9700   // Set an implicit return of 'zero' if the function can return some integral,
9701   // enumeration, pointer or nullptr type.
9702   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9703       FT->getReturnType()->isAnyPointerType() ||
9704       FT->getReturnType()->isNullPtrType())
9705     // DllMain is exempt because a return value of zero means it failed.
9706     if (FD->getName() != "DllMain")
9707       FD->setHasImplicitReturnZero(true);
9708 
9709   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9710     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9711     FD->setInvalidDecl();
9712   }
9713 }
9714 
9715 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9716   // FIXME: Need strict checking.  In C89, we need to check for
9717   // any assignment, increment, decrement, function-calls, or
9718   // commas outside of a sizeof.  In C99, it's the same list,
9719   // except that the aforementioned are allowed in unevaluated
9720   // expressions.  Everything else falls under the
9721   // "may accept other forms of constant expressions" exception.
9722   // (We never end up here for C++, so the constant expression
9723   // rules there don't matter.)
9724   const Expr *Culprit;
9725   if (Init->isConstantInitializer(Context, false, &Culprit))
9726     return false;
9727   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9728     << Culprit->getSourceRange();
9729   return true;
9730 }
9731 
9732 namespace {
9733   // Visits an initialization expression to see if OrigDecl is evaluated in
9734   // its own initialization and throws a warning if it does.
9735   class SelfReferenceChecker
9736       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9737     Sema &S;
9738     Decl *OrigDecl;
9739     bool isRecordType;
9740     bool isPODType;
9741     bool isReferenceType;
9742 
9743     bool isInitList;
9744     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9745 
9746   public:
9747     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9748 
9749     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9750                                                     S(S), OrigDecl(OrigDecl) {
9751       isPODType = false;
9752       isRecordType = false;
9753       isReferenceType = false;
9754       isInitList = false;
9755       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9756         isPODType = VD->getType().isPODType(S.Context);
9757         isRecordType = VD->getType()->isRecordType();
9758         isReferenceType = VD->getType()->isReferenceType();
9759       }
9760     }
9761 
9762     // For most expressions, just call the visitor.  For initializer lists,
9763     // track the index of the field being initialized since fields are
9764     // initialized in order allowing use of previously initialized fields.
9765     void CheckExpr(Expr *E) {
9766       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9767       if (!InitList) {
9768         Visit(E);
9769         return;
9770       }
9771 
9772       // Track and increment the index here.
9773       isInitList = true;
9774       InitFieldIndex.push_back(0);
9775       for (auto Child : InitList->children()) {
9776         CheckExpr(cast<Expr>(Child));
9777         ++InitFieldIndex.back();
9778       }
9779       InitFieldIndex.pop_back();
9780     }
9781 
9782     // Returns true if MemberExpr is checked and no further checking is needed.
9783     // Returns false if additional checking is required.
9784     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9785       llvm::SmallVector<FieldDecl*, 4> Fields;
9786       Expr *Base = E;
9787       bool ReferenceField = false;
9788 
9789       // Get the field memebers used.
9790       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9791         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9792         if (!FD)
9793           return false;
9794         Fields.push_back(FD);
9795         if (FD->getType()->isReferenceType())
9796           ReferenceField = true;
9797         Base = ME->getBase()->IgnoreParenImpCasts();
9798       }
9799 
9800       // Keep checking only if the base Decl is the same.
9801       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9802       if (!DRE || DRE->getDecl() != OrigDecl)
9803         return false;
9804 
9805       // A reference field can be bound to an unininitialized field.
9806       if (CheckReference && !ReferenceField)
9807         return true;
9808 
9809       // Convert FieldDecls to their index number.
9810       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9811       for (const FieldDecl *I : llvm::reverse(Fields))
9812         UsedFieldIndex.push_back(I->getFieldIndex());
9813 
9814       // See if a warning is needed by checking the first difference in index
9815       // numbers.  If field being used has index less than the field being
9816       // initialized, then the use is safe.
9817       for (auto UsedIter = UsedFieldIndex.begin(),
9818                 UsedEnd = UsedFieldIndex.end(),
9819                 OrigIter = InitFieldIndex.begin(),
9820                 OrigEnd = InitFieldIndex.end();
9821            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9822         if (*UsedIter < *OrigIter)
9823           return true;
9824         if (*UsedIter > *OrigIter)
9825           break;
9826       }
9827 
9828       // TODO: Add a different warning which will print the field names.
9829       HandleDeclRefExpr(DRE);
9830       return true;
9831     }
9832 
9833     // For most expressions, the cast is directly above the DeclRefExpr.
9834     // For conditional operators, the cast can be outside the conditional
9835     // operator if both expressions are DeclRefExpr's.
9836     void HandleValue(Expr *E) {
9837       E = E->IgnoreParens();
9838       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9839         HandleDeclRefExpr(DRE);
9840         return;
9841       }
9842 
9843       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9844         Visit(CO->getCond());
9845         HandleValue(CO->getTrueExpr());
9846         HandleValue(CO->getFalseExpr());
9847         return;
9848       }
9849 
9850       if (BinaryConditionalOperator *BCO =
9851               dyn_cast<BinaryConditionalOperator>(E)) {
9852         Visit(BCO->getCond());
9853         HandleValue(BCO->getFalseExpr());
9854         return;
9855       }
9856 
9857       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9858         HandleValue(OVE->getSourceExpr());
9859         return;
9860       }
9861 
9862       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9863         if (BO->getOpcode() == BO_Comma) {
9864           Visit(BO->getLHS());
9865           HandleValue(BO->getRHS());
9866           return;
9867         }
9868       }
9869 
9870       if (isa<MemberExpr>(E)) {
9871         if (isInitList) {
9872           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9873                                       false /*CheckReference*/))
9874             return;
9875         }
9876 
9877         Expr *Base = E->IgnoreParenImpCasts();
9878         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9879           // Check for static member variables and don't warn on them.
9880           if (!isa<FieldDecl>(ME->getMemberDecl()))
9881             return;
9882           Base = ME->getBase()->IgnoreParenImpCasts();
9883         }
9884         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9885           HandleDeclRefExpr(DRE);
9886         return;
9887       }
9888 
9889       Visit(E);
9890     }
9891 
9892     // Reference types not handled in HandleValue are handled here since all
9893     // uses of references are bad, not just r-value uses.
9894     void VisitDeclRefExpr(DeclRefExpr *E) {
9895       if (isReferenceType)
9896         HandleDeclRefExpr(E);
9897     }
9898 
9899     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9900       if (E->getCastKind() == CK_LValueToRValue) {
9901         HandleValue(E->getSubExpr());
9902         return;
9903       }
9904 
9905       Inherited::VisitImplicitCastExpr(E);
9906     }
9907 
9908     void VisitMemberExpr(MemberExpr *E) {
9909       if (isInitList) {
9910         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9911           return;
9912       }
9913 
9914       // Don't warn on arrays since they can be treated as pointers.
9915       if (E->getType()->canDecayToPointerType()) return;
9916 
9917       // Warn when a non-static method call is followed by non-static member
9918       // field accesses, which is followed by a DeclRefExpr.
9919       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9920       bool Warn = (MD && !MD->isStatic());
9921       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9922       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9923         if (!isa<FieldDecl>(ME->getMemberDecl()))
9924           Warn = false;
9925         Base = ME->getBase()->IgnoreParenImpCasts();
9926       }
9927 
9928       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9929         if (Warn)
9930           HandleDeclRefExpr(DRE);
9931         return;
9932       }
9933 
9934       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9935       // Visit that expression.
9936       Visit(Base);
9937     }
9938 
9939     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9940       Expr *Callee = E->getCallee();
9941 
9942       if (isa<UnresolvedLookupExpr>(Callee))
9943         return Inherited::VisitCXXOperatorCallExpr(E);
9944 
9945       Visit(Callee);
9946       for (auto Arg: E->arguments())
9947         HandleValue(Arg->IgnoreParenImpCasts());
9948     }
9949 
9950     void VisitUnaryOperator(UnaryOperator *E) {
9951       // For POD record types, addresses of its own members are well-defined.
9952       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9953           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9954         if (!isPODType)
9955           HandleValue(E->getSubExpr());
9956         return;
9957       }
9958 
9959       if (E->isIncrementDecrementOp()) {
9960         HandleValue(E->getSubExpr());
9961         return;
9962       }
9963 
9964       Inherited::VisitUnaryOperator(E);
9965     }
9966 
9967     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9968 
9969     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9970       if (E->getConstructor()->isCopyConstructor()) {
9971         Expr *ArgExpr = E->getArg(0);
9972         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9973           if (ILE->getNumInits() == 1)
9974             ArgExpr = ILE->getInit(0);
9975         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9976           if (ICE->getCastKind() == CK_NoOp)
9977             ArgExpr = ICE->getSubExpr();
9978         HandleValue(ArgExpr);
9979         return;
9980       }
9981       Inherited::VisitCXXConstructExpr(E);
9982     }
9983 
9984     void VisitCallExpr(CallExpr *E) {
9985       // Treat std::move as a use.
9986       if (E->getNumArgs() == 1) {
9987         if (FunctionDecl *FD = E->getDirectCallee()) {
9988           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9989               FD->getIdentifier()->isStr("move")) {
9990             HandleValue(E->getArg(0));
9991             return;
9992           }
9993         }
9994       }
9995 
9996       Inherited::VisitCallExpr(E);
9997     }
9998 
9999     void VisitBinaryOperator(BinaryOperator *E) {
10000       if (E->isCompoundAssignmentOp()) {
10001         HandleValue(E->getLHS());
10002         Visit(E->getRHS());
10003         return;
10004       }
10005 
10006       Inherited::VisitBinaryOperator(E);
10007     }
10008 
10009     // A custom visitor for BinaryConditionalOperator is needed because the
10010     // regular visitor would check the condition and true expression separately
10011     // but both point to the same place giving duplicate diagnostics.
10012     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10013       Visit(E->getCond());
10014       Visit(E->getFalseExpr());
10015     }
10016 
10017     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10018       Decl* ReferenceDecl = DRE->getDecl();
10019       if (OrigDecl != ReferenceDecl) return;
10020       unsigned diag;
10021       if (isReferenceType) {
10022         diag = diag::warn_uninit_self_reference_in_reference_init;
10023       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10024         diag = diag::warn_static_self_reference_in_init;
10025       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10026                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10027                  DRE->getDecl()->getType()->isRecordType()) {
10028         diag = diag::warn_uninit_self_reference_in_init;
10029       } else {
10030         // Local variables will be handled by the CFG analysis.
10031         return;
10032       }
10033 
10034       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10035                             S.PDiag(diag)
10036                               << DRE->getNameInfo().getName()
10037                               << OrigDecl->getLocation()
10038                               << DRE->getSourceRange());
10039     }
10040   };
10041 
10042   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10043   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10044                                  bool DirectInit) {
10045     // Parameters arguments are occassionially constructed with itself,
10046     // for instance, in recursive functions.  Skip them.
10047     if (isa<ParmVarDecl>(OrigDecl))
10048       return;
10049 
10050     E = E->IgnoreParens();
10051 
10052     // Skip checking T a = a where T is not a record or reference type.
10053     // Doing so is a way to silence uninitialized warnings.
10054     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10055       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10056         if (ICE->getCastKind() == CK_LValueToRValue)
10057           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10058             if (DRE->getDecl() == OrigDecl)
10059               return;
10060 
10061     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10062   }
10063 } // end anonymous namespace
10064 
10065 namespace {
10066   // Simple wrapper to add the name of a variable or (if no variable is
10067   // available) a DeclarationName into a diagnostic.
10068   struct VarDeclOrName {
10069     VarDecl *VDecl;
10070     DeclarationName Name;
10071 
10072     friend const Sema::SemaDiagnosticBuilder &
10073     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10074       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10075     }
10076   };
10077 } // end anonymous namespace
10078 
10079 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10080                                             DeclarationName Name, QualType Type,
10081                                             TypeSourceInfo *TSI,
10082                                             SourceRange Range, bool DirectInit,
10083                                             Expr *Init) {
10084   bool IsInitCapture = !VDecl;
10085   assert((!VDecl || !VDecl->isInitCapture()) &&
10086          "init captures are expected to be deduced prior to initialization");
10087 
10088   VarDeclOrName VN{VDecl, Name};
10089 
10090   DeducedType *Deduced = Type->getContainedDeducedType();
10091   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10092 
10093   // C++11 [dcl.spec.auto]p3
10094   if (!Init) {
10095     assert(VDecl && "no init for init capture deduction?");
10096     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10097       << VDecl->getDeclName() << Type;
10098     return QualType();
10099   }
10100 
10101   ArrayRef<Expr*> DeduceInits = Init;
10102   if (DirectInit) {
10103     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10104       DeduceInits = PL->exprs();
10105   }
10106 
10107   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10108     assert(VDecl && "non-auto type for init capture deduction?");
10109     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10110     InitializationKind Kind = InitializationKind::CreateForInit(
10111         VDecl->getLocation(), DirectInit, Init);
10112     // FIXME: Initialization should not be taking a mutable list of inits.
10113     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10114     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10115                                                        InitsCopy);
10116   }
10117 
10118   if (DirectInit) {
10119     if (auto *IL = dyn_cast<InitListExpr>(Init))
10120       DeduceInits = IL->inits();
10121   }
10122 
10123   // Deduction only works if we have exactly one source expression.
10124   if (DeduceInits.empty()) {
10125     // It isn't possible to write this directly, but it is possible to
10126     // end up in this situation with "auto x(some_pack...);"
10127     Diag(Init->getLocStart(), IsInitCapture
10128                                   ? diag::err_init_capture_no_expression
10129                                   : diag::err_auto_var_init_no_expression)
10130         << VN << Type << Range;
10131     return QualType();
10132   }
10133 
10134   if (DeduceInits.size() > 1) {
10135     Diag(DeduceInits[1]->getLocStart(),
10136          IsInitCapture ? diag::err_init_capture_multiple_expressions
10137                        : diag::err_auto_var_init_multiple_expressions)
10138         << VN << Type << Range;
10139     return QualType();
10140   }
10141 
10142   Expr *DeduceInit = DeduceInits[0];
10143   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10144     Diag(Init->getLocStart(), IsInitCapture
10145                                   ? diag::err_init_capture_paren_braces
10146                                   : diag::err_auto_var_init_paren_braces)
10147         << isa<InitListExpr>(Init) << VN << Type << Range;
10148     return QualType();
10149   }
10150 
10151   // Expressions default to 'id' when we're in a debugger.
10152   bool DefaultedAnyToId = false;
10153   if (getLangOpts().DebuggerCastResultToId &&
10154       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10155     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10156     if (Result.isInvalid()) {
10157       return QualType();
10158     }
10159     Init = Result.get();
10160     DefaultedAnyToId = true;
10161   }
10162 
10163   // C++ [dcl.decomp]p1:
10164   //   If the assignment-expression [...] has array type A and no ref-qualifier
10165   //   is present, e has type cv A
10166   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10167       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10168       DeduceInit->getType()->isConstantArrayType())
10169     return Context.getQualifiedType(DeduceInit->getType(),
10170                                     Type.getQualifiers());
10171 
10172   QualType DeducedType;
10173   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10174     if (!IsInitCapture)
10175       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10176     else if (isa<InitListExpr>(Init))
10177       Diag(Range.getBegin(),
10178            diag::err_init_capture_deduction_failure_from_init_list)
10179           << VN
10180           << (DeduceInit->getType().isNull() ? TSI->getType()
10181                                              : DeduceInit->getType())
10182           << DeduceInit->getSourceRange();
10183     else
10184       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10185           << VN << TSI->getType()
10186           << (DeduceInit->getType().isNull() ? TSI->getType()
10187                                              : DeduceInit->getType())
10188           << DeduceInit->getSourceRange();
10189   }
10190 
10191   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10192   // 'id' instead of a specific object type prevents most of our usual
10193   // checks.
10194   // We only want to warn outside of template instantiations, though:
10195   // inside a template, the 'id' could have come from a parameter.
10196   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10197       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10198     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10199     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10200   }
10201 
10202   return DeducedType;
10203 }
10204 
10205 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10206                                          Expr *Init) {
10207   QualType DeducedType = deduceVarTypeFromInitializer(
10208       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10209       VDecl->getSourceRange(), DirectInit, Init);
10210   if (DeducedType.isNull()) {
10211     VDecl->setInvalidDecl();
10212     return true;
10213   }
10214 
10215   VDecl->setType(DeducedType);
10216   assert(VDecl->isLinkageValid());
10217 
10218   // In ARC, infer lifetime.
10219   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10220     VDecl->setInvalidDecl();
10221 
10222   // If this is a redeclaration, check that the type we just deduced matches
10223   // the previously declared type.
10224   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10225     // We never need to merge the type, because we cannot form an incomplete
10226     // array of auto, nor deduce such a type.
10227     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10228   }
10229 
10230   // Check the deduced type is valid for a variable declaration.
10231   CheckVariableDeclarationType(VDecl);
10232   return VDecl->isInvalidDecl();
10233 }
10234 
10235 /// AddInitializerToDecl - Adds the initializer Init to the
10236 /// declaration dcl. If DirectInit is true, this is C++ direct
10237 /// initialization rather than copy initialization.
10238 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10239   // If there is no declaration, there was an error parsing it.  Just ignore
10240   // the initializer.
10241   if (!RealDecl || RealDecl->isInvalidDecl()) {
10242     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10243     return;
10244   }
10245 
10246   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10247     // Pure-specifiers are handled in ActOnPureSpecifier.
10248     Diag(Method->getLocation(), diag::err_member_function_initialization)
10249       << Method->getDeclName() << Init->getSourceRange();
10250     Method->setInvalidDecl();
10251     return;
10252   }
10253 
10254   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10255   if (!VDecl) {
10256     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10257     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10258     RealDecl->setInvalidDecl();
10259     return;
10260   }
10261 
10262   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10263   if (VDecl->getType()->isUndeducedType()) {
10264     // Attempt typo correction early so that the type of the init expression can
10265     // be deduced based on the chosen correction if the original init contains a
10266     // TypoExpr.
10267     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10268     if (!Res.isUsable()) {
10269       RealDecl->setInvalidDecl();
10270       return;
10271     }
10272     Init = Res.get();
10273 
10274     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10275       return;
10276   }
10277 
10278   // dllimport cannot be used on variable definitions.
10279   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10280     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10281     VDecl->setInvalidDecl();
10282     return;
10283   }
10284 
10285   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10286     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10287     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10288     VDecl->setInvalidDecl();
10289     return;
10290   }
10291 
10292   if (!VDecl->getType()->isDependentType()) {
10293     // A definition must end up with a complete type, which means it must be
10294     // complete with the restriction that an array type might be completed by
10295     // the initializer; note that later code assumes this restriction.
10296     QualType BaseDeclType = VDecl->getType();
10297     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10298       BaseDeclType = Array->getElementType();
10299     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10300                             diag::err_typecheck_decl_incomplete_type)) {
10301       RealDecl->setInvalidDecl();
10302       return;
10303     }
10304 
10305     // The variable can not have an abstract class type.
10306     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10307                                diag::err_abstract_type_in_decl,
10308                                AbstractVariableType))
10309       VDecl->setInvalidDecl();
10310   }
10311 
10312   // If adding the initializer will turn this declaration into a definition,
10313   // and we already have a definition for this variable, diagnose or otherwise
10314   // handle the situation.
10315   VarDecl *Def;
10316   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10317       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10318       !VDecl->isThisDeclarationADemotedDefinition() &&
10319       checkVarDeclRedefinition(Def, VDecl))
10320     return;
10321 
10322   if (getLangOpts().CPlusPlus) {
10323     // C++ [class.static.data]p4
10324     //   If a static data member is of const integral or const
10325     //   enumeration type, its declaration in the class definition can
10326     //   specify a constant-initializer which shall be an integral
10327     //   constant expression (5.19). In that case, the member can appear
10328     //   in integral constant expressions. The member shall still be
10329     //   defined in a namespace scope if it is used in the program and the
10330     //   namespace scope definition shall not contain an initializer.
10331     //
10332     // We already performed a redefinition check above, but for static
10333     // data members we also need to check whether there was an in-class
10334     // declaration with an initializer.
10335     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10336       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10337           << VDecl->getDeclName();
10338       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10339            diag::note_previous_initializer)
10340           << 0;
10341       return;
10342     }
10343 
10344     if (VDecl->hasLocalStorage())
10345       getCurFunction()->setHasBranchProtectedScope();
10346 
10347     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10348       VDecl->setInvalidDecl();
10349       return;
10350     }
10351   }
10352 
10353   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10354   // a kernel function cannot be initialized."
10355   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10356     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10357     VDecl->setInvalidDecl();
10358     return;
10359   }
10360 
10361   // Get the decls type and save a reference for later, since
10362   // CheckInitializerTypes may change it.
10363   QualType DclT = VDecl->getType(), SavT = DclT;
10364 
10365   // Expressions default to 'id' when we're in a debugger
10366   // and we are assigning it to a variable of Objective-C pointer type.
10367   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10368       Init->getType() == Context.UnknownAnyTy) {
10369     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10370     if (Result.isInvalid()) {
10371       VDecl->setInvalidDecl();
10372       return;
10373     }
10374     Init = Result.get();
10375   }
10376 
10377   // Perform the initialization.
10378   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10379   if (!VDecl->isInvalidDecl()) {
10380     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10381     InitializationKind Kind = InitializationKind::CreateForInit(
10382         VDecl->getLocation(), DirectInit, Init);
10383 
10384     MultiExprArg Args = Init;
10385     if (CXXDirectInit)
10386       Args = MultiExprArg(CXXDirectInit->getExprs(),
10387                           CXXDirectInit->getNumExprs());
10388 
10389     // Try to correct any TypoExprs in the initialization arguments.
10390     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10391       ExprResult Res = CorrectDelayedTyposInExpr(
10392           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10393             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10394             return Init.Failed() ? ExprError() : E;
10395           });
10396       if (Res.isInvalid()) {
10397         VDecl->setInvalidDecl();
10398       } else if (Res.get() != Args[Idx]) {
10399         Args[Idx] = Res.get();
10400       }
10401     }
10402     if (VDecl->isInvalidDecl())
10403       return;
10404 
10405     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10406                                    /*TopLevelOfInitList=*/false,
10407                                    /*TreatUnavailableAsInvalid=*/false);
10408     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10409     if (Result.isInvalid()) {
10410       VDecl->setInvalidDecl();
10411       return;
10412     }
10413 
10414     Init = Result.getAs<Expr>();
10415   }
10416 
10417   // Check for self-references within variable initializers.
10418   // Variables declared within a function/method body (except for references)
10419   // are handled by a dataflow analysis.
10420   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10421       VDecl->getType()->isReferenceType()) {
10422     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10423   }
10424 
10425   // If the type changed, it means we had an incomplete type that was
10426   // completed by the initializer. For example:
10427   //   int ary[] = { 1, 3, 5 };
10428   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10429   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10430     VDecl->setType(DclT);
10431 
10432   if (!VDecl->isInvalidDecl()) {
10433     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10434 
10435     if (VDecl->hasAttr<BlocksAttr>())
10436       checkRetainCycles(VDecl, Init);
10437 
10438     // It is safe to assign a weak reference into a strong variable.
10439     // Although this code can still have problems:
10440     //   id x = self.weakProp;
10441     //   id y = self.weakProp;
10442     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10443     // paths through the function. This should be revisited if
10444     // -Wrepeated-use-of-weak is made flow-sensitive.
10445     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10446          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10447         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10448                          Init->getLocStart()))
10449       getCurFunction()->markSafeWeakUse(Init);
10450   }
10451 
10452   // The initialization is usually a full-expression.
10453   //
10454   // FIXME: If this is a braced initialization of an aggregate, it is not
10455   // an expression, and each individual field initializer is a separate
10456   // full-expression. For instance, in:
10457   //
10458   //   struct Temp { ~Temp(); };
10459   //   struct S { S(Temp); };
10460   //   struct T { S a, b; } t = { Temp(), Temp() }
10461   //
10462   // we should destroy the first Temp before constructing the second.
10463   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10464                                           false,
10465                                           VDecl->isConstexpr());
10466   if (Result.isInvalid()) {
10467     VDecl->setInvalidDecl();
10468     return;
10469   }
10470   Init = Result.get();
10471 
10472   // Attach the initializer to the decl.
10473   VDecl->setInit(Init);
10474 
10475   if (VDecl->isLocalVarDecl()) {
10476     // Don't check the initializer if the declaration is malformed.
10477     if (VDecl->isInvalidDecl()) {
10478       // do nothing
10479 
10480     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10481     // This is true even in OpenCL C++.
10482     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10483       CheckForConstantInitializer(Init, DclT);
10484 
10485     // Otherwise, C++ does not restrict the initializer.
10486     } else if (getLangOpts().CPlusPlus) {
10487       // do nothing
10488 
10489     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10490     // static storage duration shall be constant expressions or string literals.
10491     } else if (VDecl->getStorageClass() == SC_Static) {
10492       CheckForConstantInitializer(Init, DclT);
10493 
10494     // C89 is stricter than C99 for aggregate initializers.
10495     // C89 6.5.7p3: All the expressions [...] in an initializer list
10496     // for an object that has aggregate or union type shall be
10497     // constant expressions.
10498     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10499                isa<InitListExpr>(Init)) {
10500       const Expr *Culprit;
10501       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10502         Diag(Culprit->getExprLoc(),
10503              diag::ext_aggregate_init_not_constant)
10504           << Culprit->getSourceRange();
10505       }
10506     }
10507   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10508              VDecl->getLexicalDeclContext()->isRecord()) {
10509     // This is an in-class initialization for a static data member, e.g.,
10510     //
10511     // struct S {
10512     //   static const int value = 17;
10513     // };
10514 
10515     // C++ [class.mem]p4:
10516     //   A member-declarator can contain a constant-initializer only
10517     //   if it declares a static member (9.4) of const integral or
10518     //   const enumeration type, see 9.4.2.
10519     //
10520     // C++11 [class.static.data]p3:
10521     //   If a non-volatile non-inline const static data member is of integral
10522     //   or enumeration type, its declaration in the class definition can
10523     //   specify a brace-or-equal-initializer in which every initializer-clause
10524     //   that is an assignment-expression is a constant expression. A static
10525     //   data member of literal type can be declared in the class definition
10526     //   with the constexpr specifier; if so, its declaration shall specify a
10527     //   brace-or-equal-initializer in which every initializer-clause that is
10528     //   an assignment-expression is a constant expression.
10529 
10530     // Do nothing on dependent types.
10531     if (DclT->isDependentType()) {
10532 
10533     // Allow any 'static constexpr' members, whether or not they are of literal
10534     // type. We separately check that every constexpr variable is of literal
10535     // type.
10536     } else if (VDecl->isConstexpr()) {
10537 
10538     // Require constness.
10539     } else if (!DclT.isConstQualified()) {
10540       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10541         << Init->getSourceRange();
10542       VDecl->setInvalidDecl();
10543 
10544     // We allow integer constant expressions in all cases.
10545     } else if (DclT->isIntegralOrEnumerationType()) {
10546       // Check whether the expression is a constant expression.
10547       SourceLocation Loc;
10548       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10549         // In C++11, a non-constexpr const static data member with an
10550         // in-class initializer cannot be volatile.
10551         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10552       else if (Init->isValueDependent())
10553         ; // Nothing to check.
10554       else if (Init->isIntegerConstantExpr(Context, &Loc))
10555         ; // Ok, it's an ICE!
10556       else if (Init->isEvaluatable(Context)) {
10557         // If we can constant fold the initializer through heroics, accept it,
10558         // but report this as a use of an extension for -pedantic.
10559         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10560           << Init->getSourceRange();
10561       } else {
10562         // Otherwise, this is some crazy unknown case.  Report the issue at the
10563         // location provided by the isIntegerConstantExpr failed check.
10564         Diag(Loc, diag::err_in_class_initializer_non_constant)
10565           << Init->getSourceRange();
10566         VDecl->setInvalidDecl();
10567       }
10568 
10569     // We allow foldable floating-point constants as an extension.
10570     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10571       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10572       // it anyway and provide a fixit to add the 'constexpr'.
10573       if (getLangOpts().CPlusPlus11) {
10574         Diag(VDecl->getLocation(),
10575              diag::ext_in_class_initializer_float_type_cxx11)
10576             << DclT << Init->getSourceRange();
10577         Diag(VDecl->getLocStart(),
10578              diag::note_in_class_initializer_float_type_cxx11)
10579             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10580       } else {
10581         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10582           << DclT << Init->getSourceRange();
10583 
10584         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10585           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10586             << Init->getSourceRange();
10587           VDecl->setInvalidDecl();
10588         }
10589       }
10590 
10591     // Suggest adding 'constexpr' in C++11 for literal types.
10592     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10593       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10594         << DclT << Init->getSourceRange()
10595         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10596       VDecl->setConstexpr(true);
10597 
10598     } else {
10599       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10600         << DclT << Init->getSourceRange();
10601       VDecl->setInvalidDecl();
10602     }
10603   } else if (VDecl->isFileVarDecl()) {
10604     // In C, extern is typically used to avoid tentative definitions when
10605     // declaring variables in headers, but adding an intializer makes it a
10606     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10607     // In C++, extern is often used to give implictly static const variables
10608     // external linkage, so don't warn in that case. If selectany is present,
10609     // this might be header code intended for C and C++ inclusion, so apply the
10610     // C++ rules.
10611     if (VDecl->getStorageClass() == SC_Extern &&
10612         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10613          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10614         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10615         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10616       Diag(VDecl->getLocation(), diag::warn_extern_init);
10617 
10618     // C99 6.7.8p4. All file scoped initializers need to be constant.
10619     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10620       CheckForConstantInitializer(Init, DclT);
10621   }
10622 
10623   // We will represent direct-initialization similarly to copy-initialization:
10624   //    int x(1);  -as-> int x = 1;
10625   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10626   //
10627   // Clients that want to distinguish between the two forms, can check for
10628   // direct initializer using VarDecl::getInitStyle().
10629   // A major benefit is that clients that don't particularly care about which
10630   // exactly form was it (like the CodeGen) can handle both cases without
10631   // special case code.
10632 
10633   // C++ 8.5p11:
10634   // The form of initialization (using parentheses or '=') is generally
10635   // insignificant, but does matter when the entity being initialized has a
10636   // class type.
10637   if (CXXDirectInit) {
10638     assert(DirectInit && "Call-style initializer must be direct init.");
10639     VDecl->setInitStyle(VarDecl::CallInit);
10640   } else if (DirectInit) {
10641     // This must be list-initialization. No other way is direct-initialization.
10642     VDecl->setInitStyle(VarDecl::ListInit);
10643   }
10644 
10645   CheckCompleteVariableDeclaration(VDecl);
10646 }
10647 
10648 /// ActOnInitializerError - Given that there was an error parsing an
10649 /// initializer for the given declaration, try to return to some form
10650 /// of sanity.
10651 void Sema::ActOnInitializerError(Decl *D) {
10652   // Our main concern here is re-establishing invariants like "a
10653   // variable's type is either dependent or complete".
10654   if (!D || D->isInvalidDecl()) return;
10655 
10656   VarDecl *VD = dyn_cast<VarDecl>(D);
10657   if (!VD) return;
10658 
10659   // Bindings are not usable if we can't make sense of the initializer.
10660   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10661     for (auto *BD : DD->bindings())
10662       BD->setInvalidDecl();
10663 
10664   // Auto types are meaningless if we can't make sense of the initializer.
10665   if (ParsingInitForAutoVars.count(D)) {
10666     D->setInvalidDecl();
10667     return;
10668   }
10669 
10670   QualType Ty = VD->getType();
10671   if (Ty->isDependentType()) return;
10672 
10673   // Require a complete type.
10674   if (RequireCompleteType(VD->getLocation(),
10675                           Context.getBaseElementType(Ty),
10676                           diag::err_typecheck_decl_incomplete_type)) {
10677     VD->setInvalidDecl();
10678     return;
10679   }
10680 
10681   // Require a non-abstract type.
10682   if (RequireNonAbstractType(VD->getLocation(), Ty,
10683                              diag::err_abstract_type_in_decl,
10684                              AbstractVariableType)) {
10685     VD->setInvalidDecl();
10686     return;
10687   }
10688 
10689   // Don't bother complaining about constructors or destructors,
10690   // though.
10691 }
10692 
10693 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10694   // If there is no declaration, there was an error parsing it. Just ignore it.
10695   if (!RealDecl)
10696     return;
10697 
10698   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10699     QualType Type = Var->getType();
10700 
10701     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10702     if (isa<DecompositionDecl>(RealDecl)) {
10703       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10704       Var->setInvalidDecl();
10705       return;
10706     }
10707 
10708     if (Type->isUndeducedType() &&
10709         DeduceVariableDeclarationType(Var, false, nullptr))
10710       return;
10711 
10712     // C++11 [class.static.data]p3: A static data member can be declared with
10713     // the constexpr specifier; if so, its declaration shall specify
10714     // a brace-or-equal-initializer.
10715     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10716     // the definition of a variable [...] or the declaration of a static data
10717     // member.
10718     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10719         !Var->isThisDeclarationADemotedDefinition()) {
10720       if (Var->isStaticDataMember()) {
10721         // C++1z removes the relevant rule; the in-class declaration is always
10722         // a definition there.
10723         if (!getLangOpts().CPlusPlus1z) {
10724           Diag(Var->getLocation(),
10725                diag::err_constexpr_static_mem_var_requires_init)
10726             << Var->getDeclName();
10727           Var->setInvalidDecl();
10728           return;
10729         }
10730       } else {
10731         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10732         Var->setInvalidDecl();
10733         return;
10734       }
10735     }
10736 
10737     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10738     // definition having the concept specifier is called a variable concept. A
10739     // concept definition refers to [...] a variable concept and its initializer.
10740     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10741       if (VTD->isConcept()) {
10742         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10743         Var->setInvalidDecl();
10744         return;
10745       }
10746     }
10747 
10748     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10749     // be initialized.
10750     if (!Var->isInvalidDecl() &&
10751         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10752         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10753       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10754       Var->setInvalidDecl();
10755       return;
10756     }
10757 
10758     switch (Var->isThisDeclarationADefinition()) {
10759     case VarDecl::Definition:
10760       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10761         break;
10762 
10763       // We have an out-of-line definition of a static data member
10764       // that has an in-class initializer, so we type-check this like
10765       // a declaration.
10766       //
10767       // Fall through
10768 
10769     case VarDecl::DeclarationOnly:
10770       // It's only a declaration.
10771 
10772       // Block scope. C99 6.7p7: If an identifier for an object is
10773       // declared with no linkage (C99 6.2.2p6), the type for the
10774       // object shall be complete.
10775       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10776           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10777           RequireCompleteType(Var->getLocation(), Type,
10778                               diag::err_typecheck_decl_incomplete_type))
10779         Var->setInvalidDecl();
10780 
10781       // Make sure that the type is not abstract.
10782       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10783           RequireNonAbstractType(Var->getLocation(), Type,
10784                                  diag::err_abstract_type_in_decl,
10785                                  AbstractVariableType))
10786         Var->setInvalidDecl();
10787       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10788           Var->getStorageClass() == SC_PrivateExtern) {
10789         Diag(Var->getLocation(), diag::warn_private_extern);
10790         Diag(Var->getLocation(), diag::note_private_extern);
10791       }
10792 
10793       return;
10794 
10795     case VarDecl::TentativeDefinition:
10796       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10797       // object that has file scope without an initializer, and without a
10798       // storage-class specifier or with the storage-class specifier "static",
10799       // constitutes a tentative definition. Note: A tentative definition with
10800       // external linkage is valid (C99 6.2.2p5).
10801       if (!Var->isInvalidDecl()) {
10802         if (const IncompleteArrayType *ArrayT
10803                                     = Context.getAsIncompleteArrayType(Type)) {
10804           if (RequireCompleteType(Var->getLocation(),
10805                                   ArrayT->getElementType(),
10806                                   diag::err_illegal_decl_array_incomplete_type))
10807             Var->setInvalidDecl();
10808         } else if (Var->getStorageClass() == SC_Static) {
10809           // C99 6.9.2p3: If the declaration of an identifier for an object is
10810           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10811           // declared type shall not be an incomplete type.
10812           // NOTE: code such as the following
10813           //     static struct s;
10814           //     struct s { int a; };
10815           // is accepted by gcc. Hence here we issue a warning instead of
10816           // an error and we do not invalidate the static declaration.
10817           // NOTE: to avoid multiple warnings, only check the first declaration.
10818           if (Var->isFirstDecl())
10819             RequireCompleteType(Var->getLocation(), Type,
10820                                 diag::ext_typecheck_decl_incomplete_type);
10821         }
10822       }
10823 
10824       // Record the tentative definition; we're done.
10825       if (!Var->isInvalidDecl())
10826         TentativeDefinitions.push_back(Var);
10827       return;
10828     }
10829 
10830     // Provide a specific diagnostic for uninitialized variable
10831     // definitions with incomplete array type.
10832     if (Type->isIncompleteArrayType()) {
10833       Diag(Var->getLocation(),
10834            diag::err_typecheck_incomplete_array_needs_initializer);
10835       Var->setInvalidDecl();
10836       return;
10837     }
10838 
10839     // Provide a specific diagnostic for uninitialized variable
10840     // definitions with reference type.
10841     if (Type->isReferenceType()) {
10842       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10843         << Var->getDeclName()
10844         << SourceRange(Var->getLocation(), Var->getLocation());
10845       Var->setInvalidDecl();
10846       return;
10847     }
10848 
10849     // Do not attempt to type-check the default initializer for a
10850     // variable with dependent type.
10851     if (Type->isDependentType())
10852       return;
10853 
10854     if (Var->isInvalidDecl())
10855       return;
10856 
10857     if (!Var->hasAttr<AliasAttr>()) {
10858       if (RequireCompleteType(Var->getLocation(),
10859                               Context.getBaseElementType(Type),
10860                               diag::err_typecheck_decl_incomplete_type)) {
10861         Var->setInvalidDecl();
10862         return;
10863       }
10864     } else {
10865       return;
10866     }
10867 
10868     // The variable can not have an abstract class type.
10869     if (RequireNonAbstractType(Var->getLocation(), Type,
10870                                diag::err_abstract_type_in_decl,
10871                                AbstractVariableType)) {
10872       Var->setInvalidDecl();
10873       return;
10874     }
10875 
10876     // Check for jumps past the implicit initializer.  C++0x
10877     // clarifies that this applies to a "variable with automatic
10878     // storage duration", not a "local variable".
10879     // C++11 [stmt.dcl]p3
10880     //   A program that jumps from a point where a variable with automatic
10881     //   storage duration is not in scope to a point where it is in scope is
10882     //   ill-formed unless the variable has scalar type, class type with a
10883     //   trivial default constructor and a trivial destructor, a cv-qualified
10884     //   version of one of these types, or an array of one of the preceding
10885     //   types and is declared without an initializer.
10886     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10887       if (const RecordType *Record
10888             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10889         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10890         // Mark the function for further checking even if the looser rules of
10891         // C++11 do not require such checks, so that we can diagnose
10892         // incompatibilities with C++98.
10893         if (!CXXRecord->isPOD())
10894           getCurFunction()->setHasBranchProtectedScope();
10895       }
10896     }
10897 
10898     // C++03 [dcl.init]p9:
10899     //   If no initializer is specified for an object, and the
10900     //   object is of (possibly cv-qualified) non-POD class type (or
10901     //   array thereof), the object shall be default-initialized; if
10902     //   the object is of const-qualified type, the underlying class
10903     //   type shall have a user-declared default
10904     //   constructor. Otherwise, if no initializer is specified for
10905     //   a non- static object, the object and its subobjects, if
10906     //   any, have an indeterminate initial value); if the object
10907     //   or any of its subobjects are of const-qualified type, the
10908     //   program is ill-formed.
10909     // C++0x [dcl.init]p11:
10910     //   If no initializer is specified for an object, the object is
10911     //   default-initialized; [...].
10912     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10913     InitializationKind Kind
10914       = InitializationKind::CreateDefault(Var->getLocation());
10915 
10916     InitializationSequence InitSeq(*this, Entity, Kind, None);
10917     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10918     if (Init.isInvalid())
10919       Var->setInvalidDecl();
10920     else if (Init.get()) {
10921       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10922       // This is important for template substitution.
10923       Var->setInitStyle(VarDecl::CallInit);
10924     }
10925 
10926     CheckCompleteVariableDeclaration(Var);
10927   }
10928 }
10929 
10930 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10931   // If there is no declaration, there was an error parsing it. Ignore it.
10932   if (!D)
10933     return;
10934 
10935   VarDecl *VD = dyn_cast<VarDecl>(D);
10936   if (!VD) {
10937     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10938     D->setInvalidDecl();
10939     return;
10940   }
10941 
10942   VD->setCXXForRangeDecl(true);
10943 
10944   // for-range-declaration cannot be given a storage class specifier.
10945   int Error = -1;
10946   switch (VD->getStorageClass()) {
10947   case SC_None:
10948     break;
10949   case SC_Extern:
10950     Error = 0;
10951     break;
10952   case SC_Static:
10953     Error = 1;
10954     break;
10955   case SC_PrivateExtern:
10956     Error = 2;
10957     break;
10958   case SC_Auto:
10959     Error = 3;
10960     break;
10961   case SC_Register:
10962     Error = 4;
10963     break;
10964   }
10965   if (Error != -1) {
10966     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10967       << VD->getDeclName() << Error;
10968     D->setInvalidDecl();
10969   }
10970 }
10971 
10972 StmtResult
10973 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10974                                  IdentifierInfo *Ident,
10975                                  ParsedAttributes &Attrs,
10976                                  SourceLocation AttrEnd) {
10977   // C++1y [stmt.iter]p1:
10978   //   A range-based for statement of the form
10979   //      for ( for-range-identifier : for-range-initializer ) statement
10980   //   is equivalent to
10981   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10982   DeclSpec DS(Attrs.getPool().getFactory());
10983 
10984   const char *PrevSpec;
10985   unsigned DiagID;
10986   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10987                      getPrintingPolicy());
10988 
10989   Declarator D(DS, Declarator::ForContext);
10990   D.SetIdentifier(Ident, IdentLoc);
10991   D.takeAttributes(Attrs, AttrEnd);
10992 
10993   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10994   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10995                 EmptyAttrs, IdentLoc);
10996   Decl *Var = ActOnDeclarator(S, D);
10997   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10998   FinalizeDeclaration(Var);
10999   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11000                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11001 }
11002 
11003 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11004   if (var->isInvalidDecl()) return;
11005 
11006   if (getLangOpts().OpenCL) {
11007     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11008     // initialiser
11009     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11010         !var->hasInit()) {
11011       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11012           << 1 /*Init*/;
11013       var->setInvalidDecl();
11014       return;
11015     }
11016   }
11017 
11018   // In Objective-C, don't allow jumps past the implicit initialization of a
11019   // local retaining variable.
11020   if (getLangOpts().ObjC1 &&
11021       var->hasLocalStorage()) {
11022     switch (var->getType().getObjCLifetime()) {
11023     case Qualifiers::OCL_None:
11024     case Qualifiers::OCL_ExplicitNone:
11025     case Qualifiers::OCL_Autoreleasing:
11026       break;
11027 
11028     case Qualifiers::OCL_Weak:
11029     case Qualifiers::OCL_Strong:
11030       getCurFunction()->setHasBranchProtectedScope();
11031       break;
11032     }
11033   }
11034 
11035   // Warn about externally-visible variables being defined without a
11036   // prior declaration.  We only want to do this for global
11037   // declarations, but we also specifically need to avoid doing it for
11038   // class members because the linkage of an anonymous class can
11039   // change if it's later given a typedef name.
11040   if (var->isThisDeclarationADefinition() &&
11041       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11042       var->isExternallyVisible() && var->hasLinkage() &&
11043       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11044                                   var->getLocation())) {
11045     // Find a previous declaration that's not a definition.
11046     VarDecl *prev = var->getPreviousDecl();
11047     while (prev && prev->isThisDeclarationADefinition())
11048       prev = prev->getPreviousDecl();
11049 
11050     if (!prev)
11051       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11052   }
11053 
11054   // Cache the result of checking for constant initialization.
11055   Optional<bool> CacheHasConstInit;
11056   const Expr *CacheCulprit;
11057   auto checkConstInit = [&]() mutable {
11058     if (!CacheHasConstInit)
11059       CacheHasConstInit = var->getInit()->isConstantInitializer(
11060             Context, var->getType()->isReferenceType(), &CacheCulprit);
11061     return *CacheHasConstInit;
11062   };
11063 
11064   if (var->getTLSKind() == VarDecl::TLS_Static) {
11065     if (var->getType().isDestructedType()) {
11066       // GNU C++98 edits for __thread, [basic.start.term]p3:
11067       //   The type of an object with thread storage duration shall not
11068       //   have a non-trivial destructor.
11069       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11070       if (getLangOpts().CPlusPlus11)
11071         Diag(var->getLocation(), diag::note_use_thread_local);
11072     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11073       if (!checkConstInit()) {
11074         // GNU C++98 edits for __thread, [basic.start.init]p4:
11075         //   An object of thread storage duration shall not require dynamic
11076         //   initialization.
11077         // FIXME: Need strict checking here.
11078         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11079           << CacheCulprit->getSourceRange();
11080         if (getLangOpts().CPlusPlus11)
11081           Diag(var->getLocation(), diag::note_use_thread_local);
11082       }
11083     }
11084   }
11085 
11086   // Apply section attributes and pragmas to global variables.
11087   bool GlobalStorage = var->hasGlobalStorage();
11088   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11089       !inTemplateInstantiation()) {
11090     PragmaStack<StringLiteral *> *Stack = nullptr;
11091     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11092     if (var->getType().isConstQualified())
11093       Stack = &ConstSegStack;
11094     else if (!var->getInit()) {
11095       Stack = &BSSSegStack;
11096       SectionFlags |= ASTContext::PSF_Write;
11097     } else {
11098       Stack = &DataSegStack;
11099       SectionFlags |= ASTContext::PSF_Write;
11100     }
11101     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11102       var->addAttr(SectionAttr::CreateImplicit(
11103           Context, SectionAttr::Declspec_allocate,
11104           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11105     }
11106     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11107       if (UnifySection(SA->getName(), SectionFlags, var))
11108         var->dropAttr<SectionAttr>();
11109 
11110     // Apply the init_seg attribute if this has an initializer.  If the
11111     // initializer turns out to not be dynamic, we'll end up ignoring this
11112     // attribute.
11113     if (CurInitSeg && var->getInit())
11114       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11115                                                CurInitSegLoc));
11116   }
11117 
11118   // All the following checks are C++ only.
11119   if (!getLangOpts().CPlusPlus) {
11120       // If this variable must be emitted, add it as an initializer for the
11121       // current module.
11122      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11123        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11124      return;
11125   }
11126 
11127   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11128     CheckCompleteDecompositionDeclaration(DD);
11129 
11130   QualType type = var->getType();
11131   if (type->isDependentType()) return;
11132 
11133   // __block variables might require us to capture a copy-initializer.
11134   if (var->hasAttr<BlocksAttr>()) {
11135     // It's currently invalid to ever have a __block variable with an
11136     // array type; should we diagnose that here?
11137 
11138     // Regardless, we don't want to ignore array nesting when
11139     // constructing this copy.
11140     if (type->isStructureOrClassType()) {
11141       EnterExpressionEvaluationContext scope(
11142           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11143       SourceLocation poi = var->getLocation();
11144       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11145       ExprResult result
11146         = PerformMoveOrCopyInitialization(
11147             InitializedEntity::InitializeBlock(poi, type, false),
11148             var, var->getType(), varRef, /*AllowNRVO=*/true);
11149       if (!result.isInvalid()) {
11150         result = MaybeCreateExprWithCleanups(result);
11151         Expr *init = result.getAs<Expr>();
11152         Context.setBlockVarCopyInits(var, init);
11153       }
11154     }
11155   }
11156 
11157   Expr *Init = var->getInit();
11158   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11159   QualType baseType = Context.getBaseElementType(type);
11160 
11161   if (Init && !Init->isValueDependent()) {
11162     if (var->isConstexpr()) {
11163       SmallVector<PartialDiagnosticAt, 8> Notes;
11164       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11165         SourceLocation DiagLoc = var->getLocation();
11166         // If the note doesn't add any useful information other than a source
11167         // location, fold it into the primary diagnostic.
11168         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11169               diag::note_invalid_subexpr_in_const_expr) {
11170           DiagLoc = Notes[0].first;
11171           Notes.clear();
11172         }
11173         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11174           << var << Init->getSourceRange();
11175         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11176           Diag(Notes[I].first, Notes[I].second);
11177       }
11178     } else if (var->isUsableInConstantExpressions(Context)) {
11179       // Check whether the initializer of a const variable of integral or
11180       // enumeration type is an ICE now, since we can't tell whether it was
11181       // initialized by a constant expression if we check later.
11182       var->checkInitIsICE();
11183     }
11184 
11185     // Don't emit further diagnostics about constexpr globals since they
11186     // were just diagnosed.
11187     if (!var->isConstexpr() && GlobalStorage &&
11188             var->hasAttr<RequireConstantInitAttr>()) {
11189       // FIXME: Need strict checking in C++03 here.
11190       bool DiagErr = getLangOpts().CPlusPlus11
11191           ? !var->checkInitIsICE() : !checkConstInit();
11192       if (DiagErr) {
11193         auto attr = var->getAttr<RequireConstantInitAttr>();
11194         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11195           << Init->getSourceRange();
11196         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11197           << attr->getRange();
11198         if (getLangOpts().CPlusPlus11) {
11199           APValue Value;
11200           SmallVector<PartialDiagnosticAt, 8> Notes;
11201           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11202           for (auto &it : Notes)
11203             Diag(it.first, it.second);
11204         } else {
11205           Diag(CacheCulprit->getExprLoc(),
11206                diag::note_invalid_subexpr_in_const_expr)
11207               << CacheCulprit->getSourceRange();
11208         }
11209       }
11210     }
11211     else if (!var->isConstexpr() && IsGlobal &&
11212              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11213                                     var->getLocation())) {
11214       // Warn about globals which don't have a constant initializer.  Don't
11215       // warn about globals with a non-trivial destructor because we already
11216       // warned about them.
11217       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11218       if (!(RD && !RD->hasTrivialDestructor())) {
11219         if (!checkConstInit())
11220           Diag(var->getLocation(), diag::warn_global_constructor)
11221             << Init->getSourceRange();
11222       }
11223     }
11224   }
11225 
11226   // Require the destructor.
11227   if (const RecordType *recordType = baseType->getAs<RecordType>())
11228     FinalizeVarWithDestructor(var, recordType);
11229 
11230   // If this variable must be emitted, add it as an initializer for the current
11231   // module.
11232   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11233     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11234 }
11235 
11236 /// \brief Determines if a variable's alignment is dependent.
11237 static bool hasDependentAlignment(VarDecl *VD) {
11238   if (VD->getType()->isDependentType())
11239     return true;
11240   for (auto *I : VD->specific_attrs<AlignedAttr>())
11241     if (I->isAlignmentDependent())
11242       return true;
11243   return false;
11244 }
11245 
11246 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11247 /// any semantic actions necessary after any initializer has been attached.
11248 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11249   // Note that we are no longer parsing the initializer for this declaration.
11250   ParsingInitForAutoVars.erase(ThisDecl);
11251 
11252   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11253   if (!VD)
11254     return;
11255 
11256   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11257   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11258       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11259     if (PragmaClangBSSSection.Valid)
11260       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11261                                                             PragmaClangBSSSection.SectionName,
11262                                                             PragmaClangBSSSection.PragmaLocation));
11263     if (PragmaClangDataSection.Valid)
11264       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11265                                                              PragmaClangDataSection.SectionName,
11266                                                              PragmaClangDataSection.PragmaLocation));
11267     if (PragmaClangRodataSection.Valid)
11268       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11269                                                                PragmaClangRodataSection.SectionName,
11270                                                                PragmaClangRodataSection.PragmaLocation));
11271   }
11272 
11273   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11274     for (auto *BD : DD->bindings()) {
11275       FinalizeDeclaration(BD);
11276     }
11277   }
11278 
11279   checkAttributesAfterMerging(*this, *VD);
11280 
11281   // Perform TLS alignment check here after attributes attached to the variable
11282   // which may affect the alignment have been processed. Only perform the check
11283   // if the target has a maximum TLS alignment (zero means no constraints).
11284   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11285     // Protect the check so that it's not performed on dependent types and
11286     // dependent alignments (we can't determine the alignment in that case).
11287     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11288         !VD->isInvalidDecl()) {
11289       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11290       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11291         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11292           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11293           << (unsigned)MaxAlignChars.getQuantity();
11294       }
11295     }
11296   }
11297 
11298   if (VD->isStaticLocal()) {
11299     if (FunctionDecl *FD =
11300             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11301       // Static locals inherit dll attributes from their function.
11302       if (Attr *A = getDLLAttr(FD)) {
11303         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11304         NewAttr->setInherited(true);
11305         VD->addAttr(NewAttr);
11306       }
11307       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11308       // function, only __shared__ variables may be declared with
11309       // static storage class.
11310       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11311           CUDADiagIfDeviceCode(VD->getLocation(),
11312                                diag::err_device_static_local_var)
11313               << CurrentCUDATarget())
11314         VD->setInvalidDecl();
11315     }
11316   }
11317 
11318   // Perform check for initializers of device-side global variables.
11319   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11320   // 7.5). We must also apply the same checks to all __shared__
11321   // variables whether they are local or not. CUDA also allows
11322   // constant initializers for __constant__ and __device__ variables.
11323   if (getLangOpts().CUDA) {
11324     const Expr *Init = VD->getInit();
11325     if (Init && VD->hasGlobalStorage()) {
11326       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11327           VD->hasAttr<CUDASharedAttr>()) {
11328         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11329         bool AllowedInit = false;
11330         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11331           AllowedInit =
11332               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11333         // We'll allow constant initializers even if it's a non-empty
11334         // constructor according to CUDA rules. This deviates from NVCC,
11335         // but allows us to handle things like constexpr constructors.
11336         if (!AllowedInit &&
11337             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11338           AllowedInit = VD->getInit()->isConstantInitializer(
11339               Context, VD->getType()->isReferenceType());
11340 
11341         // Also make sure that destructor, if there is one, is empty.
11342         if (AllowedInit)
11343           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11344             AllowedInit =
11345                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11346 
11347         if (!AllowedInit) {
11348           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11349                                       ? diag::err_shared_var_init
11350                                       : diag::err_dynamic_var_init)
11351               << Init->getSourceRange();
11352           VD->setInvalidDecl();
11353         }
11354       } else {
11355         // This is a host-side global variable.  Check that the initializer is
11356         // callable from the host side.
11357         const FunctionDecl *InitFn = nullptr;
11358         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11359           InitFn = CE->getConstructor();
11360         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11361           InitFn = CE->getDirectCallee();
11362         }
11363         if (InitFn) {
11364           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11365           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11366             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11367                 << InitFnTarget << InitFn;
11368             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11369             VD->setInvalidDecl();
11370           }
11371         }
11372       }
11373     }
11374   }
11375 
11376   // Grab the dllimport or dllexport attribute off of the VarDecl.
11377   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11378 
11379   // Imported static data members cannot be defined out-of-line.
11380   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11381     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11382         VD->isThisDeclarationADefinition()) {
11383       // We allow definitions of dllimport class template static data members
11384       // with a warning.
11385       CXXRecordDecl *Context =
11386         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11387       bool IsClassTemplateMember =
11388           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11389           Context->getDescribedClassTemplate();
11390 
11391       Diag(VD->getLocation(),
11392            IsClassTemplateMember
11393                ? diag::warn_attribute_dllimport_static_field_definition
11394                : diag::err_attribute_dllimport_static_field_definition);
11395       Diag(IA->getLocation(), diag::note_attribute);
11396       if (!IsClassTemplateMember)
11397         VD->setInvalidDecl();
11398     }
11399   }
11400 
11401   // dllimport/dllexport variables cannot be thread local, their TLS index
11402   // isn't exported with the variable.
11403   if (DLLAttr && VD->getTLSKind()) {
11404     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11405     if (F && getDLLAttr(F)) {
11406       assert(VD->isStaticLocal());
11407       // But if this is a static local in a dlimport/dllexport function, the
11408       // function will never be inlined, which means the var would never be
11409       // imported, so having it marked import/export is safe.
11410     } else {
11411       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11412                                                                     << DLLAttr;
11413       VD->setInvalidDecl();
11414     }
11415   }
11416 
11417   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11418     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11419       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11420       VD->dropAttr<UsedAttr>();
11421     }
11422   }
11423 
11424   const DeclContext *DC = VD->getDeclContext();
11425   // If there's a #pragma GCC visibility in scope, and this isn't a class
11426   // member, set the visibility of this variable.
11427   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11428     AddPushedVisibilityAttribute(VD);
11429 
11430   // FIXME: Warn on unused var template partial specializations.
11431   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11432     MarkUnusedFileScopedDecl(VD);
11433 
11434   // Now we have parsed the initializer and can update the table of magic
11435   // tag values.
11436   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11437       !VD->getType()->isIntegralOrEnumerationType())
11438     return;
11439 
11440   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11441     const Expr *MagicValueExpr = VD->getInit();
11442     if (!MagicValueExpr) {
11443       continue;
11444     }
11445     llvm::APSInt MagicValueInt;
11446     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11447       Diag(I->getRange().getBegin(),
11448            diag::err_type_tag_for_datatype_not_ice)
11449         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11450       continue;
11451     }
11452     if (MagicValueInt.getActiveBits() > 64) {
11453       Diag(I->getRange().getBegin(),
11454            diag::err_type_tag_for_datatype_too_large)
11455         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11456       continue;
11457     }
11458     uint64_t MagicValue = MagicValueInt.getZExtValue();
11459     RegisterTypeTagForDatatype(I->getArgumentKind(),
11460                                MagicValue,
11461                                I->getMatchingCType(),
11462                                I->getLayoutCompatible(),
11463                                I->getMustBeNull());
11464   }
11465 }
11466 
11467 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11468   auto *VD = dyn_cast<VarDecl>(DD);
11469   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11470 }
11471 
11472 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11473                                                    ArrayRef<Decl *> Group) {
11474   SmallVector<Decl*, 8> Decls;
11475 
11476   if (DS.isTypeSpecOwned())
11477     Decls.push_back(DS.getRepAsDecl());
11478 
11479   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11480   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11481   bool DiagnosedMultipleDecomps = false;
11482   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11483   bool DiagnosedNonDeducedAuto = false;
11484 
11485   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11486     if (Decl *D = Group[i]) {
11487       // For declarators, there are some additional syntactic-ish checks we need
11488       // to perform.
11489       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11490         if (!FirstDeclaratorInGroup)
11491           FirstDeclaratorInGroup = DD;
11492         if (!FirstDecompDeclaratorInGroup)
11493           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11494         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11495             !hasDeducedAuto(DD))
11496           FirstNonDeducedAutoInGroup = DD;
11497 
11498         if (FirstDeclaratorInGroup != DD) {
11499           // A decomposition declaration cannot be combined with any other
11500           // declaration in the same group.
11501           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11502             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11503                  diag::err_decomp_decl_not_alone)
11504                 << FirstDeclaratorInGroup->getSourceRange()
11505                 << DD->getSourceRange();
11506             DiagnosedMultipleDecomps = true;
11507           }
11508 
11509           // A declarator that uses 'auto' in any way other than to declare a
11510           // variable with a deduced type cannot be combined with any other
11511           // declarator in the same group.
11512           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11513             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11514                  diag::err_auto_non_deduced_not_alone)
11515                 << FirstNonDeducedAutoInGroup->getType()
11516                        ->hasAutoForTrailingReturnType()
11517                 << FirstDeclaratorInGroup->getSourceRange()
11518                 << DD->getSourceRange();
11519             DiagnosedNonDeducedAuto = true;
11520           }
11521         }
11522       }
11523 
11524       Decls.push_back(D);
11525     }
11526   }
11527 
11528   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11529     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11530       handleTagNumbering(Tag, S);
11531       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11532           getLangOpts().CPlusPlus)
11533         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11534     }
11535   }
11536 
11537   return BuildDeclaratorGroup(Decls);
11538 }
11539 
11540 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11541 /// group, performing any necessary semantic checking.
11542 Sema::DeclGroupPtrTy
11543 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11544   // C++14 [dcl.spec.auto]p7: (DR1347)
11545   //   If the type that replaces the placeholder type is not the same in each
11546   //   deduction, the program is ill-formed.
11547   if (Group.size() > 1) {
11548     QualType Deduced;
11549     VarDecl *DeducedDecl = nullptr;
11550     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11551       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11552       if (!D || D->isInvalidDecl())
11553         break;
11554       DeducedType *DT = D->getType()->getContainedDeducedType();
11555       if (!DT || DT->getDeducedType().isNull())
11556         continue;
11557       if (Deduced.isNull()) {
11558         Deduced = DT->getDeducedType();
11559         DeducedDecl = D;
11560       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11561         auto *AT = dyn_cast<AutoType>(DT);
11562         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11563              diag::err_auto_different_deductions)
11564           << (AT ? (unsigned)AT->getKeyword() : 3)
11565           << Deduced << DeducedDecl->getDeclName()
11566           << DT->getDeducedType() << D->getDeclName()
11567           << DeducedDecl->getInit()->getSourceRange()
11568           << D->getInit()->getSourceRange();
11569         D->setInvalidDecl();
11570         break;
11571       }
11572     }
11573   }
11574 
11575   ActOnDocumentableDecls(Group);
11576 
11577   return DeclGroupPtrTy::make(
11578       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11579 }
11580 
11581 void Sema::ActOnDocumentableDecl(Decl *D) {
11582   ActOnDocumentableDecls(D);
11583 }
11584 
11585 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11586   // Don't parse the comment if Doxygen diagnostics are ignored.
11587   if (Group.empty() || !Group[0])
11588     return;
11589 
11590   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11591                       Group[0]->getLocation()) &&
11592       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11593                       Group[0]->getLocation()))
11594     return;
11595 
11596   if (Group.size() >= 2) {
11597     // This is a decl group.  Normally it will contain only declarations
11598     // produced from declarator list.  But in case we have any definitions or
11599     // additional declaration references:
11600     //   'typedef struct S {} S;'
11601     //   'typedef struct S *S;'
11602     //   'struct S *pS;'
11603     // FinalizeDeclaratorGroup adds these as separate declarations.
11604     Decl *MaybeTagDecl = Group[0];
11605     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11606       Group = Group.slice(1);
11607     }
11608   }
11609 
11610   // See if there are any new comments that are not attached to a decl.
11611   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11612   if (!Comments.empty() &&
11613       !Comments.back()->isAttached()) {
11614     // There is at least one comment that not attached to a decl.
11615     // Maybe it should be attached to one of these decls?
11616     //
11617     // Note that this way we pick up not only comments that precede the
11618     // declaration, but also comments that *follow* the declaration -- thanks to
11619     // the lookahead in the lexer: we've consumed the semicolon and looked
11620     // ahead through comments.
11621     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11622       Context.getCommentForDecl(Group[i], &PP);
11623   }
11624 }
11625 
11626 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11627 /// to introduce parameters into function prototype scope.
11628 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11629   const DeclSpec &DS = D.getDeclSpec();
11630 
11631   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11632 
11633   // C++03 [dcl.stc]p2 also permits 'auto'.
11634   StorageClass SC = SC_None;
11635   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11636     SC = SC_Register;
11637   } else if (getLangOpts().CPlusPlus &&
11638              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11639     SC = SC_Auto;
11640   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11641     Diag(DS.getStorageClassSpecLoc(),
11642          diag::err_invalid_storage_class_in_func_decl);
11643     D.getMutableDeclSpec().ClearStorageClassSpecs();
11644   }
11645 
11646   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11647     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11648       << DeclSpec::getSpecifierName(TSCS);
11649   if (DS.isInlineSpecified())
11650     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11651         << getLangOpts().CPlusPlus1z;
11652   if (DS.isConstexprSpecified())
11653     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11654       << 0;
11655   if (DS.isConceptSpecified())
11656     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11657 
11658   DiagnoseFunctionSpecifiers(DS);
11659 
11660   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11661   QualType parmDeclType = TInfo->getType();
11662 
11663   if (getLangOpts().CPlusPlus) {
11664     // Check that there are no default arguments inside the type of this
11665     // parameter.
11666     CheckExtraCXXDefaultArguments(D);
11667 
11668     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11669     if (D.getCXXScopeSpec().isSet()) {
11670       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11671         << D.getCXXScopeSpec().getRange();
11672       D.getCXXScopeSpec().clear();
11673     }
11674   }
11675 
11676   // Ensure we have a valid name
11677   IdentifierInfo *II = nullptr;
11678   if (D.hasName()) {
11679     II = D.getIdentifier();
11680     if (!II) {
11681       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11682         << GetNameForDeclarator(D).getName();
11683       D.setInvalidType(true);
11684     }
11685   }
11686 
11687   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11688   if (II) {
11689     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11690                    ForRedeclaration);
11691     LookupName(R, S);
11692     if (R.isSingleResult()) {
11693       NamedDecl *PrevDecl = R.getFoundDecl();
11694       if (PrevDecl->isTemplateParameter()) {
11695         // Maybe we will complain about the shadowed template parameter.
11696         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11697         // Just pretend that we didn't see the previous declaration.
11698         PrevDecl = nullptr;
11699       } else if (S->isDeclScope(PrevDecl)) {
11700         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11701         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11702 
11703         // Recover by removing the name
11704         II = nullptr;
11705         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11706         D.setInvalidType(true);
11707       }
11708     }
11709   }
11710 
11711   // Temporarily put parameter variables in the translation unit, not
11712   // the enclosing context.  This prevents them from accidentally
11713   // looking like class members in C++.
11714   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11715                                     D.getLocStart(),
11716                                     D.getIdentifierLoc(), II,
11717                                     parmDeclType, TInfo,
11718                                     SC);
11719 
11720   if (D.isInvalidType())
11721     New->setInvalidDecl();
11722 
11723   assert(S->isFunctionPrototypeScope());
11724   assert(S->getFunctionPrototypeDepth() >= 1);
11725   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11726                     S->getNextFunctionPrototypeIndex());
11727 
11728   // Add the parameter declaration into this scope.
11729   S->AddDecl(New);
11730   if (II)
11731     IdResolver.AddDecl(New);
11732 
11733   ProcessDeclAttributes(S, New, D);
11734 
11735   if (D.getDeclSpec().isModulePrivateSpecified())
11736     Diag(New->getLocation(), diag::err_module_private_local)
11737       << 1 << New->getDeclName()
11738       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11739       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11740 
11741   if (New->hasAttr<BlocksAttr>()) {
11742     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11743   }
11744   return New;
11745 }
11746 
11747 /// \brief Synthesizes a variable for a parameter arising from a
11748 /// typedef.
11749 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11750                                               SourceLocation Loc,
11751                                               QualType T) {
11752   /* FIXME: setting StartLoc == Loc.
11753      Would it be worth to modify callers so as to provide proper source
11754      location for the unnamed parameters, embedding the parameter's type? */
11755   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11756                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11757                                            SC_None, nullptr);
11758   Param->setImplicit();
11759   return Param;
11760 }
11761 
11762 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11763   // Don't diagnose unused-parameter errors in template instantiations; we
11764   // will already have done so in the template itself.
11765   if (inTemplateInstantiation())
11766     return;
11767 
11768   for (const ParmVarDecl *Parameter : Parameters) {
11769     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11770         !Parameter->hasAttr<UnusedAttr>()) {
11771       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11772         << Parameter->getDeclName();
11773     }
11774   }
11775 }
11776 
11777 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11778     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11779   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11780     return;
11781 
11782   // Warn if the return value is pass-by-value and larger than the specified
11783   // threshold.
11784   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11785     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11786     if (Size > LangOpts.NumLargeByValueCopy)
11787       Diag(D->getLocation(), diag::warn_return_value_size)
11788           << D->getDeclName() << Size;
11789   }
11790 
11791   // Warn if any parameter is pass-by-value and larger than the specified
11792   // threshold.
11793   for (const ParmVarDecl *Parameter : Parameters) {
11794     QualType T = Parameter->getType();
11795     if (T->isDependentType() || !T.isPODType(Context))
11796       continue;
11797     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11798     if (Size > LangOpts.NumLargeByValueCopy)
11799       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11800           << Parameter->getDeclName() << Size;
11801   }
11802 }
11803 
11804 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11805                                   SourceLocation NameLoc, IdentifierInfo *Name,
11806                                   QualType T, TypeSourceInfo *TSInfo,
11807                                   StorageClass SC) {
11808   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11809   if (getLangOpts().ObjCAutoRefCount &&
11810       T.getObjCLifetime() == Qualifiers::OCL_None &&
11811       T->isObjCLifetimeType()) {
11812 
11813     Qualifiers::ObjCLifetime lifetime;
11814 
11815     // Special cases for arrays:
11816     //   - if it's const, use __unsafe_unretained
11817     //   - otherwise, it's an error
11818     if (T->isArrayType()) {
11819       if (!T.isConstQualified()) {
11820         DelayedDiagnostics.add(
11821             sema::DelayedDiagnostic::makeForbiddenType(
11822             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11823       }
11824       lifetime = Qualifiers::OCL_ExplicitNone;
11825     } else {
11826       lifetime = T->getObjCARCImplicitLifetime();
11827     }
11828     T = Context.getLifetimeQualifiedType(T, lifetime);
11829   }
11830 
11831   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11832                                          Context.getAdjustedParameterType(T),
11833                                          TSInfo, SC, nullptr);
11834 
11835   // Parameters can not be abstract class types.
11836   // For record types, this is done by the AbstractClassUsageDiagnoser once
11837   // the class has been completely parsed.
11838   if (!CurContext->isRecord() &&
11839       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11840                              AbstractParamType))
11841     New->setInvalidDecl();
11842 
11843   // Parameter declarators cannot be interface types. All ObjC objects are
11844   // passed by reference.
11845   if (T->isObjCObjectType()) {
11846     SourceLocation TypeEndLoc =
11847         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11848     Diag(NameLoc,
11849          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11850       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11851     T = Context.getObjCObjectPointerType(T);
11852     New->setType(T);
11853   }
11854 
11855   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11856   // duration shall not be qualified by an address-space qualifier."
11857   // Since all parameters have automatic store duration, they can not have
11858   // an address space.
11859   if (T.getAddressSpace() != 0) {
11860     // OpenCL allows function arguments declared to be an array of a type
11861     // to be qualified with an address space.
11862     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11863       Diag(NameLoc, diag::err_arg_with_address_space);
11864       New->setInvalidDecl();
11865     }
11866   }
11867 
11868   return New;
11869 }
11870 
11871 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11872                                            SourceLocation LocAfterDecls) {
11873   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11874 
11875   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11876   // for a K&R function.
11877   if (!FTI.hasPrototype) {
11878     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11879       --i;
11880       if (FTI.Params[i].Param == nullptr) {
11881         SmallString<256> Code;
11882         llvm::raw_svector_ostream(Code)
11883             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11884         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11885             << FTI.Params[i].Ident
11886             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11887 
11888         // Implicitly declare the argument as type 'int' for lack of a better
11889         // type.
11890         AttributeFactory attrs;
11891         DeclSpec DS(attrs);
11892         const char* PrevSpec; // unused
11893         unsigned DiagID; // unused
11894         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11895                            DiagID, Context.getPrintingPolicy());
11896         // Use the identifier location for the type source range.
11897         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11898         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11899         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11900         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11901         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11902       }
11903     }
11904   }
11905 }
11906 
11907 Decl *
11908 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11909                               MultiTemplateParamsArg TemplateParameterLists,
11910                               SkipBodyInfo *SkipBody) {
11911   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11912   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11913   Scope *ParentScope = FnBodyScope->getParent();
11914 
11915   D.setFunctionDefinitionKind(FDK_Definition);
11916   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11917   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11918 }
11919 
11920 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11921   Consumer.HandleInlineFunctionDefinition(D);
11922 }
11923 
11924 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11925                              const FunctionDecl*& PossibleZeroParamPrototype) {
11926   // Don't warn about invalid declarations.
11927   if (FD->isInvalidDecl())
11928     return false;
11929 
11930   // Or declarations that aren't global.
11931   if (!FD->isGlobal())
11932     return false;
11933 
11934   // Don't warn about C++ member functions.
11935   if (isa<CXXMethodDecl>(FD))
11936     return false;
11937 
11938   // Don't warn about 'main'.
11939   if (FD->isMain())
11940     return false;
11941 
11942   // Don't warn about inline functions.
11943   if (FD->isInlined())
11944     return false;
11945 
11946   // Don't warn about function templates.
11947   if (FD->getDescribedFunctionTemplate())
11948     return false;
11949 
11950   // Don't warn about function template specializations.
11951   if (FD->isFunctionTemplateSpecialization())
11952     return false;
11953 
11954   // Don't warn for OpenCL kernels.
11955   if (FD->hasAttr<OpenCLKernelAttr>())
11956     return false;
11957 
11958   // Don't warn on explicitly deleted functions.
11959   if (FD->isDeleted())
11960     return false;
11961 
11962   bool MissingPrototype = true;
11963   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11964        Prev; Prev = Prev->getPreviousDecl()) {
11965     // Ignore any declarations that occur in function or method
11966     // scope, because they aren't visible from the header.
11967     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11968       continue;
11969 
11970     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11971     if (FD->getNumParams() == 0)
11972       PossibleZeroParamPrototype = Prev;
11973     break;
11974   }
11975 
11976   return MissingPrototype;
11977 }
11978 
11979 void
11980 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11981                                    const FunctionDecl *EffectiveDefinition,
11982                                    SkipBodyInfo *SkipBody) {
11983   const FunctionDecl *Definition = EffectiveDefinition;
11984   if (!Definition)
11985     if (!FD->isDefined(Definition))
11986       return;
11987 
11988   if (canRedefineFunction(Definition, getLangOpts()))
11989     return;
11990 
11991   // Don't emit an error when this is redefinition of a typo-corrected
11992   // definition.
11993   if (TypoCorrectedFunctionDefinitions.count(Definition))
11994     return;
11995 
11996   // If we don't have a visible definition of the function, and it's inline or
11997   // a template, skip the new definition.
11998   if (SkipBody && !hasVisibleDefinition(Definition) &&
11999       (Definition->getFormalLinkage() == InternalLinkage ||
12000        Definition->isInlined() ||
12001        Definition->getDescribedFunctionTemplate() ||
12002        Definition->getNumTemplateParameterLists())) {
12003     SkipBody->ShouldSkip = true;
12004     if (auto *TD = Definition->getDescribedFunctionTemplate())
12005       makeMergedDefinitionVisible(TD);
12006     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12007     return;
12008   }
12009 
12010   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12011       Definition->getStorageClass() == SC_Extern)
12012     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12013         << FD->getDeclName() << getLangOpts().CPlusPlus;
12014   else
12015     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12016 
12017   Diag(Definition->getLocation(), diag::note_previous_definition);
12018   FD->setInvalidDecl();
12019 }
12020 
12021 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12022                                    Sema &S) {
12023   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12024 
12025   LambdaScopeInfo *LSI = S.PushLambdaScope();
12026   LSI->CallOperator = CallOperator;
12027   LSI->Lambda = LambdaClass;
12028   LSI->ReturnType = CallOperator->getReturnType();
12029   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12030 
12031   if (LCD == LCD_None)
12032     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12033   else if (LCD == LCD_ByCopy)
12034     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12035   else if (LCD == LCD_ByRef)
12036     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12037   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12038 
12039   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12040   LSI->Mutable = !CallOperator->isConst();
12041 
12042   // Add the captures to the LSI so they can be noted as already
12043   // captured within tryCaptureVar.
12044   auto I = LambdaClass->field_begin();
12045   for (const auto &C : LambdaClass->captures()) {
12046     if (C.capturesVariable()) {
12047       VarDecl *VD = C.getCapturedVar();
12048       if (VD->isInitCapture())
12049         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12050       QualType CaptureType = VD->getType();
12051       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12052       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12053           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12054           /*EllipsisLoc*/C.isPackExpansion()
12055                          ? C.getEllipsisLoc() : SourceLocation(),
12056           CaptureType, /*Expr*/ nullptr);
12057 
12058     } else if (C.capturesThis()) {
12059       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12060                               /*Expr*/ nullptr,
12061                               C.getCaptureKind() == LCK_StarThis);
12062     } else {
12063       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12064     }
12065     ++I;
12066   }
12067 }
12068 
12069 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12070                                     SkipBodyInfo *SkipBody) {
12071   if (!D)
12072     return D;
12073   FunctionDecl *FD = nullptr;
12074 
12075   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12076     FD = FunTmpl->getTemplatedDecl();
12077   else
12078     FD = cast<FunctionDecl>(D);
12079 
12080   // Check for defining attributes before the check for redefinition.
12081   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12082     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12083     FD->dropAttr<AliasAttr>();
12084     FD->setInvalidDecl();
12085   }
12086   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12087     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12088     FD->dropAttr<IFuncAttr>();
12089     FD->setInvalidDecl();
12090   }
12091 
12092   // See if this is a redefinition. If 'will have body' is already set, then
12093   // these checks were already performed when it was set.
12094   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12095     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12096 
12097     // If we're skipping the body, we're done. Don't enter the scope.
12098     if (SkipBody && SkipBody->ShouldSkip)
12099       return D;
12100   }
12101 
12102   // Mark this function as "will have a body eventually".  This lets users to
12103   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12104   // this function.
12105   FD->setWillHaveBody();
12106 
12107   // If we are instantiating a generic lambda call operator, push
12108   // a LambdaScopeInfo onto the function stack.  But use the information
12109   // that's already been calculated (ActOnLambdaExpr) to prime the current
12110   // LambdaScopeInfo.
12111   // When the template operator is being specialized, the LambdaScopeInfo,
12112   // has to be properly restored so that tryCaptureVariable doesn't try
12113   // and capture any new variables. In addition when calculating potential
12114   // captures during transformation of nested lambdas, it is necessary to
12115   // have the LSI properly restored.
12116   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12117     assert(inTemplateInstantiation() &&
12118            "There should be an active template instantiation on the stack "
12119            "when instantiating a generic lambda!");
12120     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12121   } else {
12122     // Enter a new function scope
12123     PushFunctionScope();
12124   }
12125 
12126   // Builtin functions cannot be defined.
12127   if (unsigned BuiltinID = FD->getBuiltinID()) {
12128     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12129         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12130       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12131       FD->setInvalidDecl();
12132     }
12133   }
12134 
12135   // The return type of a function definition must be complete
12136   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12137   QualType ResultType = FD->getReturnType();
12138   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12139       !FD->isInvalidDecl() &&
12140       RequireCompleteType(FD->getLocation(), ResultType,
12141                           diag::err_func_def_incomplete_result))
12142     FD->setInvalidDecl();
12143 
12144   if (FnBodyScope)
12145     PushDeclContext(FnBodyScope, FD);
12146 
12147   // Check the validity of our function parameters
12148   CheckParmsForFunctionDef(FD->parameters(),
12149                            /*CheckParameterNames=*/true);
12150 
12151   // Add non-parameter declarations already in the function to the current
12152   // scope.
12153   if (FnBodyScope) {
12154     for (Decl *NPD : FD->decls()) {
12155       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12156       if (!NonParmDecl)
12157         continue;
12158       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12159              "parameters should not be in newly created FD yet");
12160 
12161       // If the decl has a name, make it accessible in the current scope.
12162       if (NonParmDecl->getDeclName())
12163         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12164 
12165       // Similarly, dive into enums and fish their constants out, making them
12166       // accessible in this scope.
12167       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12168         for (auto *EI : ED->enumerators())
12169           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12170       }
12171     }
12172   }
12173 
12174   // Introduce our parameters into the function scope
12175   for (auto Param : FD->parameters()) {
12176     Param->setOwningFunction(FD);
12177 
12178     // If this has an identifier, add it to the scope stack.
12179     if (Param->getIdentifier() && FnBodyScope) {
12180       CheckShadow(FnBodyScope, Param);
12181 
12182       PushOnScopeChains(Param, FnBodyScope);
12183     }
12184   }
12185 
12186   // Ensure that the function's exception specification is instantiated.
12187   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12188     ResolveExceptionSpec(D->getLocation(), FPT);
12189 
12190   // dllimport cannot be applied to non-inline function definitions.
12191   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12192       !FD->isTemplateInstantiation()) {
12193     assert(!FD->hasAttr<DLLExportAttr>());
12194     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12195     FD->setInvalidDecl();
12196     return D;
12197   }
12198   // We want to attach documentation to original Decl (which might be
12199   // a function template).
12200   ActOnDocumentableDecl(D);
12201   if (getCurLexicalContext()->isObjCContainer() &&
12202       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12203       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12204     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12205 
12206   return D;
12207 }
12208 
12209 /// \brief Given the set of return statements within a function body,
12210 /// compute the variables that are subject to the named return value
12211 /// optimization.
12212 ///
12213 /// Each of the variables that is subject to the named return value
12214 /// optimization will be marked as NRVO variables in the AST, and any
12215 /// return statement that has a marked NRVO variable as its NRVO candidate can
12216 /// use the named return value optimization.
12217 ///
12218 /// This function applies a very simplistic algorithm for NRVO: if every return
12219 /// statement in the scope of a variable has the same NRVO candidate, that
12220 /// candidate is an NRVO variable.
12221 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12222   ReturnStmt **Returns = Scope->Returns.data();
12223 
12224   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12225     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12226       if (!NRVOCandidate->isNRVOVariable())
12227         Returns[I]->setNRVOCandidate(nullptr);
12228     }
12229   }
12230 }
12231 
12232 bool Sema::canDelayFunctionBody(const Declarator &D) {
12233   // We can't delay parsing the body of a constexpr function template (yet).
12234   if (D.getDeclSpec().isConstexprSpecified())
12235     return false;
12236 
12237   // We can't delay parsing the body of a function template with a deduced
12238   // return type (yet).
12239   if (D.getDeclSpec().hasAutoTypeSpec()) {
12240     // If the placeholder introduces a non-deduced trailing return type,
12241     // we can still delay parsing it.
12242     if (D.getNumTypeObjects()) {
12243       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12244       if (Outer.Kind == DeclaratorChunk::Function &&
12245           Outer.Fun.hasTrailingReturnType()) {
12246         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12247         return Ty.isNull() || !Ty->isUndeducedType();
12248       }
12249     }
12250     return false;
12251   }
12252 
12253   return true;
12254 }
12255 
12256 bool Sema::canSkipFunctionBody(Decl *D) {
12257   // We cannot skip the body of a function (or function template) which is
12258   // constexpr, since we may need to evaluate its body in order to parse the
12259   // rest of the file.
12260   // We cannot skip the body of a function with an undeduced return type,
12261   // because any callers of that function need to know the type.
12262   if (const FunctionDecl *FD = D->getAsFunction())
12263     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12264       return false;
12265   return Consumer.shouldSkipFunctionBody(D);
12266 }
12267 
12268 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12269   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12270     FD->setHasSkippedBody();
12271   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12272     MD->setHasSkippedBody();
12273   return Decl;
12274 }
12275 
12276 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12277   return ActOnFinishFunctionBody(D, BodyArg, false);
12278 }
12279 
12280 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12281                                     bool IsInstantiation) {
12282   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12283 
12284   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12285   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12286 
12287   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12288     CheckCompletedCoroutineBody(FD, Body);
12289 
12290   if (FD) {
12291     FD->setBody(Body);
12292     FD->setWillHaveBody(false);
12293 
12294     if (getLangOpts().CPlusPlus14) {
12295       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12296           FD->getReturnType()->isUndeducedType()) {
12297         // If the function has a deduced result type but contains no 'return'
12298         // statements, the result type as written must be exactly 'auto', and
12299         // the deduced result type is 'void'.
12300         if (!FD->getReturnType()->getAs<AutoType>()) {
12301           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12302               << FD->getReturnType();
12303           FD->setInvalidDecl();
12304         } else {
12305           // Substitute 'void' for the 'auto' in the type.
12306           TypeLoc ResultType = getReturnTypeLoc(FD);
12307           Context.adjustDeducedFunctionResultType(
12308               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12309         }
12310       }
12311     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12312       // In C++11, we don't use 'auto' deduction rules for lambda call
12313       // operators because we don't support return type deduction.
12314       auto *LSI = getCurLambda();
12315       if (LSI->HasImplicitReturnType) {
12316         deduceClosureReturnType(*LSI);
12317 
12318         // C++11 [expr.prim.lambda]p4:
12319         //   [...] if there are no return statements in the compound-statement
12320         //   [the deduced type is] the type void
12321         QualType RetType =
12322             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12323 
12324         // Update the return type to the deduced type.
12325         const FunctionProtoType *Proto =
12326             FD->getType()->getAs<FunctionProtoType>();
12327         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12328                                             Proto->getExtProtoInfo()));
12329       }
12330     }
12331 
12332     // The only way to be included in UndefinedButUsed is if there is an
12333     // ODR use before the definition. Avoid the expensive map lookup if this
12334     // is the first declaration.
12335     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12336       if (!FD->isExternallyVisible())
12337         UndefinedButUsed.erase(FD);
12338       else if (FD->isInlined() &&
12339                !LangOpts.GNUInline &&
12340                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12341         UndefinedButUsed.erase(FD);
12342     }
12343 
12344     // If the function implicitly returns zero (like 'main') or is naked,
12345     // don't complain about missing return statements.
12346     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12347       WP.disableCheckFallThrough();
12348 
12349     // MSVC permits the use of pure specifier (=0) on function definition,
12350     // defined at class scope, warn about this non-standard construct.
12351     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12352       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12353 
12354     if (!FD->isInvalidDecl()) {
12355       // Don't diagnose unused parameters of defaulted or deleted functions.
12356       if (!FD->isDeleted() && !FD->isDefaulted())
12357         DiagnoseUnusedParameters(FD->parameters());
12358       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12359                                              FD->getReturnType(), FD);
12360 
12361       // If this is a structor, we need a vtable.
12362       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12363         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12364       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12365         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12366 
12367       // Try to apply the named return value optimization. We have to check
12368       // if we can do this here because lambdas keep return statements around
12369       // to deduce an implicit return type.
12370       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12371           !FD->isDependentContext())
12372         computeNRVO(Body, getCurFunction());
12373     }
12374 
12375     // GNU warning -Wmissing-prototypes:
12376     //   Warn if a global function is defined without a previous
12377     //   prototype declaration. This warning is issued even if the
12378     //   definition itself provides a prototype. The aim is to detect
12379     //   global functions that fail to be declared in header files.
12380     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12381     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12382       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12383 
12384       if (PossibleZeroParamPrototype) {
12385         // We found a declaration that is not a prototype,
12386         // but that could be a zero-parameter prototype
12387         if (TypeSourceInfo *TI =
12388                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12389           TypeLoc TL = TI->getTypeLoc();
12390           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12391             Diag(PossibleZeroParamPrototype->getLocation(),
12392                  diag::note_declaration_not_a_prototype)
12393                 << PossibleZeroParamPrototype
12394                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12395         }
12396       }
12397 
12398       // GNU warning -Wstrict-prototypes
12399       //   Warn if K&R function is defined without a previous declaration.
12400       //   This warning is issued only if the definition itself does not provide
12401       //   a prototype. Only K&R definitions do not provide a prototype.
12402       //   An empty list in a function declarator that is part of a definition
12403       //   of that function specifies that the function has no parameters
12404       //   (C99 6.7.5.3p14)
12405       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12406           !LangOpts.CPlusPlus) {
12407         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12408         TypeLoc TL = TI->getTypeLoc();
12409         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12410         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12411       }
12412     }
12413 
12414     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12415       const CXXMethodDecl *KeyFunction;
12416       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12417           MD->isVirtual() &&
12418           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12419           MD == KeyFunction->getCanonicalDecl()) {
12420         // Update the key-function state if necessary for this ABI.
12421         if (FD->isInlined() &&
12422             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12423           Context.setNonKeyFunction(MD);
12424 
12425           // If the newly-chosen key function is already defined, then we
12426           // need to mark the vtable as used retroactively.
12427           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12428           const FunctionDecl *Definition;
12429           if (KeyFunction && KeyFunction->isDefined(Definition))
12430             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12431         } else {
12432           // We just defined they key function; mark the vtable as used.
12433           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12434         }
12435       }
12436     }
12437 
12438     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12439            "Function parsing confused");
12440   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12441     assert(MD == getCurMethodDecl() && "Method parsing confused");
12442     MD->setBody(Body);
12443     if (!MD->isInvalidDecl()) {
12444       DiagnoseUnusedParameters(MD->parameters());
12445       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12446                                              MD->getReturnType(), MD);
12447 
12448       if (Body)
12449         computeNRVO(Body, getCurFunction());
12450     }
12451     if (getCurFunction()->ObjCShouldCallSuper) {
12452       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12453         << MD->getSelector().getAsString();
12454       getCurFunction()->ObjCShouldCallSuper = false;
12455     }
12456     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12457       const ObjCMethodDecl *InitMethod = nullptr;
12458       bool isDesignated =
12459           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12460       assert(isDesignated && InitMethod);
12461       (void)isDesignated;
12462 
12463       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12464         auto IFace = MD->getClassInterface();
12465         if (!IFace)
12466           return false;
12467         auto SuperD = IFace->getSuperClass();
12468         if (!SuperD)
12469           return false;
12470         return SuperD->getIdentifier() ==
12471             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12472       };
12473       // Don't issue this warning for unavailable inits or direct subclasses
12474       // of NSObject.
12475       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12476         Diag(MD->getLocation(),
12477              diag::warn_objc_designated_init_missing_super_call);
12478         Diag(InitMethod->getLocation(),
12479              diag::note_objc_designated_init_marked_here);
12480       }
12481       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12482     }
12483     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12484       // Don't issue this warning for unavaialable inits.
12485       if (!MD->isUnavailable())
12486         Diag(MD->getLocation(),
12487              diag::warn_objc_secondary_init_missing_init_call);
12488       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12489     }
12490   } else {
12491     return nullptr;
12492   }
12493 
12494   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12495     DiagnoseUnguardedAvailabilityViolations(dcl);
12496 
12497   assert(!getCurFunction()->ObjCShouldCallSuper &&
12498          "This should only be set for ObjC methods, which should have been "
12499          "handled in the block above.");
12500 
12501   // Verify and clean out per-function state.
12502   if (Body && (!FD || !FD->isDefaulted())) {
12503     // C++ constructors that have function-try-blocks can't have return
12504     // statements in the handlers of that block. (C++ [except.handle]p14)
12505     // Verify this.
12506     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12507       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12508 
12509     // Verify that gotos and switch cases don't jump into scopes illegally.
12510     if (getCurFunction()->NeedsScopeChecking() &&
12511         !PP.isCodeCompletionEnabled())
12512       DiagnoseInvalidJumps(Body);
12513 
12514     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12515       if (!Destructor->getParent()->isDependentType())
12516         CheckDestructor(Destructor);
12517 
12518       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12519                                              Destructor->getParent());
12520     }
12521 
12522     // If any errors have occurred, clear out any temporaries that may have
12523     // been leftover. This ensures that these temporaries won't be picked up for
12524     // deletion in some later function.
12525     if (getDiagnostics().hasErrorOccurred() ||
12526         getDiagnostics().getSuppressAllDiagnostics()) {
12527       DiscardCleanupsInEvaluationContext();
12528     }
12529     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12530         !isa<FunctionTemplateDecl>(dcl)) {
12531       // Since the body is valid, issue any analysis-based warnings that are
12532       // enabled.
12533       ActivePolicy = &WP;
12534     }
12535 
12536     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12537         (!CheckConstexprFunctionDecl(FD) ||
12538          !CheckConstexprFunctionBody(FD, Body)))
12539       FD->setInvalidDecl();
12540 
12541     if (FD && FD->hasAttr<NakedAttr>()) {
12542       for (const Stmt *S : Body->children()) {
12543         // Allow local register variables without initializer as they don't
12544         // require prologue.
12545         bool RegisterVariables = false;
12546         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12547           for (const auto *Decl : DS->decls()) {
12548             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12549               RegisterVariables =
12550                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12551               if (!RegisterVariables)
12552                 break;
12553             }
12554           }
12555         }
12556         if (RegisterVariables)
12557           continue;
12558         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12559           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12560           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12561           FD->setInvalidDecl();
12562           break;
12563         }
12564       }
12565     }
12566 
12567     assert(ExprCleanupObjects.size() ==
12568                ExprEvalContexts.back().NumCleanupObjects &&
12569            "Leftover temporaries in function");
12570     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12571     assert(MaybeODRUseExprs.empty() &&
12572            "Leftover expressions for odr-use checking");
12573   }
12574 
12575   if (!IsInstantiation)
12576     PopDeclContext();
12577 
12578   PopFunctionScopeInfo(ActivePolicy, dcl);
12579   // If any errors have occurred, clear out any temporaries that may have
12580   // been leftover. This ensures that these temporaries won't be picked up for
12581   // deletion in some later function.
12582   if (getDiagnostics().hasErrorOccurred()) {
12583     DiscardCleanupsInEvaluationContext();
12584   }
12585 
12586   return dcl;
12587 }
12588 
12589 /// When we finish delayed parsing of an attribute, we must attach it to the
12590 /// relevant Decl.
12591 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12592                                        ParsedAttributes &Attrs) {
12593   // Always attach attributes to the underlying decl.
12594   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12595     D = TD->getTemplatedDecl();
12596   ProcessDeclAttributeList(S, D, Attrs.getList());
12597 
12598   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12599     if (Method->isStatic())
12600       checkThisInStaticMemberFunctionAttributes(Method);
12601 }
12602 
12603 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12604 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12605 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12606                                           IdentifierInfo &II, Scope *S) {
12607   // Before we produce a declaration for an implicitly defined
12608   // function, see whether there was a locally-scoped declaration of
12609   // this name as a function or variable. If so, use that
12610   // (non-visible) declaration, and complain about it.
12611   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12612     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12613     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12614     return ExternCPrev;
12615   }
12616 
12617   // Extension in C99.  Legal in C90, but warn about it.
12618   unsigned diag_id;
12619   if (II.getName().startswith("__builtin_"))
12620     diag_id = diag::warn_builtin_unknown;
12621   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12622   else if (getLangOpts().OpenCL)
12623     diag_id = diag::err_opencl_implicit_function_decl;
12624   else if (getLangOpts().C99)
12625     diag_id = diag::ext_implicit_function_decl;
12626   else
12627     diag_id = diag::warn_implicit_function_decl;
12628   Diag(Loc, diag_id) << &II;
12629 
12630   // Because typo correction is expensive, only do it if the implicit
12631   // function declaration is going to be treated as an error.
12632   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12633     TypoCorrection Corrected;
12634     if (S &&
12635         (Corrected = CorrectTypo(
12636              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12637              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12638       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12639                    /*ErrorRecovery*/false);
12640   }
12641 
12642   // Set a Declarator for the implicit definition: int foo();
12643   const char *Dummy;
12644   AttributeFactory attrFactory;
12645   DeclSpec DS(attrFactory);
12646   unsigned DiagID;
12647   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12648                                   Context.getPrintingPolicy());
12649   (void)Error; // Silence warning.
12650   assert(!Error && "Error setting up implicit decl!");
12651   SourceLocation NoLoc;
12652   Declarator D(DS, Declarator::BlockContext);
12653   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12654                                              /*IsAmbiguous=*/false,
12655                                              /*LParenLoc=*/NoLoc,
12656                                              /*Params=*/nullptr,
12657                                              /*NumParams=*/0,
12658                                              /*EllipsisLoc=*/NoLoc,
12659                                              /*RParenLoc=*/NoLoc,
12660                                              /*TypeQuals=*/0,
12661                                              /*RefQualifierIsLvalueRef=*/true,
12662                                              /*RefQualifierLoc=*/NoLoc,
12663                                              /*ConstQualifierLoc=*/NoLoc,
12664                                              /*VolatileQualifierLoc=*/NoLoc,
12665                                              /*RestrictQualifierLoc=*/NoLoc,
12666                                              /*MutableLoc=*/NoLoc,
12667                                              EST_None,
12668                                              /*ESpecRange=*/SourceRange(),
12669                                              /*Exceptions=*/nullptr,
12670                                              /*ExceptionRanges=*/nullptr,
12671                                              /*NumExceptions=*/0,
12672                                              /*NoexceptExpr=*/nullptr,
12673                                              /*ExceptionSpecTokens=*/nullptr,
12674                                              /*DeclsInPrototype=*/None,
12675                                              Loc, Loc, D),
12676                 DS.getAttributes(),
12677                 SourceLocation());
12678   D.SetIdentifier(&II, Loc);
12679 
12680   // Insert this function into the enclosing block scope.
12681   while (S && !S->isCompoundStmtScope())
12682     S = S->getParent();
12683   if (S == nullptr)
12684     S = TUScope;
12685 
12686   DeclContext *PrevDC = CurContext;
12687   CurContext = Context.getTranslationUnitDecl();
12688 
12689   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(S, D));
12690   FD->setImplicit();
12691 
12692   CurContext = PrevDC;
12693 
12694   AddKnownFunctionAttributes(FD);
12695 
12696   return FD;
12697 }
12698 
12699 /// \brief Adds any function attributes that we know a priori based on
12700 /// the declaration of this function.
12701 ///
12702 /// These attributes can apply both to implicitly-declared builtins
12703 /// (like __builtin___printf_chk) or to library-declared functions
12704 /// like NSLog or printf.
12705 ///
12706 /// We need to check for duplicate attributes both here and where user-written
12707 /// attributes are applied to declarations.
12708 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12709   if (FD->isInvalidDecl())
12710     return;
12711 
12712   // If this is a built-in function, map its builtin attributes to
12713   // actual attributes.
12714   if (unsigned BuiltinID = FD->getBuiltinID()) {
12715     // Handle printf-formatting attributes.
12716     unsigned FormatIdx;
12717     bool HasVAListArg;
12718     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12719       if (!FD->hasAttr<FormatAttr>()) {
12720         const char *fmt = "printf";
12721         unsigned int NumParams = FD->getNumParams();
12722         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12723             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12724           fmt = "NSString";
12725         FD->addAttr(FormatAttr::CreateImplicit(Context,
12726                                                &Context.Idents.get(fmt),
12727                                                FormatIdx+1,
12728                                                HasVAListArg ? 0 : FormatIdx+2,
12729                                                FD->getLocation()));
12730       }
12731     }
12732     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12733                                              HasVAListArg)) {
12734      if (!FD->hasAttr<FormatAttr>())
12735        FD->addAttr(FormatAttr::CreateImplicit(Context,
12736                                               &Context.Idents.get("scanf"),
12737                                               FormatIdx+1,
12738                                               HasVAListArg ? 0 : FormatIdx+2,
12739                                               FD->getLocation()));
12740     }
12741 
12742     // Mark const if we don't care about errno and that is the only
12743     // thing preventing the function from being const. This allows
12744     // IRgen to use LLVM intrinsics for such functions.
12745     if (!getLangOpts().MathErrno &&
12746         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12747       if (!FD->hasAttr<ConstAttr>())
12748         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12749     }
12750 
12751     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12752         !FD->hasAttr<ReturnsTwiceAttr>())
12753       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12754                                          FD->getLocation()));
12755     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12756       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12757     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12758       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12759     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12760       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12761     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12762         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12763       // Add the appropriate attribute, depending on the CUDA compilation mode
12764       // and which target the builtin belongs to. For example, during host
12765       // compilation, aux builtins are __device__, while the rest are __host__.
12766       if (getLangOpts().CUDAIsDevice !=
12767           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12768         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12769       else
12770         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12771     }
12772   }
12773 
12774   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12775   // throw, add an implicit nothrow attribute to any extern "C" function we come
12776   // across.
12777   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12778       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12779     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12780     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12781       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12782   }
12783 
12784   IdentifierInfo *Name = FD->getIdentifier();
12785   if (!Name)
12786     return;
12787   if ((!getLangOpts().CPlusPlus &&
12788        FD->getDeclContext()->isTranslationUnit()) ||
12789       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12790        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12791        LinkageSpecDecl::lang_c)) {
12792     // Okay: this could be a libc/libm/Objective-C function we know
12793     // about.
12794   } else
12795     return;
12796 
12797   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12798     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12799     // target-specific builtins, perhaps?
12800     if (!FD->hasAttr<FormatAttr>())
12801       FD->addAttr(FormatAttr::CreateImplicit(Context,
12802                                              &Context.Idents.get("printf"), 2,
12803                                              Name->isStr("vasprintf") ? 0 : 3,
12804                                              FD->getLocation()));
12805   }
12806 
12807   if (Name->isStr("__CFStringMakeConstantString")) {
12808     // We already have a __builtin___CFStringMakeConstantString,
12809     // but builds that use -fno-constant-cfstrings don't go through that.
12810     if (!FD->hasAttr<FormatArgAttr>())
12811       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12812                                                 FD->getLocation()));
12813   }
12814 }
12815 
12816 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12817                                     TypeSourceInfo *TInfo) {
12818   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12819   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12820 
12821   if (!TInfo) {
12822     assert(D.isInvalidType() && "no declarator info for valid type");
12823     TInfo = Context.getTrivialTypeSourceInfo(T);
12824   }
12825 
12826   // Scope manipulation handled by caller.
12827   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12828                                            D.getLocStart(),
12829                                            D.getIdentifierLoc(),
12830                                            D.getIdentifier(),
12831                                            TInfo);
12832 
12833   // Bail out immediately if we have an invalid declaration.
12834   if (D.isInvalidType()) {
12835     NewTD->setInvalidDecl();
12836     return NewTD;
12837   }
12838 
12839   if (D.getDeclSpec().isModulePrivateSpecified()) {
12840     if (CurContext->isFunctionOrMethod())
12841       Diag(NewTD->getLocation(), diag::err_module_private_local)
12842         << 2 << NewTD->getDeclName()
12843         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12844         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12845     else
12846       NewTD->setModulePrivate();
12847   }
12848 
12849   // C++ [dcl.typedef]p8:
12850   //   If the typedef declaration defines an unnamed class (or
12851   //   enum), the first typedef-name declared by the declaration
12852   //   to be that class type (or enum type) is used to denote the
12853   //   class type (or enum type) for linkage purposes only.
12854   // We need to check whether the type was declared in the declaration.
12855   switch (D.getDeclSpec().getTypeSpecType()) {
12856   case TST_enum:
12857   case TST_struct:
12858   case TST_interface:
12859   case TST_union:
12860   case TST_class: {
12861     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12862     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12863     break;
12864   }
12865 
12866   default:
12867     break;
12868   }
12869 
12870   return NewTD;
12871 }
12872 
12873 /// \brief Check that this is a valid underlying type for an enum declaration.
12874 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12875   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12876   QualType T = TI->getType();
12877 
12878   if (T->isDependentType())
12879     return false;
12880 
12881   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12882     if (BT->isInteger())
12883       return false;
12884 
12885   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12886   return true;
12887 }
12888 
12889 /// Check whether this is a valid redeclaration of a previous enumeration.
12890 /// \return true if the redeclaration was invalid.
12891 bool Sema::CheckEnumRedeclaration(
12892     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12893     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12894   bool IsFixed = !EnumUnderlyingTy.isNull();
12895 
12896   if (IsScoped != Prev->isScoped()) {
12897     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12898       << Prev->isScoped();
12899     Diag(Prev->getLocation(), diag::note_previous_declaration);
12900     return true;
12901   }
12902 
12903   if (IsFixed && Prev->isFixed()) {
12904     if (!EnumUnderlyingTy->isDependentType() &&
12905         !Prev->getIntegerType()->isDependentType() &&
12906         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12907                                         Prev->getIntegerType())) {
12908       // TODO: Highlight the underlying type of the redeclaration.
12909       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12910         << EnumUnderlyingTy << Prev->getIntegerType();
12911       Diag(Prev->getLocation(), diag::note_previous_declaration)
12912           << Prev->getIntegerTypeRange();
12913       return true;
12914     }
12915   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12916     ;
12917   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12918     ;
12919   } else if (IsFixed != Prev->isFixed()) {
12920     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12921       << Prev->isFixed();
12922     Diag(Prev->getLocation(), diag::note_previous_declaration);
12923     return true;
12924   }
12925 
12926   return false;
12927 }
12928 
12929 /// \brief Get diagnostic %select index for tag kind for
12930 /// redeclaration diagnostic message.
12931 /// WARNING: Indexes apply to particular diagnostics only!
12932 ///
12933 /// \returns diagnostic %select index.
12934 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12935   switch (Tag) {
12936   case TTK_Struct: return 0;
12937   case TTK_Interface: return 1;
12938   case TTK_Class:  return 2;
12939   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12940   }
12941 }
12942 
12943 /// \brief Determine if tag kind is a class-key compatible with
12944 /// class for redeclaration (class, struct, or __interface).
12945 ///
12946 /// \returns true iff the tag kind is compatible.
12947 static bool isClassCompatTagKind(TagTypeKind Tag)
12948 {
12949   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12950 }
12951 
12952 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12953                                              TagTypeKind TTK) {
12954   if (isa<TypedefDecl>(PrevDecl))
12955     return NTK_Typedef;
12956   else if (isa<TypeAliasDecl>(PrevDecl))
12957     return NTK_TypeAlias;
12958   else if (isa<ClassTemplateDecl>(PrevDecl))
12959     return NTK_Template;
12960   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12961     return NTK_TypeAliasTemplate;
12962   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12963     return NTK_TemplateTemplateArgument;
12964   switch (TTK) {
12965   case TTK_Struct:
12966   case TTK_Interface:
12967   case TTK_Class:
12968     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12969   case TTK_Union:
12970     return NTK_NonUnion;
12971   case TTK_Enum:
12972     return NTK_NonEnum;
12973   }
12974   llvm_unreachable("invalid TTK");
12975 }
12976 
12977 /// \brief Determine whether a tag with a given kind is acceptable
12978 /// as a redeclaration of the given tag declaration.
12979 ///
12980 /// \returns true if the new tag kind is acceptable, false otherwise.
12981 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12982                                         TagTypeKind NewTag, bool isDefinition,
12983                                         SourceLocation NewTagLoc,
12984                                         const IdentifierInfo *Name) {
12985   // C++ [dcl.type.elab]p3:
12986   //   The class-key or enum keyword present in the
12987   //   elaborated-type-specifier shall agree in kind with the
12988   //   declaration to which the name in the elaborated-type-specifier
12989   //   refers. This rule also applies to the form of
12990   //   elaborated-type-specifier that declares a class-name or
12991   //   friend class since it can be construed as referring to the
12992   //   definition of the class. Thus, in any
12993   //   elaborated-type-specifier, the enum keyword shall be used to
12994   //   refer to an enumeration (7.2), the union class-key shall be
12995   //   used to refer to a union (clause 9), and either the class or
12996   //   struct class-key shall be used to refer to a class (clause 9)
12997   //   declared using the class or struct class-key.
12998   TagTypeKind OldTag = Previous->getTagKind();
12999   if (!isDefinition || !isClassCompatTagKind(NewTag))
13000     if (OldTag == NewTag)
13001       return true;
13002 
13003   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13004     // Warn about the struct/class tag mismatch.
13005     bool isTemplate = false;
13006     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13007       isTemplate = Record->getDescribedClassTemplate();
13008 
13009     if (inTemplateInstantiation()) {
13010       // In a template instantiation, do not offer fix-its for tag mismatches
13011       // since they usually mess up the template instead of fixing the problem.
13012       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13013         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13014         << getRedeclDiagFromTagKind(OldTag);
13015       return true;
13016     }
13017 
13018     if (isDefinition) {
13019       // On definitions, check previous tags and issue a fix-it for each
13020       // one that doesn't match the current tag.
13021       if (Previous->getDefinition()) {
13022         // Don't suggest fix-its for redefinitions.
13023         return true;
13024       }
13025 
13026       bool previousMismatch = false;
13027       for (auto I : Previous->redecls()) {
13028         if (I->getTagKind() != NewTag) {
13029           if (!previousMismatch) {
13030             previousMismatch = true;
13031             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13032               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13033               << getRedeclDiagFromTagKind(I->getTagKind());
13034           }
13035           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13036             << getRedeclDiagFromTagKind(NewTag)
13037             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13038                  TypeWithKeyword::getTagTypeKindName(NewTag));
13039         }
13040       }
13041       return true;
13042     }
13043 
13044     // Check for a previous definition.  If current tag and definition
13045     // are same type, do nothing.  If no definition, but disagree with
13046     // with previous tag type, give a warning, but no fix-it.
13047     const TagDecl *Redecl = Previous->getDefinition() ?
13048                             Previous->getDefinition() : Previous;
13049     if (Redecl->getTagKind() == NewTag) {
13050       return true;
13051     }
13052 
13053     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13054       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13055       << getRedeclDiagFromTagKind(OldTag);
13056     Diag(Redecl->getLocation(), diag::note_previous_use);
13057 
13058     // If there is a previous definition, suggest a fix-it.
13059     if (Previous->getDefinition()) {
13060         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13061           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13062           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13063                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13064     }
13065 
13066     return true;
13067   }
13068   return false;
13069 }
13070 
13071 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13072 /// from an outer enclosing namespace or file scope inside a friend declaration.
13073 /// This should provide the commented out code in the following snippet:
13074 ///   namespace N {
13075 ///     struct X;
13076 ///     namespace M {
13077 ///       struct Y { friend struct /*N::*/ X; };
13078 ///     }
13079 ///   }
13080 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13081                                          SourceLocation NameLoc) {
13082   // While the decl is in a namespace, do repeated lookup of that name and see
13083   // if we get the same namespace back.  If we do not, continue until
13084   // translation unit scope, at which point we have a fully qualified NNS.
13085   SmallVector<IdentifierInfo *, 4> Namespaces;
13086   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13087   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13088     // This tag should be declared in a namespace, which can only be enclosed by
13089     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13090     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13091     if (!Namespace || Namespace->isAnonymousNamespace())
13092       return FixItHint();
13093     IdentifierInfo *II = Namespace->getIdentifier();
13094     Namespaces.push_back(II);
13095     NamedDecl *Lookup = SemaRef.LookupSingleName(
13096         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13097     if (Lookup == Namespace)
13098       break;
13099   }
13100 
13101   // Once we have all the namespaces, reverse them to go outermost first, and
13102   // build an NNS.
13103   SmallString<64> Insertion;
13104   llvm::raw_svector_ostream OS(Insertion);
13105   if (DC->isTranslationUnit())
13106     OS << "::";
13107   std::reverse(Namespaces.begin(), Namespaces.end());
13108   for (auto *II : Namespaces)
13109     OS << II->getName() << "::";
13110   return FixItHint::CreateInsertion(NameLoc, Insertion);
13111 }
13112 
13113 /// \brief Determine whether a tag originally declared in context \p OldDC can
13114 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13115 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13116 /// using-declaration).
13117 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13118                                          DeclContext *NewDC) {
13119   OldDC = OldDC->getRedeclContext();
13120   NewDC = NewDC->getRedeclContext();
13121 
13122   if (OldDC->Equals(NewDC))
13123     return true;
13124 
13125   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13126   // encloses the other).
13127   if (S.getLangOpts().MSVCCompat &&
13128       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13129     return true;
13130 
13131   return false;
13132 }
13133 
13134 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13135 /// former case, Name will be non-null.  In the later case, Name will be null.
13136 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13137 /// reference/declaration/definition of a tag.
13138 ///
13139 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13140 /// trailing-type-specifier) other than one in an alias-declaration.
13141 ///
13142 /// \param SkipBody If non-null, will be set to indicate if the caller should
13143 /// skip the definition of this tag and treat it as if it were a declaration.
13144 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13145                      SourceLocation KWLoc, CXXScopeSpec &SS,
13146                      IdentifierInfo *Name, SourceLocation NameLoc,
13147                      AttributeList *Attr, AccessSpecifier AS,
13148                      SourceLocation ModulePrivateLoc,
13149                      MultiTemplateParamsArg TemplateParameterLists,
13150                      bool &OwnedDecl, bool &IsDependent,
13151                      SourceLocation ScopedEnumKWLoc,
13152                      bool ScopedEnumUsesClassTag,
13153                      TypeResult UnderlyingType,
13154                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13155                      SkipBodyInfo *SkipBody) {
13156   // If this is not a definition, it must have a name.
13157   IdentifierInfo *OrigName = Name;
13158   assert((Name != nullptr || TUK == TUK_Definition) &&
13159          "Nameless record must be a definition!");
13160   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13161 
13162   OwnedDecl = false;
13163   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13164   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13165 
13166   // FIXME: Check member specializations more carefully.
13167   bool isMemberSpecialization = false;
13168   bool Invalid = false;
13169 
13170   // We only need to do this matching if we have template parameters
13171   // or a scope specifier, which also conveniently avoids this work
13172   // for non-C++ cases.
13173   if (TemplateParameterLists.size() > 0 ||
13174       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13175     if (TemplateParameterList *TemplateParams =
13176             MatchTemplateParametersToScopeSpecifier(
13177                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13178                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13179       if (Kind == TTK_Enum) {
13180         Diag(KWLoc, diag::err_enum_template);
13181         return nullptr;
13182       }
13183 
13184       if (TemplateParams->size() > 0) {
13185         // This is a declaration or definition of a class template (which may
13186         // be a member of another template).
13187 
13188         if (Invalid)
13189           return nullptr;
13190 
13191         OwnedDecl = false;
13192         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13193                                                SS, Name, NameLoc, Attr,
13194                                                TemplateParams, AS,
13195                                                ModulePrivateLoc,
13196                                                /*FriendLoc*/SourceLocation(),
13197                                                TemplateParameterLists.size()-1,
13198                                                TemplateParameterLists.data(),
13199                                                SkipBody);
13200         return Result.get();
13201       } else {
13202         // The "template<>" header is extraneous.
13203         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13204           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13205         isMemberSpecialization = true;
13206       }
13207     }
13208   }
13209 
13210   // Figure out the underlying type if this a enum declaration. We need to do
13211   // this early, because it's needed to detect if this is an incompatible
13212   // redeclaration.
13213   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13214   bool EnumUnderlyingIsImplicit = false;
13215 
13216   if (Kind == TTK_Enum) {
13217     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13218       // No underlying type explicitly specified, or we failed to parse the
13219       // type, default to int.
13220       EnumUnderlying = Context.IntTy.getTypePtr();
13221     else if (UnderlyingType.get()) {
13222       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13223       // integral type; any cv-qualification is ignored.
13224       TypeSourceInfo *TI = nullptr;
13225       GetTypeFromParser(UnderlyingType.get(), &TI);
13226       EnumUnderlying = TI;
13227 
13228       if (CheckEnumUnderlyingType(TI))
13229         // Recover by falling back to int.
13230         EnumUnderlying = Context.IntTy.getTypePtr();
13231 
13232       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13233                                           UPPC_FixedUnderlyingType))
13234         EnumUnderlying = Context.IntTy.getTypePtr();
13235 
13236     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13237       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13238         // Microsoft enums are always of int type.
13239         EnumUnderlying = Context.IntTy.getTypePtr();
13240         EnumUnderlyingIsImplicit = true;
13241       }
13242     }
13243   }
13244 
13245   DeclContext *SearchDC = CurContext;
13246   DeclContext *DC = CurContext;
13247   bool isStdBadAlloc = false;
13248   bool isStdAlignValT = false;
13249 
13250   RedeclarationKind Redecl = ForRedeclaration;
13251   if (TUK == TUK_Friend || TUK == TUK_Reference)
13252     Redecl = NotForRedeclaration;
13253 
13254   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13255   /// implemented asks for structural equivalence checking, the returned decl
13256   /// here is passed back to the parser, allowing the tag body to be parsed.
13257   auto createTagFromNewDecl = [&]() -> TagDecl * {
13258     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13259     // If there is an identifier, use the location of the identifier as the
13260     // location of the decl, otherwise use the location of the struct/union
13261     // keyword.
13262     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13263     TagDecl *New = nullptr;
13264 
13265     if (Kind == TTK_Enum) {
13266       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13267                              ScopedEnum, ScopedEnumUsesClassTag,
13268                              !EnumUnderlying.isNull());
13269       // If this is an undefined enum, bail.
13270       if (TUK != TUK_Definition && !Invalid)
13271         return nullptr;
13272       if (EnumUnderlying) {
13273         EnumDecl *ED = cast<EnumDecl>(New);
13274         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13275           ED->setIntegerTypeSourceInfo(TI);
13276         else
13277           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13278         ED->setPromotionType(ED->getIntegerType());
13279       }
13280     } else { // struct/union
13281       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13282                                nullptr);
13283     }
13284 
13285     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13286       // Add alignment attributes if necessary; these attributes are checked
13287       // when the ASTContext lays out the structure.
13288       //
13289       // It is important for implementing the correct semantics that this
13290       // happen here (in ActOnTag). The #pragma pack stack is
13291       // maintained as a result of parser callbacks which can occur at
13292       // many points during the parsing of a struct declaration (because
13293       // the #pragma tokens are effectively skipped over during the
13294       // parsing of the struct).
13295       if (TUK == TUK_Definition) {
13296         AddAlignmentAttributesForRecord(RD);
13297         AddMsStructLayoutForRecord(RD);
13298       }
13299     }
13300     New->setLexicalDeclContext(CurContext);
13301     return New;
13302   };
13303 
13304   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13305   if (Name && SS.isNotEmpty()) {
13306     // We have a nested-name tag ('struct foo::bar').
13307 
13308     // Check for invalid 'foo::'.
13309     if (SS.isInvalid()) {
13310       Name = nullptr;
13311       goto CreateNewDecl;
13312     }
13313 
13314     // If this is a friend or a reference to a class in a dependent
13315     // context, don't try to make a decl for it.
13316     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13317       DC = computeDeclContext(SS, false);
13318       if (!DC) {
13319         IsDependent = true;
13320         return nullptr;
13321       }
13322     } else {
13323       DC = computeDeclContext(SS, true);
13324       if (!DC) {
13325         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13326           << SS.getRange();
13327         return nullptr;
13328       }
13329     }
13330 
13331     if (RequireCompleteDeclContext(SS, DC))
13332       return nullptr;
13333 
13334     SearchDC = DC;
13335     // Look-up name inside 'foo::'.
13336     LookupQualifiedName(Previous, DC);
13337 
13338     if (Previous.isAmbiguous())
13339       return nullptr;
13340 
13341     if (Previous.empty()) {
13342       // Name lookup did not find anything. However, if the
13343       // nested-name-specifier refers to the current instantiation,
13344       // and that current instantiation has any dependent base
13345       // classes, we might find something at instantiation time: treat
13346       // this as a dependent elaborated-type-specifier.
13347       // But this only makes any sense for reference-like lookups.
13348       if (Previous.wasNotFoundInCurrentInstantiation() &&
13349           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13350         IsDependent = true;
13351         return nullptr;
13352       }
13353 
13354       // A tag 'foo::bar' must already exist.
13355       Diag(NameLoc, diag::err_not_tag_in_scope)
13356         << Kind << Name << DC << SS.getRange();
13357       Name = nullptr;
13358       Invalid = true;
13359       goto CreateNewDecl;
13360     }
13361   } else if (Name) {
13362     // C++14 [class.mem]p14:
13363     //   If T is the name of a class, then each of the following shall have a
13364     //   name different from T:
13365     //    -- every member of class T that is itself a type
13366     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13367         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13368       return nullptr;
13369 
13370     // If this is a named struct, check to see if there was a previous forward
13371     // declaration or definition.
13372     // FIXME: We're looking into outer scopes here, even when we
13373     // shouldn't be. Doing so can result in ambiguities that we
13374     // shouldn't be diagnosing.
13375     LookupName(Previous, S);
13376 
13377     // When declaring or defining a tag, ignore ambiguities introduced
13378     // by types using'ed into this scope.
13379     if (Previous.isAmbiguous() &&
13380         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13381       LookupResult::Filter F = Previous.makeFilter();
13382       while (F.hasNext()) {
13383         NamedDecl *ND = F.next();
13384         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13385                 SearchDC->getRedeclContext()))
13386           F.erase();
13387       }
13388       F.done();
13389     }
13390 
13391     // C++11 [namespace.memdef]p3:
13392     //   If the name in a friend declaration is neither qualified nor
13393     //   a template-id and the declaration is a function or an
13394     //   elaborated-type-specifier, the lookup to determine whether
13395     //   the entity has been previously declared shall not consider
13396     //   any scopes outside the innermost enclosing namespace.
13397     //
13398     // MSVC doesn't implement the above rule for types, so a friend tag
13399     // declaration may be a redeclaration of a type declared in an enclosing
13400     // scope.  They do implement this rule for friend functions.
13401     //
13402     // Does it matter that this should be by scope instead of by
13403     // semantic context?
13404     if (!Previous.empty() && TUK == TUK_Friend) {
13405       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13406       LookupResult::Filter F = Previous.makeFilter();
13407       bool FriendSawTagOutsideEnclosingNamespace = false;
13408       while (F.hasNext()) {
13409         NamedDecl *ND = F.next();
13410         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13411         if (DC->isFileContext() &&
13412             !EnclosingNS->Encloses(ND->getDeclContext())) {
13413           if (getLangOpts().MSVCCompat)
13414             FriendSawTagOutsideEnclosingNamespace = true;
13415           else
13416             F.erase();
13417         }
13418       }
13419       F.done();
13420 
13421       // Diagnose this MSVC extension in the easy case where lookup would have
13422       // unambiguously found something outside the enclosing namespace.
13423       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13424         NamedDecl *ND = Previous.getFoundDecl();
13425         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13426             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13427       }
13428     }
13429 
13430     // Note:  there used to be some attempt at recovery here.
13431     if (Previous.isAmbiguous())
13432       return nullptr;
13433 
13434     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13435       // FIXME: This makes sure that we ignore the contexts associated
13436       // with C structs, unions, and enums when looking for a matching
13437       // tag declaration or definition. See the similar lookup tweak
13438       // in Sema::LookupName; is there a better way to deal with this?
13439       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13440         SearchDC = SearchDC->getParent();
13441     }
13442   }
13443 
13444   if (Previous.isSingleResult() &&
13445       Previous.getFoundDecl()->isTemplateParameter()) {
13446     // Maybe we will complain about the shadowed template parameter.
13447     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13448     // Just pretend that we didn't see the previous declaration.
13449     Previous.clear();
13450   }
13451 
13452   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13453       DC->Equals(getStdNamespace())) {
13454     if (Name->isStr("bad_alloc")) {
13455       // This is a declaration of or a reference to "std::bad_alloc".
13456       isStdBadAlloc = true;
13457 
13458       // If std::bad_alloc has been implicitly declared (but made invisible to
13459       // name lookup), fill in this implicit declaration as the previous
13460       // declaration, so that the declarations get chained appropriately.
13461       if (Previous.empty() && StdBadAlloc)
13462         Previous.addDecl(getStdBadAlloc());
13463     } else if (Name->isStr("align_val_t")) {
13464       isStdAlignValT = true;
13465       if (Previous.empty() && StdAlignValT)
13466         Previous.addDecl(getStdAlignValT());
13467     }
13468   }
13469 
13470   // If we didn't find a previous declaration, and this is a reference
13471   // (or friend reference), move to the correct scope.  In C++, we
13472   // also need to do a redeclaration lookup there, just in case
13473   // there's a shadow friend decl.
13474   if (Name && Previous.empty() &&
13475       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13476     if (Invalid) goto CreateNewDecl;
13477     assert(SS.isEmpty());
13478 
13479     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13480       // C++ [basic.scope.pdecl]p5:
13481       //   -- for an elaborated-type-specifier of the form
13482       //
13483       //          class-key identifier
13484       //
13485       //      if the elaborated-type-specifier is used in the
13486       //      decl-specifier-seq or parameter-declaration-clause of a
13487       //      function defined in namespace scope, the identifier is
13488       //      declared as a class-name in the namespace that contains
13489       //      the declaration; otherwise, except as a friend
13490       //      declaration, the identifier is declared in the smallest
13491       //      non-class, non-function-prototype scope that contains the
13492       //      declaration.
13493       //
13494       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13495       // C structs and unions.
13496       //
13497       // It is an error in C++ to declare (rather than define) an enum
13498       // type, including via an elaborated type specifier.  We'll
13499       // diagnose that later; for now, declare the enum in the same
13500       // scope as we would have picked for any other tag type.
13501       //
13502       // GNU C also supports this behavior as part of its incomplete
13503       // enum types extension, while GNU C++ does not.
13504       //
13505       // Find the context where we'll be declaring the tag.
13506       // FIXME: We would like to maintain the current DeclContext as the
13507       // lexical context,
13508       SearchDC = getTagInjectionContext(SearchDC);
13509 
13510       // Find the scope where we'll be declaring the tag.
13511       S = getTagInjectionScope(S, getLangOpts());
13512     } else {
13513       assert(TUK == TUK_Friend);
13514       // C++ [namespace.memdef]p3:
13515       //   If a friend declaration in a non-local class first declares a
13516       //   class or function, the friend class or function is a member of
13517       //   the innermost enclosing namespace.
13518       SearchDC = SearchDC->getEnclosingNamespaceContext();
13519     }
13520 
13521     // In C++, we need to do a redeclaration lookup to properly
13522     // diagnose some problems.
13523     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13524     // hidden declaration so that we don't get ambiguity errors when using a
13525     // type declared by an elaborated-type-specifier.  In C that is not correct
13526     // and we should instead merge compatible types found by lookup.
13527     if (getLangOpts().CPlusPlus) {
13528       Previous.setRedeclarationKind(ForRedeclaration);
13529       LookupQualifiedName(Previous, SearchDC);
13530     } else {
13531       Previous.setRedeclarationKind(ForRedeclaration);
13532       LookupName(Previous, S);
13533     }
13534   }
13535 
13536   // If we have a known previous declaration to use, then use it.
13537   if (Previous.empty() && SkipBody && SkipBody->Previous)
13538     Previous.addDecl(SkipBody->Previous);
13539 
13540   if (!Previous.empty()) {
13541     NamedDecl *PrevDecl = Previous.getFoundDecl();
13542     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13543 
13544     // It's okay to have a tag decl in the same scope as a typedef
13545     // which hides a tag decl in the same scope.  Finding this
13546     // insanity with a redeclaration lookup can only actually happen
13547     // in C++.
13548     //
13549     // This is also okay for elaborated-type-specifiers, which is
13550     // technically forbidden by the current standard but which is
13551     // okay according to the likely resolution of an open issue;
13552     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13553     if (getLangOpts().CPlusPlus) {
13554       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13555         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13556           TagDecl *Tag = TT->getDecl();
13557           if (Tag->getDeclName() == Name &&
13558               Tag->getDeclContext()->getRedeclContext()
13559                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13560             PrevDecl = Tag;
13561             Previous.clear();
13562             Previous.addDecl(Tag);
13563             Previous.resolveKind();
13564           }
13565         }
13566       }
13567     }
13568 
13569     // If this is a redeclaration of a using shadow declaration, it must
13570     // declare a tag in the same context. In MSVC mode, we allow a
13571     // redefinition if either context is within the other.
13572     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13573       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13574       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13575           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13576           !(OldTag && isAcceptableTagRedeclContext(
13577                           *this, OldTag->getDeclContext(), SearchDC))) {
13578         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13579         Diag(Shadow->getTargetDecl()->getLocation(),
13580              diag::note_using_decl_target);
13581         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13582             << 0;
13583         // Recover by ignoring the old declaration.
13584         Previous.clear();
13585         goto CreateNewDecl;
13586       }
13587     }
13588 
13589     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13590       // If this is a use of a previous tag, or if the tag is already declared
13591       // in the same scope (so that the definition/declaration completes or
13592       // rementions the tag), reuse the decl.
13593       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13594           isDeclInScope(DirectPrevDecl, SearchDC, S,
13595                         SS.isNotEmpty() || isMemberSpecialization)) {
13596         // Make sure that this wasn't declared as an enum and now used as a
13597         // struct or something similar.
13598         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13599                                           TUK == TUK_Definition, KWLoc,
13600                                           Name)) {
13601           bool SafeToContinue
13602             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13603                Kind != TTK_Enum);
13604           if (SafeToContinue)
13605             Diag(KWLoc, diag::err_use_with_wrong_tag)
13606               << Name
13607               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13608                                               PrevTagDecl->getKindName());
13609           else
13610             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13611           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13612 
13613           if (SafeToContinue)
13614             Kind = PrevTagDecl->getTagKind();
13615           else {
13616             // Recover by making this an anonymous redefinition.
13617             Name = nullptr;
13618             Previous.clear();
13619             Invalid = true;
13620           }
13621         }
13622 
13623         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13624           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13625 
13626           // If this is an elaborated-type-specifier for a scoped enumeration,
13627           // the 'class' keyword is not necessary and not permitted.
13628           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13629             if (ScopedEnum)
13630               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13631                 << PrevEnum->isScoped()
13632                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13633             return PrevTagDecl;
13634           }
13635 
13636           QualType EnumUnderlyingTy;
13637           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13638             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13639           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13640             EnumUnderlyingTy = QualType(T, 0);
13641 
13642           // All conflicts with previous declarations are recovered by
13643           // returning the previous declaration, unless this is a definition,
13644           // in which case we want the caller to bail out.
13645           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13646                                      ScopedEnum, EnumUnderlyingTy,
13647                                      EnumUnderlyingIsImplicit, PrevEnum))
13648             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13649         }
13650 
13651         // C++11 [class.mem]p1:
13652         //   A member shall not be declared twice in the member-specification,
13653         //   except that a nested class or member class template can be declared
13654         //   and then later defined.
13655         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13656             S->isDeclScope(PrevDecl)) {
13657           Diag(NameLoc, diag::ext_member_redeclared);
13658           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13659         }
13660 
13661         if (!Invalid) {
13662           // If this is a use, just return the declaration we found, unless
13663           // we have attributes.
13664           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13665             if (Attr) {
13666               // FIXME: Diagnose these attributes. For now, we create a new
13667               // declaration to hold them.
13668             } else if (TUK == TUK_Reference &&
13669                        (PrevTagDecl->getFriendObjectKind() ==
13670                             Decl::FOK_Undeclared ||
13671                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13672                        SS.isEmpty()) {
13673               // This declaration is a reference to an existing entity, but
13674               // has different visibility from that entity: it either makes
13675               // a friend visible or it makes a type visible in a new module.
13676               // In either case, create a new declaration. We only do this if
13677               // the declaration would have meant the same thing if no prior
13678               // declaration were found, that is, if it was found in the same
13679               // scope where we would have injected a declaration.
13680               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13681                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13682                 return PrevTagDecl;
13683               // This is in the injected scope, create a new declaration in
13684               // that scope.
13685               S = getTagInjectionScope(S, getLangOpts());
13686             } else {
13687               return PrevTagDecl;
13688             }
13689           }
13690 
13691           // Diagnose attempts to redefine a tag.
13692           if (TUK == TUK_Definition) {
13693             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13694               // If we're defining a specialization and the previous definition
13695               // is from an implicit instantiation, don't emit an error
13696               // here; we'll catch this in the general case below.
13697               bool IsExplicitSpecializationAfterInstantiation = false;
13698               if (isMemberSpecialization) {
13699                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13700                   IsExplicitSpecializationAfterInstantiation =
13701                     RD->getTemplateSpecializationKind() !=
13702                     TSK_ExplicitSpecialization;
13703                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13704                   IsExplicitSpecializationAfterInstantiation =
13705                     ED->getTemplateSpecializationKind() !=
13706                     TSK_ExplicitSpecialization;
13707               }
13708 
13709               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13710               // not keep more that one definition around (merge them). However,
13711               // ensure the decl passes the structural compatibility check in
13712               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13713               NamedDecl *Hidden = nullptr;
13714               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13715                 // There is a definition of this tag, but it is not visible. We
13716                 // explicitly make use of C++'s one definition rule here, and
13717                 // assume that this definition is identical to the hidden one
13718                 // we already have. Make the existing definition visible and
13719                 // use it in place of this one.
13720                 if (!getLangOpts().CPlusPlus) {
13721                   // Postpone making the old definition visible until after we
13722                   // complete parsing the new one and do the structural
13723                   // comparison.
13724                   SkipBody->CheckSameAsPrevious = true;
13725                   SkipBody->New = createTagFromNewDecl();
13726                   SkipBody->Previous = Hidden;
13727                 } else {
13728                   SkipBody->ShouldSkip = true;
13729                   makeMergedDefinitionVisible(Hidden);
13730                 }
13731                 return Def;
13732               } else if (!IsExplicitSpecializationAfterInstantiation) {
13733                 // A redeclaration in function prototype scope in C isn't
13734                 // visible elsewhere, so merely issue a warning.
13735                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13736                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13737                 else
13738                   Diag(NameLoc, diag::err_redefinition) << Name;
13739                 notePreviousDefinition(Def,
13740                                        NameLoc.isValid() ? NameLoc : KWLoc);
13741                 // If this is a redefinition, recover by making this
13742                 // struct be anonymous, which will make any later
13743                 // references get the previous definition.
13744                 Name = nullptr;
13745                 Previous.clear();
13746                 Invalid = true;
13747               }
13748             } else {
13749               // If the type is currently being defined, complain
13750               // about a nested redefinition.
13751               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13752               if (TD->isBeingDefined()) {
13753                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13754                 Diag(PrevTagDecl->getLocation(),
13755                      diag::note_previous_definition);
13756                 Name = nullptr;
13757                 Previous.clear();
13758                 Invalid = true;
13759               }
13760             }
13761 
13762             // Okay, this is definition of a previously declared or referenced
13763             // tag. We're going to create a new Decl for it.
13764           }
13765 
13766           // Okay, we're going to make a redeclaration.  If this is some kind
13767           // of reference, make sure we build the redeclaration in the same DC
13768           // as the original, and ignore the current access specifier.
13769           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13770             SearchDC = PrevTagDecl->getDeclContext();
13771             AS = AS_none;
13772           }
13773         }
13774         // If we get here we have (another) forward declaration or we
13775         // have a definition.  Just create a new decl.
13776 
13777       } else {
13778         // If we get here, this is a definition of a new tag type in a nested
13779         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13780         // new decl/type.  We set PrevDecl to NULL so that the entities
13781         // have distinct types.
13782         Previous.clear();
13783       }
13784       // If we get here, we're going to create a new Decl. If PrevDecl
13785       // is non-NULL, it's a definition of the tag declared by
13786       // PrevDecl. If it's NULL, we have a new definition.
13787 
13788     // Otherwise, PrevDecl is not a tag, but was found with tag
13789     // lookup.  This is only actually possible in C++, where a few
13790     // things like templates still live in the tag namespace.
13791     } else {
13792       // Use a better diagnostic if an elaborated-type-specifier
13793       // found the wrong kind of type on the first
13794       // (non-redeclaration) lookup.
13795       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13796           !Previous.isForRedeclaration()) {
13797         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13798         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13799                                                        << Kind;
13800         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13801         Invalid = true;
13802 
13803       // Otherwise, only diagnose if the declaration is in scope.
13804       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13805                                 SS.isNotEmpty() || isMemberSpecialization)) {
13806         // do nothing
13807 
13808       // Diagnose implicit declarations introduced by elaborated types.
13809       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13810         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13811         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13812         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13813         Invalid = true;
13814 
13815       // Otherwise it's a declaration.  Call out a particularly common
13816       // case here.
13817       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13818         unsigned Kind = 0;
13819         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13820         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13821           << Name << Kind << TND->getUnderlyingType();
13822         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13823         Invalid = true;
13824 
13825       // Otherwise, diagnose.
13826       } else {
13827         // The tag name clashes with something else in the target scope,
13828         // issue an error and recover by making this tag be anonymous.
13829         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13830         notePreviousDefinition(PrevDecl, NameLoc);
13831         Name = nullptr;
13832         Invalid = true;
13833       }
13834 
13835       // The existing declaration isn't relevant to us; we're in a
13836       // new scope, so clear out the previous declaration.
13837       Previous.clear();
13838     }
13839   }
13840 
13841 CreateNewDecl:
13842 
13843   TagDecl *PrevDecl = nullptr;
13844   if (Previous.isSingleResult())
13845     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13846 
13847   // If there is an identifier, use the location of the identifier as the
13848   // location of the decl, otherwise use the location of the struct/union
13849   // keyword.
13850   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13851 
13852   // Otherwise, create a new declaration. If there is a previous
13853   // declaration of the same entity, the two will be linked via
13854   // PrevDecl.
13855   TagDecl *New;
13856 
13857   bool IsForwardReference = false;
13858   if (Kind == TTK_Enum) {
13859     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13860     // enum X { A, B, C } D;    D should chain to X.
13861     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13862                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13863                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13864 
13865     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13866       StdAlignValT = cast<EnumDecl>(New);
13867 
13868     // If this is an undefined enum, warn.
13869     if (TUK != TUK_Definition && !Invalid) {
13870       TagDecl *Def;
13871       if (!EnumUnderlyingIsImplicit &&
13872           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13873           cast<EnumDecl>(New)->isFixed()) {
13874         // C++0x: 7.2p2: opaque-enum-declaration.
13875         // Conflicts are diagnosed above. Do nothing.
13876       }
13877       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13878         Diag(Loc, diag::ext_forward_ref_enum_def)
13879           << New;
13880         Diag(Def->getLocation(), diag::note_previous_definition);
13881       } else {
13882         unsigned DiagID = diag::ext_forward_ref_enum;
13883         if (getLangOpts().MSVCCompat)
13884           DiagID = diag::ext_ms_forward_ref_enum;
13885         else if (getLangOpts().CPlusPlus)
13886           DiagID = diag::err_forward_ref_enum;
13887         Diag(Loc, DiagID);
13888 
13889         // If this is a forward-declared reference to an enumeration, make a
13890         // note of it; we won't actually be introducing the declaration into
13891         // the declaration context.
13892         if (TUK == TUK_Reference)
13893           IsForwardReference = true;
13894       }
13895     }
13896 
13897     if (EnumUnderlying) {
13898       EnumDecl *ED = cast<EnumDecl>(New);
13899       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13900         ED->setIntegerTypeSourceInfo(TI);
13901       else
13902         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13903       ED->setPromotionType(ED->getIntegerType());
13904     }
13905   } else {
13906     // struct/union/class
13907 
13908     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13909     // struct X { int A; } D;    D should chain to X.
13910     if (getLangOpts().CPlusPlus) {
13911       // FIXME: Look for a way to use RecordDecl for simple structs.
13912       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13913                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13914 
13915       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13916         StdBadAlloc = cast<CXXRecordDecl>(New);
13917     } else
13918       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13919                                cast_or_null<RecordDecl>(PrevDecl));
13920   }
13921 
13922   // C++11 [dcl.type]p3:
13923   //   A type-specifier-seq shall not define a class or enumeration [...].
13924   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13925       TUK == TUK_Definition) {
13926     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13927       << Context.getTagDeclType(New);
13928     Invalid = true;
13929   }
13930 
13931   if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) {
13932     Diag(New->getLocation(), diag::err_type_defined_in_enum)
13933       << Context.getTagDeclType(New);
13934     Invalid = true;
13935   }
13936 
13937   // Maybe add qualifier info.
13938   if (SS.isNotEmpty()) {
13939     if (SS.isSet()) {
13940       // If this is either a declaration or a definition, check the
13941       // nested-name-specifier against the current context. We don't do this
13942       // for explicit specializations, because they have similar checking
13943       // (with more specific diagnostics) in the call to
13944       // CheckMemberSpecialization, below.
13945       if (!isMemberSpecialization &&
13946           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13947           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13948         Invalid = true;
13949 
13950       New->setQualifierInfo(SS.getWithLocInContext(Context));
13951       if (TemplateParameterLists.size() > 0) {
13952         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13953       }
13954     }
13955     else
13956       Invalid = true;
13957   }
13958 
13959   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13960     // Add alignment attributes if necessary; these attributes are checked when
13961     // the ASTContext lays out the structure.
13962     //
13963     // It is important for implementing the correct semantics that this
13964     // happen here (in ActOnTag). The #pragma pack stack is
13965     // maintained as a result of parser callbacks which can occur at
13966     // many points during the parsing of a struct declaration (because
13967     // the #pragma tokens are effectively skipped over during the
13968     // parsing of the struct).
13969     if (TUK == TUK_Definition) {
13970       AddAlignmentAttributesForRecord(RD);
13971       AddMsStructLayoutForRecord(RD);
13972     }
13973   }
13974 
13975   if (ModulePrivateLoc.isValid()) {
13976     if (isMemberSpecialization)
13977       Diag(New->getLocation(), diag::err_module_private_specialization)
13978         << 2
13979         << FixItHint::CreateRemoval(ModulePrivateLoc);
13980     // __module_private__ does not apply to local classes. However, we only
13981     // diagnose this as an error when the declaration specifiers are
13982     // freestanding. Here, we just ignore the __module_private__.
13983     else if (!SearchDC->isFunctionOrMethod())
13984       New->setModulePrivate();
13985   }
13986 
13987   // If this is a specialization of a member class (of a class template),
13988   // check the specialization.
13989   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13990     Invalid = true;
13991 
13992   // If we're declaring or defining a tag in function prototype scope in C,
13993   // note that this type can only be used within the function and add it to
13994   // the list of decls to inject into the function definition scope.
13995   if ((Name || Kind == TTK_Enum) &&
13996       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13997     if (getLangOpts().CPlusPlus) {
13998       // C++ [dcl.fct]p6:
13999       //   Types shall not be defined in return or parameter types.
14000       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14001         Diag(Loc, diag::err_type_defined_in_param_type)
14002             << Name;
14003         Invalid = true;
14004       }
14005     } else if (!PrevDecl) {
14006       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14007     }
14008   }
14009 
14010   if (Invalid)
14011     New->setInvalidDecl();
14012 
14013   // Set the lexical context. If the tag has a C++ scope specifier, the
14014   // lexical context will be different from the semantic context.
14015   New->setLexicalDeclContext(CurContext);
14016 
14017   // Mark this as a friend decl if applicable.
14018   // In Microsoft mode, a friend declaration also acts as a forward
14019   // declaration so we always pass true to setObjectOfFriendDecl to make
14020   // the tag name visible.
14021   if (TUK == TUK_Friend)
14022     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14023 
14024   // Set the access specifier.
14025   if (!Invalid && SearchDC->isRecord())
14026     SetMemberAccessSpecifier(New, PrevDecl, AS);
14027 
14028   if (TUK == TUK_Definition)
14029     New->startDefinition();
14030 
14031   if (Attr)
14032     ProcessDeclAttributeList(S, New, Attr);
14033   AddPragmaAttributes(S, New);
14034 
14035   // If this has an identifier, add it to the scope stack.
14036   if (TUK == TUK_Friend) {
14037     // We might be replacing an existing declaration in the lookup tables;
14038     // if so, borrow its access specifier.
14039     if (PrevDecl)
14040       New->setAccess(PrevDecl->getAccess());
14041 
14042     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14043     DC->makeDeclVisibleInContext(New);
14044     if (Name) // can be null along some error paths
14045       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14046         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14047   } else if (Name) {
14048     S = getNonFieldDeclScope(S);
14049     PushOnScopeChains(New, S, !IsForwardReference);
14050     if (IsForwardReference)
14051       SearchDC->makeDeclVisibleInContext(New);
14052   } else {
14053     CurContext->addDecl(New);
14054   }
14055 
14056   // If this is the C FILE type, notify the AST context.
14057   if (IdentifierInfo *II = New->getIdentifier())
14058     if (!New->isInvalidDecl() &&
14059         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14060         II->isStr("FILE"))
14061       Context.setFILEDecl(New);
14062 
14063   if (PrevDecl)
14064     mergeDeclAttributes(New, PrevDecl);
14065 
14066   // If there's a #pragma GCC visibility in scope, set the visibility of this
14067   // record.
14068   AddPushedVisibilityAttribute(New);
14069 
14070   if (isMemberSpecialization && !New->isInvalidDecl())
14071     CompleteMemberSpecialization(New, Previous);
14072 
14073   OwnedDecl = true;
14074   // In C++, don't return an invalid declaration. We can't recover well from
14075   // the cases where we make the type anonymous.
14076   if (Invalid && getLangOpts().CPlusPlus) {
14077     if (New->isBeingDefined())
14078       if (auto RD = dyn_cast<RecordDecl>(New))
14079         RD->completeDefinition();
14080     return nullptr;
14081   } else {
14082     return New;
14083   }
14084 }
14085 
14086 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14087   AdjustDeclIfTemplate(TagD);
14088   TagDecl *Tag = cast<TagDecl>(TagD);
14089 
14090   // Enter the tag context.
14091   PushDeclContext(S, Tag);
14092 
14093   ActOnDocumentableDecl(TagD);
14094 
14095   // If there's a #pragma GCC visibility in scope, set the visibility of this
14096   // record.
14097   AddPushedVisibilityAttribute(Tag);
14098 }
14099 
14100 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14101                                     SkipBodyInfo &SkipBody) {
14102   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14103     return false;
14104 
14105   // Make the previous decl visible.
14106   makeMergedDefinitionVisible(SkipBody.Previous);
14107   return true;
14108 }
14109 
14110 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14111   assert(isa<ObjCContainerDecl>(IDecl) &&
14112          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14113   DeclContext *OCD = cast<DeclContext>(IDecl);
14114   assert(getContainingDC(OCD) == CurContext &&
14115       "The next DeclContext should be lexically contained in the current one.");
14116   CurContext = OCD;
14117   return IDecl;
14118 }
14119 
14120 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14121                                            SourceLocation FinalLoc,
14122                                            bool IsFinalSpelledSealed,
14123                                            SourceLocation LBraceLoc) {
14124   AdjustDeclIfTemplate(TagD);
14125   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14126 
14127   FieldCollector->StartClass();
14128 
14129   if (!Record->getIdentifier())
14130     return;
14131 
14132   if (FinalLoc.isValid())
14133     Record->addAttr(new (Context)
14134                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14135 
14136   // C++ [class]p2:
14137   //   [...] The class-name is also inserted into the scope of the
14138   //   class itself; this is known as the injected-class-name. For
14139   //   purposes of access checking, the injected-class-name is treated
14140   //   as if it were a public member name.
14141   CXXRecordDecl *InjectedClassName
14142     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14143                             Record->getLocStart(), Record->getLocation(),
14144                             Record->getIdentifier(),
14145                             /*PrevDecl=*/nullptr,
14146                             /*DelayTypeCreation=*/true);
14147   Context.getTypeDeclType(InjectedClassName, Record);
14148   InjectedClassName->setImplicit();
14149   InjectedClassName->setAccess(AS_public);
14150   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14151       InjectedClassName->setDescribedClassTemplate(Template);
14152   PushOnScopeChains(InjectedClassName, S);
14153   assert(InjectedClassName->isInjectedClassName() &&
14154          "Broken injected-class-name");
14155 }
14156 
14157 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14158                                     SourceRange BraceRange) {
14159   AdjustDeclIfTemplate(TagD);
14160   TagDecl *Tag = cast<TagDecl>(TagD);
14161   Tag->setBraceRange(BraceRange);
14162 
14163   // Make sure we "complete" the definition even it is invalid.
14164   if (Tag->isBeingDefined()) {
14165     assert(Tag->isInvalidDecl() && "We should already have completed it");
14166     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14167       RD->completeDefinition();
14168   }
14169 
14170   if (isa<CXXRecordDecl>(Tag)) {
14171     FieldCollector->FinishClass();
14172   }
14173 
14174   // Exit this scope of this tag's definition.
14175   PopDeclContext();
14176 
14177   if (getCurLexicalContext()->isObjCContainer() &&
14178       Tag->getDeclContext()->isFileContext())
14179     Tag->setTopLevelDeclInObjCContainer();
14180 
14181   // Notify the consumer that we've defined a tag.
14182   if (!Tag->isInvalidDecl())
14183     Consumer.HandleTagDeclDefinition(Tag);
14184 }
14185 
14186 void Sema::ActOnObjCContainerFinishDefinition() {
14187   // Exit this scope of this interface definition.
14188   PopDeclContext();
14189 }
14190 
14191 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14192   assert(DC == CurContext && "Mismatch of container contexts");
14193   OriginalLexicalContext = DC;
14194   ActOnObjCContainerFinishDefinition();
14195 }
14196 
14197 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14198   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14199   OriginalLexicalContext = nullptr;
14200 }
14201 
14202 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14203   AdjustDeclIfTemplate(TagD);
14204   TagDecl *Tag = cast<TagDecl>(TagD);
14205   Tag->setInvalidDecl();
14206 
14207   // Make sure we "complete" the definition even it is invalid.
14208   if (Tag->isBeingDefined()) {
14209     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14210       RD->completeDefinition();
14211   }
14212 
14213   // We're undoing ActOnTagStartDefinition here, not
14214   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14215   // the FieldCollector.
14216 
14217   PopDeclContext();
14218 }
14219 
14220 // Note that FieldName may be null for anonymous bitfields.
14221 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14222                                 IdentifierInfo *FieldName,
14223                                 QualType FieldTy, bool IsMsStruct,
14224                                 Expr *BitWidth, bool *ZeroWidth) {
14225   // Default to true; that shouldn't confuse checks for emptiness
14226   if (ZeroWidth)
14227     *ZeroWidth = true;
14228 
14229   // C99 6.7.2.1p4 - verify the field type.
14230   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14231   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14232     // Handle incomplete types with specific error.
14233     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14234       return ExprError();
14235     if (FieldName)
14236       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14237         << FieldName << FieldTy << BitWidth->getSourceRange();
14238     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14239       << FieldTy << BitWidth->getSourceRange();
14240   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14241                                              UPPC_BitFieldWidth))
14242     return ExprError();
14243 
14244   // If the bit-width is type- or value-dependent, don't try to check
14245   // it now.
14246   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14247     return BitWidth;
14248 
14249   llvm::APSInt Value;
14250   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14251   if (ICE.isInvalid())
14252     return ICE;
14253   BitWidth = ICE.get();
14254 
14255   if (Value != 0 && ZeroWidth)
14256     *ZeroWidth = false;
14257 
14258   // Zero-width bitfield is ok for anonymous field.
14259   if (Value == 0 && FieldName)
14260     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14261 
14262   if (Value.isSigned() && Value.isNegative()) {
14263     if (FieldName)
14264       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14265                << FieldName << Value.toString(10);
14266     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14267       << Value.toString(10);
14268   }
14269 
14270   if (!FieldTy->isDependentType()) {
14271     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14272     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14273     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14274 
14275     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14276     // ABI.
14277     bool CStdConstraintViolation =
14278         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14279     bool MSBitfieldViolation =
14280         Value.ugt(TypeStorageSize) &&
14281         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14282     if (CStdConstraintViolation || MSBitfieldViolation) {
14283       unsigned DiagWidth =
14284           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14285       if (FieldName)
14286         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14287                << FieldName << (unsigned)Value.getZExtValue()
14288                << !CStdConstraintViolation << DiagWidth;
14289 
14290       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14291              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14292              << DiagWidth;
14293     }
14294 
14295     // Warn on types where the user might conceivably expect to get all
14296     // specified bits as value bits: that's all integral types other than
14297     // 'bool'.
14298     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14299       if (FieldName)
14300         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14301             << FieldName << (unsigned)Value.getZExtValue()
14302             << (unsigned)TypeWidth;
14303       else
14304         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14305             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14306     }
14307   }
14308 
14309   return BitWidth;
14310 }
14311 
14312 /// ActOnField - Each field of a C struct/union is passed into this in order
14313 /// to create a FieldDecl object for it.
14314 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14315                        Declarator &D, Expr *BitfieldWidth) {
14316   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14317                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14318                                /*InitStyle=*/ICIS_NoInit, AS_public);
14319   return Res;
14320 }
14321 
14322 /// HandleField - Analyze a field of a C struct or a C++ data member.
14323 ///
14324 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14325                              SourceLocation DeclStart,
14326                              Declarator &D, Expr *BitWidth,
14327                              InClassInitStyle InitStyle,
14328                              AccessSpecifier AS) {
14329   if (D.isDecompositionDeclarator()) {
14330     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14331     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14332       << Decomp.getSourceRange();
14333     return nullptr;
14334   }
14335 
14336   IdentifierInfo *II = D.getIdentifier();
14337   SourceLocation Loc = DeclStart;
14338   if (II) Loc = D.getIdentifierLoc();
14339 
14340   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14341   QualType T = TInfo->getType();
14342   if (getLangOpts().CPlusPlus) {
14343     CheckExtraCXXDefaultArguments(D);
14344 
14345     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14346                                         UPPC_DataMemberType)) {
14347       D.setInvalidType();
14348       T = Context.IntTy;
14349       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14350     }
14351   }
14352 
14353   // TR 18037 does not allow fields to be declared with address spaces.
14354   if (T.getQualifiers().hasAddressSpace()) {
14355     Diag(Loc, diag::err_field_with_address_space);
14356     D.setInvalidType();
14357   }
14358 
14359   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14360   // used as structure or union field: image, sampler, event or block types.
14361   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14362                           T->isSamplerT() || T->isBlockPointerType())) {
14363     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14364     D.setInvalidType();
14365   }
14366 
14367   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14368 
14369   if (D.getDeclSpec().isInlineSpecified())
14370     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14371         << getLangOpts().CPlusPlus1z;
14372   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14373     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14374          diag::err_invalid_thread)
14375       << DeclSpec::getSpecifierName(TSCS);
14376 
14377   // Check to see if this name was declared as a member previously
14378   NamedDecl *PrevDecl = nullptr;
14379   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14380   LookupName(Previous, S);
14381   switch (Previous.getResultKind()) {
14382     case LookupResult::Found:
14383     case LookupResult::FoundUnresolvedValue:
14384       PrevDecl = Previous.getAsSingle<NamedDecl>();
14385       break;
14386 
14387     case LookupResult::FoundOverloaded:
14388       PrevDecl = Previous.getRepresentativeDecl();
14389       break;
14390 
14391     case LookupResult::NotFound:
14392     case LookupResult::NotFoundInCurrentInstantiation:
14393     case LookupResult::Ambiguous:
14394       break;
14395   }
14396   Previous.suppressDiagnostics();
14397 
14398   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14399     // Maybe we will complain about the shadowed template parameter.
14400     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14401     // Just pretend that we didn't see the previous declaration.
14402     PrevDecl = nullptr;
14403   }
14404 
14405   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14406     PrevDecl = nullptr;
14407 
14408   bool Mutable
14409     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14410   SourceLocation TSSL = D.getLocStart();
14411   FieldDecl *NewFD
14412     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14413                      TSSL, AS, PrevDecl, &D);
14414 
14415   if (NewFD->isInvalidDecl())
14416     Record->setInvalidDecl();
14417 
14418   if (D.getDeclSpec().isModulePrivateSpecified())
14419     NewFD->setModulePrivate();
14420 
14421   if (NewFD->isInvalidDecl() && PrevDecl) {
14422     // Don't introduce NewFD into scope; there's already something
14423     // with the same name in the same scope.
14424   } else if (II) {
14425     PushOnScopeChains(NewFD, S);
14426   } else
14427     Record->addDecl(NewFD);
14428 
14429   return NewFD;
14430 }
14431 
14432 /// \brief Build a new FieldDecl and check its well-formedness.
14433 ///
14434 /// This routine builds a new FieldDecl given the fields name, type,
14435 /// record, etc. \p PrevDecl should refer to any previous declaration
14436 /// with the same name and in the same scope as the field to be
14437 /// created.
14438 ///
14439 /// \returns a new FieldDecl.
14440 ///
14441 /// \todo The Declarator argument is a hack. It will be removed once
14442 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14443                                 TypeSourceInfo *TInfo,
14444                                 RecordDecl *Record, SourceLocation Loc,
14445                                 bool Mutable, Expr *BitWidth,
14446                                 InClassInitStyle InitStyle,
14447                                 SourceLocation TSSL,
14448                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14449                                 Declarator *D) {
14450   IdentifierInfo *II = Name.getAsIdentifierInfo();
14451   bool InvalidDecl = false;
14452   if (D) InvalidDecl = D->isInvalidType();
14453 
14454   // If we receive a broken type, recover by assuming 'int' and
14455   // marking this declaration as invalid.
14456   if (T.isNull()) {
14457     InvalidDecl = true;
14458     T = Context.IntTy;
14459   }
14460 
14461   QualType EltTy = Context.getBaseElementType(T);
14462   if (!EltTy->isDependentType()) {
14463     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14464       // Fields of incomplete type force their record to be invalid.
14465       Record->setInvalidDecl();
14466       InvalidDecl = true;
14467     } else {
14468       NamedDecl *Def;
14469       EltTy->isIncompleteType(&Def);
14470       if (Def && Def->isInvalidDecl()) {
14471         Record->setInvalidDecl();
14472         InvalidDecl = true;
14473       }
14474     }
14475   }
14476 
14477   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14478   if (BitWidth && getLangOpts().OpenCL) {
14479     Diag(Loc, diag::err_opencl_bitfields);
14480     InvalidDecl = true;
14481   }
14482 
14483   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14484   // than a variably modified type.
14485   if (!InvalidDecl && T->isVariablyModifiedType()) {
14486     bool SizeIsNegative;
14487     llvm::APSInt Oversized;
14488 
14489     TypeSourceInfo *FixedTInfo =
14490       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14491                                                     SizeIsNegative,
14492                                                     Oversized);
14493     if (FixedTInfo) {
14494       Diag(Loc, diag::warn_illegal_constant_array_size);
14495       TInfo = FixedTInfo;
14496       T = FixedTInfo->getType();
14497     } else {
14498       if (SizeIsNegative)
14499         Diag(Loc, diag::err_typecheck_negative_array_size);
14500       else if (Oversized.getBoolValue())
14501         Diag(Loc, diag::err_array_too_large)
14502           << Oversized.toString(10);
14503       else
14504         Diag(Loc, diag::err_typecheck_field_variable_size);
14505       InvalidDecl = true;
14506     }
14507   }
14508 
14509   // Fields can not have abstract class types
14510   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14511                                              diag::err_abstract_type_in_decl,
14512                                              AbstractFieldType))
14513     InvalidDecl = true;
14514 
14515   bool ZeroWidth = false;
14516   if (InvalidDecl)
14517     BitWidth = nullptr;
14518   // If this is declared as a bit-field, check the bit-field.
14519   if (BitWidth) {
14520     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14521                               &ZeroWidth).get();
14522     if (!BitWidth) {
14523       InvalidDecl = true;
14524       BitWidth = nullptr;
14525       ZeroWidth = false;
14526     }
14527   }
14528 
14529   // Check that 'mutable' is consistent with the type of the declaration.
14530   if (!InvalidDecl && Mutable) {
14531     unsigned DiagID = 0;
14532     if (T->isReferenceType())
14533       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14534                                         : diag::err_mutable_reference;
14535     else if (T.isConstQualified())
14536       DiagID = diag::err_mutable_const;
14537 
14538     if (DiagID) {
14539       SourceLocation ErrLoc = Loc;
14540       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14541         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14542       Diag(ErrLoc, DiagID);
14543       if (DiagID != diag::ext_mutable_reference) {
14544         Mutable = false;
14545         InvalidDecl = true;
14546       }
14547     }
14548   }
14549 
14550   // C++11 [class.union]p8 (DR1460):
14551   //   At most one variant member of a union may have a
14552   //   brace-or-equal-initializer.
14553   if (InitStyle != ICIS_NoInit)
14554     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14555 
14556   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14557                                        BitWidth, Mutable, InitStyle);
14558   if (InvalidDecl)
14559     NewFD->setInvalidDecl();
14560 
14561   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14562     Diag(Loc, diag::err_duplicate_member) << II;
14563     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14564     NewFD->setInvalidDecl();
14565   }
14566 
14567   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14568     if (Record->isUnion()) {
14569       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14570         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14571         if (RDecl->getDefinition()) {
14572           // C++ [class.union]p1: An object of a class with a non-trivial
14573           // constructor, a non-trivial copy constructor, a non-trivial
14574           // destructor, or a non-trivial copy assignment operator
14575           // cannot be a member of a union, nor can an array of such
14576           // objects.
14577           if (CheckNontrivialField(NewFD))
14578             NewFD->setInvalidDecl();
14579         }
14580       }
14581 
14582       // C++ [class.union]p1: If a union contains a member of reference type,
14583       // the program is ill-formed, except when compiling with MSVC extensions
14584       // enabled.
14585       if (EltTy->isReferenceType()) {
14586         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14587                                     diag::ext_union_member_of_reference_type :
14588                                     diag::err_union_member_of_reference_type)
14589           << NewFD->getDeclName() << EltTy;
14590         if (!getLangOpts().MicrosoftExt)
14591           NewFD->setInvalidDecl();
14592       }
14593     }
14594   }
14595 
14596   // FIXME: We need to pass in the attributes given an AST
14597   // representation, not a parser representation.
14598   if (D) {
14599     // FIXME: The current scope is almost... but not entirely... correct here.
14600     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14601 
14602     if (NewFD->hasAttrs())
14603       CheckAlignasUnderalignment(NewFD);
14604   }
14605 
14606   // In auto-retain/release, infer strong retension for fields of
14607   // retainable type.
14608   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14609     NewFD->setInvalidDecl();
14610 
14611   if (T.isObjCGCWeak())
14612     Diag(Loc, diag::warn_attribute_weak_on_field);
14613 
14614   NewFD->setAccess(AS);
14615   return NewFD;
14616 }
14617 
14618 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14619   assert(FD);
14620   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14621 
14622   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14623     return false;
14624 
14625   QualType EltTy = Context.getBaseElementType(FD->getType());
14626   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14627     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14628     if (RDecl->getDefinition()) {
14629       // We check for copy constructors before constructors
14630       // because otherwise we'll never get complaints about
14631       // copy constructors.
14632 
14633       CXXSpecialMember member = CXXInvalid;
14634       // We're required to check for any non-trivial constructors. Since the
14635       // implicit default constructor is suppressed if there are any
14636       // user-declared constructors, we just need to check that there is a
14637       // trivial default constructor and a trivial copy constructor. (We don't
14638       // worry about move constructors here, since this is a C++98 check.)
14639       if (RDecl->hasNonTrivialCopyConstructor())
14640         member = CXXCopyConstructor;
14641       else if (!RDecl->hasTrivialDefaultConstructor())
14642         member = CXXDefaultConstructor;
14643       else if (RDecl->hasNonTrivialCopyAssignment())
14644         member = CXXCopyAssignment;
14645       else if (RDecl->hasNonTrivialDestructor())
14646         member = CXXDestructor;
14647 
14648       if (member != CXXInvalid) {
14649         if (!getLangOpts().CPlusPlus11 &&
14650             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14651           // Objective-C++ ARC: it is an error to have a non-trivial field of
14652           // a union. However, system headers in Objective-C programs
14653           // occasionally have Objective-C lifetime objects within unions,
14654           // and rather than cause the program to fail, we make those
14655           // members unavailable.
14656           SourceLocation Loc = FD->getLocation();
14657           if (getSourceManager().isInSystemHeader(Loc)) {
14658             if (!FD->hasAttr<UnavailableAttr>())
14659               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14660                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14661             return false;
14662           }
14663         }
14664 
14665         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14666                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14667                diag::err_illegal_union_or_anon_struct_member)
14668           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14669         DiagnoseNontrivial(RDecl, member);
14670         return !getLangOpts().CPlusPlus11;
14671       }
14672     }
14673   }
14674 
14675   return false;
14676 }
14677 
14678 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14679 ///  AST enum value.
14680 static ObjCIvarDecl::AccessControl
14681 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14682   switch (ivarVisibility) {
14683   default: llvm_unreachable("Unknown visitibility kind");
14684   case tok::objc_private: return ObjCIvarDecl::Private;
14685   case tok::objc_public: return ObjCIvarDecl::Public;
14686   case tok::objc_protected: return ObjCIvarDecl::Protected;
14687   case tok::objc_package: return ObjCIvarDecl::Package;
14688   }
14689 }
14690 
14691 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14692 /// in order to create an IvarDecl object for it.
14693 Decl *Sema::ActOnIvar(Scope *S,
14694                                 SourceLocation DeclStart,
14695                                 Declarator &D, Expr *BitfieldWidth,
14696                                 tok::ObjCKeywordKind Visibility) {
14697 
14698   IdentifierInfo *II = D.getIdentifier();
14699   Expr *BitWidth = (Expr*)BitfieldWidth;
14700   SourceLocation Loc = DeclStart;
14701   if (II) Loc = D.getIdentifierLoc();
14702 
14703   // FIXME: Unnamed fields can be handled in various different ways, for
14704   // example, unnamed unions inject all members into the struct namespace!
14705 
14706   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14707   QualType T = TInfo->getType();
14708 
14709   if (BitWidth) {
14710     // 6.7.2.1p3, 6.7.2.1p4
14711     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14712     if (!BitWidth)
14713       D.setInvalidType();
14714   } else {
14715     // Not a bitfield.
14716 
14717     // validate II.
14718 
14719   }
14720   if (T->isReferenceType()) {
14721     Diag(Loc, diag::err_ivar_reference_type);
14722     D.setInvalidType();
14723   }
14724   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14725   // than a variably modified type.
14726   else if (T->isVariablyModifiedType()) {
14727     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14728     D.setInvalidType();
14729   }
14730 
14731   // Get the visibility (access control) for this ivar.
14732   ObjCIvarDecl::AccessControl ac =
14733     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14734                                         : ObjCIvarDecl::None;
14735   // Must set ivar's DeclContext to its enclosing interface.
14736   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14737   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14738     return nullptr;
14739   ObjCContainerDecl *EnclosingContext;
14740   if (ObjCImplementationDecl *IMPDecl =
14741       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14742     if (LangOpts.ObjCRuntime.isFragile()) {
14743     // Case of ivar declared in an implementation. Context is that of its class.
14744       EnclosingContext = IMPDecl->getClassInterface();
14745       assert(EnclosingContext && "Implementation has no class interface!");
14746     }
14747     else
14748       EnclosingContext = EnclosingDecl;
14749   } else {
14750     if (ObjCCategoryDecl *CDecl =
14751         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14752       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14753         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14754         return nullptr;
14755       }
14756     }
14757     EnclosingContext = EnclosingDecl;
14758   }
14759 
14760   // Construct the decl.
14761   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14762                                              DeclStart, Loc, II, T,
14763                                              TInfo, ac, (Expr *)BitfieldWidth);
14764 
14765   if (II) {
14766     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14767                                            ForRedeclaration);
14768     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14769         && !isa<TagDecl>(PrevDecl)) {
14770       Diag(Loc, diag::err_duplicate_member) << II;
14771       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14772       NewID->setInvalidDecl();
14773     }
14774   }
14775 
14776   // Process attributes attached to the ivar.
14777   ProcessDeclAttributes(S, NewID, D);
14778 
14779   if (D.isInvalidType())
14780     NewID->setInvalidDecl();
14781 
14782   // In ARC, infer 'retaining' for ivars of retainable type.
14783   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14784     NewID->setInvalidDecl();
14785 
14786   if (D.getDeclSpec().isModulePrivateSpecified())
14787     NewID->setModulePrivate();
14788 
14789   if (II) {
14790     // FIXME: When interfaces are DeclContexts, we'll need to add
14791     // these to the interface.
14792     S->AddDecl(NewID);
14793     IdResolver.AddDecl(NewID);
14794   }
14795 
14796   if (LangOpts.ObjCRuntime.isNonFragile() &&
14797       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14798     Diag(Loc, diag::warn_ivars_in_interface);
14799 
14800   return NewID;
14801 }
14802 
14803 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14804 /// class and class extensions. For every class \@interface and class
14805 /// extension \@interface, if the last ivar is a bitfield of any type,
14806 /// then add an implicit `char :0` ivar to the end of that interface.
14807 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14808                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14809   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14810     return;
14811 
14812   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14813   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14814 
14815   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14816     return;
14817   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14818   if (!ID) {
14819     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14820       if (!CD->IsClassExtension())
14821         return;
14822     }
14823     // No need to add this to end of @implementation.
14824     else
14825       return;
14826   }
14827   // All conditions are met. Add a new bitfield to the tail end of ivars.
14828   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14829   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14830 
14831   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14832                               DeclLoc, DeclLoc, nullptr,
14833                               Context.CharTy,
14834                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14835                                                                DeclLoc),
14836                               ObjCIvarDecl::Private, BW,
14837                               true);
14838   AllIvarDecls.push_back(Ivar);
14839 }
14840 
14841 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14842                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14843                        SourceLocation RBrac, AttributeList *Attr) {
14844   assert(EnclosingDecl && "missing record or interface decl");
14845 
14846   // If this is an Objective-C @implementation or category and we have
14847   // new fields here we should reset the layout of the interface since
14848   // it will now change.
14849   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14850     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14851     switch (DC->getKind()) {
14852     default: break;
14853     case Decl::ObjCCategory:
14854       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14855       break;
14856     case Decl::ObjCImplementation:
14857       Context.
14858         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14859       break;
14860     }
14861   }
14862 
14863   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14864 
14865   // Start counting up the number of named members; make sure to include
14866   // members of anonymous structs and unions in the total.
14867   unsigned NumNamedMembers = 0;
14868   if (Record) {
14869     for (const auto *I : Record->decls()) {
14870       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14871         if (IFD->getDeclName())
14872           ++NumNamedMembers;
14873     }
14874   }
14875 
14876   // Verify that all the fields are okay.
14877   SmallVector<FieldDecl*, 32> RecFields;
14878 
14879   bool ObjCFieldLifetimeErrReported = false;
14880   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14881        i != end; ++i) {
14882     FieldDecl *FD = cast<FieldDecl>(*i);
14883 
14884     // Get the type for the field.
14885     const Type *FDTy = FD->getType().getTypePtr();
14886 
14887     if (!FD->isAnonymousStructOrUnion()) {
14888       // Remember all fields written by the user.
14889       RecFields.push_back(FD);
14890     }
14891 
14892     // If the field is already invalid for some reason, don't emit more
14893     // diagnostics about it.
14894     if (FD->isInvalidDecl()) {
14895       EnclosingDecl->setInvalidDecl();
14896       continue;
14897     }
14898 
14899     // C99 6.7.2.1p2:
14900     //   A structure or union shall not contain a member with
14901     //   incomplete or function type (hence, a structure shall not
14902     //   contain an instance of itself, but may contain a pointer to
14903     //   an instance of itself), except that the last member of a
14904     //   structure with more than one named member may have incomplete
14905     //   array type; such a structure (and any union containing,
14906     //   possibly recursively, a member that is such a structure)
14907     //   shall not be a member of a structure or an element of an
14908     //   array.
14909     if (FDTy->isFunctionType()) {
14910       // Field declared as a function.
14911       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14912         << FD->getDeclName();
14913       FD->setInvalidDecl();
14914       EnclosingDecl->setInvalidDecl();
14915       continue;
14916     } else if (FDTy->isIncompleteArrayType() && Record &&
14917                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14918                 ((getLangOpts().MicrosoftExt ||
14919                   getLangOpts().CPlusPlus) &&
14920                  (i + 1 == Fields.end() || Record->isUnion())))) {
14921       // Flexible array member.
14922       // Microsoft and g++ is more permissive regarding flexible array.
14923       // It will accept flexible array in union and also
14924       // as the sole element of a struct/class.
14925       unsigned DiagID = 0;
14926       if (Record->isUnion())
14927         DiagID = getLangOpts().MicrosoftExt
14928                      ? diag::ext_flexible_array_union_ms
14929                      : getLangOpts().CPlusPlus
14930                            ? diag::ext_flexible_array_union_gnu
14931                            : diag::err_flexible_array_union;
14932       else if (NumNamedMembers < 1)
14933         DiagID = getLangOpts().MicrosoftExt
14934                      ? diag::ext_flexible_array_empty_aggregate_ms
14935                      : getLangOpts().CPlusPlus
14936                            ? diag::ext_flexible_array_empty_aggregate_gnu
14937                            : diag::err_flexible_array_empty_aggregate;
14938 
14939       if (DiagID)
14940         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14941                                         << Record->getTagKind();
14942       // While the layout of types that contain virtual bases is not specified
14943       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14944       // virtual bases after the derived members.  This would make a flexible
14945       // array member declared at the end of an object not adjacent to the end
14946       // of the type.
14947       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14948         if (RD->getNumVBases() != 0)
14949           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14950             << FD->getDeclName() << Record->getTagKind();
14951       if (!getLangOpts().C99)
14952         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14953           << FD->getDeclName() << Record->getTagKind();
14954 
14955       // If the element type has a non-trivial destructor, we would not
14956       // implicitly destroy the elements, so disallow it for now.
14957       //
14958       // FIXME: GCC allows this. We should probably either implicitly delete
14959       // the destructor of the containing class, or just allow this.
14960       QualType BaseElem = Context.getBaseElementType(FD->getType());
14961       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14962         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14963           << FD->getDeclName() << FD->getType();
14964         FD->setInvalidDecl();
14965         EnclosingDecl->setInvalidDecl();
14966         continue;
14967       }
14968       // Okay, we have a legal flexible array member at the end of the struct.
14969       Record->setHasFlexibleArrayMember(true);
14970     } else if (!FDTy->isDependentType() &&
14971                RequireCompleteType(FD->getLocation(), FD->getType(),
14972                                    diag::err_field_incomplete)) {
14973       // Incomplete type
14974       FD->setInvalidDecl();
14975       EnclosingDecl->setInvalidDecl();
14976       continue;
14977     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14978       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14979         // A type which contains a flexible array member is considered to be a
14980         // flexible array member.
14981         Record->setHasFlexibleArrayMember(true);
14982         if (!Record->isUnion()) {
14983           // If this is a struct/class and this is not the last element, reject
14984           // it.  Note that GCC supports variable sized arrays in the middle of
14985           // structures.
14986           if (i + 1 != Fields.end())
14987             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14988               << FD->getDeclName() << FD->getType();
14989           else {
14990             // We support flexible arrays at the end of structs in
14991             // other structs as an extension.
14992             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14993               << FD->getDeclName();
14994           }
14995         }
14996       }
14997       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14998           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14999                                  diag::err_abstract_type_in_decl,
15000                                  AbstractIvarType)) {
15001         // Ivars can not have abstract class types
15002         FD->setInvalidDecl();
15003       }
15004       if (Record && FDTTy->getDecl()->hasObjectMember())
15005         Record->setHasObjectMember(true);
15006       if (Record && FDTTy->getDecl()->hasVolatileMember())
15007         Record->setHasVolatileMember(true);
15008     } else if (FDTy->isObjCObjectType()) {
15009       /// A field cannot be an Objective-c object
15010       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15011         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15012       QualType T = Context.getObjCObjectPointerType(FD->getType());
15013       FD->setType(T);
15014     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15015                Record && !ObjCFieldLifetimeErrReported &&
15016                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15017       // It's an error in ARC or Weak if a field has lifetime.
15018       // We don't want to report this in a system header, though,
15019       // so we just make the field unavailable.
15020       // FIXME: that's really not sufficient; we need to make the type
15021       // itself invalid to, say, initialize or copy.
15022       QualType T = FD->getType();
15023       if (T.hasNonTrivialObjCLifetime()) {
15024         SourceLocation loc = FD->getLocation();
15025         if (getSourceManager().isInSystemHeader(loc)) {
15026           if (!FD->hasAttr<UnavailableAttr>()) {
15027             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15028                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15029           }
15030         } else {
15031           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15032             << T->isBlockPointerType() << Record->getTagKind();
15033         }
15034         ObjCFieldLifetimeErrReported = true;
15035       }
15036     } else if (getLangOpts().ObjC1 &&
15037                getLangOpts().getGC() != LangOptions::NonGC &&
15038                Record && !Record->hasObjectMember()) {
15039       if (FD->getType()->isObjCObjectPointerType() ||
15040           FD->getType().isObjCGCStrong())
15041         Record->setHasObjectMember(true);
15042       else if (Context.getAsArrayType(FD->getType())) {
15043         QualType BaseType = Context.getBaseElementType(FD->getType());
15044         if (BaseType->isRecordType() &&
15045             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15046           Record->setHasObjectMember(true);
15047         else if (BaseType->isObjCObjectPointerType() ||
15048                  BaseType.isObjCGCStrong())
15049                Record->setHasObjectMember(true);
15050       }
15051     }
15052     if (Record && FD->getType().isVolatileQualified())
15053       Record->setHasVolatileMember(true);
15054     // Keep track of the number of named members.
15055     if (FD->getIdentifier())
15056       ++NumNamedMembers;
15057   }
15058 
15059   // Okay, we successfully defined 'Record'.
15060   if (Record) {
15061     bool Completed = false;
15062     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15063       if (!CXXRecord->isInvalidDecl()) {
15064         // Set access bits correctly on the directly-declared conversions.
15065         for (CXXRecordDecl::conversion_iterator
15066                I = CXXRecord->conversion_begin(),
15067                E = CXXRecord->conversion_end(); I != E; ++I)
15068           I.setAccess((*I)->getAccess());
15069       }
15070 
15071       if (!CXXRecord->isDependentType()) {
15072         if (CXXRecord->hasUserDeclaredDestructor()) {
15073           // Adjust user-defined destructor exception spec.
15074           if (getLangOpts().CPlusPlus11)
15075             AdjustDestructorExceptionSpec(CXXRecord,
15076                                           CXXRecord->getDestructor());
15077         }
15078 
15079         if (!CXXRecord->isInvalidDecl()) {
15080           // Add any implicitly-declared members to this class.
15081           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15082 
15083           // If we have virtual base classes, we may end up finding multiple
15084           // final overriders for a given virtual function. Check for this
15085           // problem now.
15086           if (CXXRecord->getNumVBases()) {
15087             CXXFinalOverriderMap FinalOverriders;
15088             CXXRecord->getFinalOverriders(FinalOverriders);
15089 
15090             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15091                                              MEnd = FinalOverriders.end();
15092                  M != MEnd; ++M) {
15093               for (OverridingMethods::iterator SO = M->second.begin(),
15094                                             SOEnd = M->second.end();
15095                    SO != SOEnd; ++SO) {
15096                 assert(SO->second.size() > 0 &&
15097                        "Virtual function without overridding functions?");
15098                 if (SO->second.size() == 1)
15099                   continue;
15100 
15101                 // C++ [class.virtual]p2:
15102                 //   In a derived class, if a virtual member function of a base
15103                 //   class subobject has more than one final overrider the
15104                 //   program is ill-formed.
15105                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15106                   << (const NamedDecl *)M->first << Record;
15107                 Diag(M->first->getLocation(),
15108                      diag::note_overridden_virtual_function);
15109                 for (OverridingMethods::overriding_iterator
15110                           OM = SO->second.begin(),
15111                        OMEnd = SO->second.end();
15112                      OM != OMEnd; ++OM)
15113                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15114                     << (const NamedDecl *)M->first << OM->Method->getParent();
15115 
15116                 Record->setInvalidDecl();
15117               }
15118             }
15119             CXXRecord->completeDefinition(&FinalOverriders);
15120             Completed = true;
15121           }
15122         }
15123       }
15124     }
15125 
15126     if (!Completed)
15127       Record->completeDefinition();
15128 
15129     // We may have deferred checking for a deleted destructor. Check now.
15130     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15131       auto *Dtor = CXXRecord->getDestructor();
15132       if (Dtor && Dtor->isImplicit() &&
15133           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
15134         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15135     }
15136 
15137     if (Record->hasAttrs()) {
15138       CheckAlignasUnderalignment(Record);
15139 
15140       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15141         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15142                                            IA->getRange(), IA->getBestCase(),
15143                                            IA->getSemanticSpelling());
15144     }
15145 
15146     // Check if the structure/union declaration is a type that can have zero
15147     // size in C. For C this is a language extension, for C++ it may cause
15148     // compatibility problems.
15149     bool CheckForZeroSize;
15150     if (!getLangOpts().CPlusPlus) {
15151       CheckForZeroSize = true;
15152     } else {
15153       // For C++ filter out types that cannot be referenced in C code.
15154       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15155       CheckForZeroSize =
15156           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15157           !CXXRecord->isDependentType() &&
15158           CXXRecord->isCLike();
15159     }
15160     if (CheckForZeroSize) {
15161       bool ZeroSize = true;
15162       bool IsEmpty = true;
15163       unsigned NonBitFields = 0;
15164       for (RecordDecl::field_iterator I = Record->field_begin(),
15165                                       E = Record->field_end();
15166            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15167         IsEmpty = false;
15168         if (I->isUnnamedBitfield()) {
15169           if (I->getBitWidthValue(Context) > 0)
15170             ZeroSize = false;
15171         } else {
15172           ++NonBitFields;
15173           QualType FieldType = I->getType();
15174           if (FieldType->isIncompleteType() ||
15175               !Context.getTypeSizeInChars(FieldType).isZero())
15176             ZeroSize = false;
15177         }
15178       }
15179 
15180       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15181       // allowed in C++, but warn if its declaration is inside
15182       // extern "C" block.
15183       if (ZeroSize) {
15184         Diag(RecLoc, getLangOpts().CPlusPlus ?
15185                          diag::warn_zero_size_struct_union_in_extern_c :
15186                          diag::warn_zero_size_struct_union_compat)
15187           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15188       }
15189 
15190       // Structs without named members are extension in C (C99 6.7.2.1p7),
15191       // but are accepted by GCC.
15192       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15193         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15194                                diag::ext_no_named_members_in_struct_union)
15195           << Record->isUnion();
15196       }
15197     }
15198   } else {
15199     ObjCIvarDecl **ClsFields =
15200       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15201     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15202       ID->setEndOfDefinitionLoc(RBrac);
15203       // Add ivar's to class's DeclContext.
15204       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15205         ClsFields[i]->setLexicalDeclContext(ID);
15206         ID->addDecl(ClsFields[i]);
15207       }
15208       // Must enforce the rule that ivars in the base classes may not be
15209       // duplicates.
15210       if (ID->getSuperClass())
15211         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15212     } else if (ObjCImplementationDecl *IMPDecl =
15213                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15214       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15215       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15216         // Ivar declared in @implementation never belongs to the implementation.
15217         // Only it is in implementation's lexical context.
15218         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15219       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15220       IMPDecl->setIvarLBraceLoc(LBrac);
15221       IMPDecl->setIvarRBraceLoc(RBrac);
15222     } else if (ObjCCategoryDecl *CDecl =
15223                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15224       // case of ivars in class extension; all other cases have been
15225       // reported as errors elsewhere.
15226       // FIXME. Class extension does not have a LocEnd field.
15227       // CDecl->setLocEnd(RBrac);
15228       // Add ivar's to class extension's DeclContext.
15229       // Diagnose redeclaration of private ivars.
15230       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15231       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15232         if (IDecl) {
15233           if (const ObjCIvarDecl *ClsIvar =
15234               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15235             Diag(ClsFields[i]->getLocation(),
15236                  diag::err_duplicate_ivar_declaration);
15237             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15238             continue;
15239           }
15240           for (const auto *Ext : IDecl->known_extensions()) {
15241             if (const ObjCIvarDecl *ClsExtIvar
15242                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15243               Diag(ClsFields[i]->getLocation(),
15244                    diag::err_duplicate_ivar_declaration);
15245               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15246               continue;
15247             }
15248           }
15249         }
15250         ClsFields[i]->setLexicalDeclContext(CDecl);
15251         CDecl->addDecl(ClsFields[i]);
15252       }
15253       CDecl->setIvarLBraceLoc(LBrac);
15254       CDecl->setIvarRBraceLoc(RBrac);
15255     }
15256   }
15257 
15258   if (Attr)
15259     ProcessDeclAttributeList(S, Record, Attr);
15260 }
15261 
15262 /// \brief Determine whether the given integral value is representable within
15263 /// the given type T.
15264 static bool isRepresentableIntegerValue(ASTContext &Context,
15265                                         llvm::APSInt &Value,
15266                                         QualType T) {
15267   assert(T->isIntegralType(Context) && "Integral type required!");
15268   unsigned BitWidth = Context.getIntWidth(T);
15269 
15270   if (Value.isUnsigned() || Value.isNonNegative()) {
15271     if (T->isSignedIntegerOrEnumerationType())
15272       --BitWidth;
15273     return Value.getActiveBits() <= BitWidth;
15274   }
15275   return Value.getMinSignedBits() <= BitWidth;
15276 }
15277 
15278 // \brief Given an integral type, return the next larger integral type
15279 // (or a NULL type of no such type exists).
15280 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15281   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15282   // enum checking below.
15283   assert(T->isIntegralType(Context) && "Integral type required!");
15284   const unsigned NumTypes = 4;
15285   QualType SignedIntegralTypes[NumTypes] = {
15286     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15287   };
15288   QualType UnsignedIntegralTypes[NumTypes] = {
15289     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15290     Context.UnsignedLongLongTy
15291   };
15292 
15293   unsigned BitWidth = Context.getTypeSize(T);
15294   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15295                                                         : UnsignedIntegralTypes;
15296   for (unsigned I = 0; I != NumTypes; ++I)
15297     if (Context.getTypeSize(Types[I]) > BitWidth)
15298       return Types[I];
15299 
15300   return QualType();
15301 }
15302 
15303 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15304                                           EnumConstantDecl *LastEnumConst,
15305                                           SourceLocation IdLoc,
15306                                           IdentifierInfo *Id,
15307                                           Expr *Val) {
15308   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15309   llvm::APSInt EnumVal(IntWidth);
15310   QualType EltTy;
15311 
15312   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15313     Val = nullptr;
15314 
15315   if (Val)
15316     Val = DefaultLvalueConversion(Val).get();
15317 
15318   if (Val) {
15319     if (Enum->isDependentType() || Val->isTypeDependent())
15320       EltTy = Context.DependentTy;
15321     else {
15322       SourceLocation ExpLoc;
15323       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15324           !getLangOpts().MSVCCompat) {
15325         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15326         // constant-expression in the enumerator-definition shall be a converted
15327         // constant expression of the underlying type.
15328         EltTy = Enum->getIntegerType();
15329         ExprResult Converted =
15330           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15331                                            CCEK_Enumerator);
15332         if (Converted.isInvalid())
15333           Val = nullptr;
15334         else
15335           Val = Converted.get();
15336       } else if (!Val->isValueDependent() &&
15337                  !(Val = VerifyIntegerConstantExpression(Val,
15338                                                          &EnumVal).get())) {
15339         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15340       } else {
15341         if (Enum->isFixed()) {
15342           EltTy = Enum->getIntegerType();
15343 
15344           // In Obj-C and Microsoft mode, require the enumeration value to be
15345           // representable in the underlying type of the enumeration. In C++11,
15346           // we perform a non-narrowing conversion as part of converted constant
15347           // expression checking.
15348           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15349             if (getLangOpts().MSVCCompat) {
15350               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15351               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15352             } else
15353               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15354           } else
15355             Val = ImpCastExprToType(Val, EltTy,
15356                                     EltTy->isBooleanType() ?
15357                                     CK_IntegralToBoolean : CK_IntegralCast)
15358                     .get();
15359         } else if (getLangOpts().CPlusPlus) {
15360           // C++11 [dcl.enum]p5:
15361           //   If the underlying type is not fixed, the type of each enumerator
15362           //   is the type of its initializing value:
15363           //     - If an initializer is specified for an enumerator, the
15364           //       initializing value has the same type as the expression.
15365           EltTy = Val->getType();
15366         } else {
15367           // C99 6.7.2.2p2:
15368           //   The expression that defines the value of an enumeration constant
15369           //   shall be an integer constant expression that has a value
15370           //   representable as an int.
15371 
15372           // Complain if the value is not representable in an int.
15373           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15374             Diag(IdLoc, diag::ext_enum_value_not_int)
15375               << EnumVal.toString(10) << Val->getSourceRange()
15376               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15377           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15378             // Force the type of the expression to 'int'.
15379             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15380           }
15381           EltTy = Val->getType();
15382         }
15383       }
15384     }
15385   }
15386 
15387   if (!Val) {
15388     if (Enum->isDependentType())
15389       EltTy = Context.DependentTy;
15390     else if (!LastEnumConst) {
15391       // C++0x [dcl.enum]p5:
15392       //   If the underlying type is not fixed, the type of each enumerator
15393       //   is the type of its initializing value:
15394       //     - If no initializer is specified for the first enumerator, the
15395       //       initializing value has an unspecified integral type.
15396       //
15397       // GCC uses 'int' for its unspecified integral type, as does
15398       // C99 6.7.2.2p3.
15399       if (Enum->isFixed()) {
15400         EltTy = Enum->getIntegerType();
15401       }
15402       else {
15403         EltTy = Context.IntTy;
15404       }
15405     } else {
15406       // Assign the last value + 1.
15407       EnumVal = LastEnumConst->getInitVal();
15408       ++EnumVal;
15409       EltTy = LastEnumConst->getType();
15410 
15411       // Check for overflow on increment.
15412       if (EnumVal < LastEnumConst->getInitVal()) {
15413         // C++0x [dcl.enum]p5:
15414         //   If the underlying type is not fixed, the type of each enumerator
15415         //   is the type of its initializing value:
15416         //
15417         //     - Otherwise the type of the initializing value is the same as
15418         //       the type of the initializing value of the preceding enumerator
15419         //       unless the incremented value is not representable in that type,
15420         //       in which case the type is an unspecified integral type
15421         //       sufficient to contain the incremented value. If no such type
15422         //       exists, the program is ill-formed.
15423         QualType T = getNextLargerIntegralType(Context, EltTy);
15424         if (T.isNull() || Enum->isFixed()) {
15425           // There is no integral type larger enough to represent this
15426           // value. Complain, then allow the value to wrap around.
15427           EnumVal = LastEnumConst->getInitVal();
15428           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15429           ++EnumVal;
15430           if (Enum->isFixed())
15431             // When the underlying type is fixed, this is ill-formed.
15432             Diag(IdLoc, diag::err_enumerator_wrapped)
15433               << EnumVal.toString(10)
15434               << EltTy;
15435           else
15436             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15437               << EnumVal.toString(10);
15438         } else {
15439           EltTy = T;
15440         }
15441 
15442         // Retrieve the last enumerator's value, extent that type to the
15443         // type that is supposed to be large enough to represent the incremented
15444         // value, then increment.
15445         EnumVal = LastEnumConst->getInitVal();
15446         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15447         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15448         ++EnumVal;
15449 
15450         // If we're not in C++, diagnose the overflow of enumerator values,
15451         // which in C99 means that the enumerator value is not representable in
15452         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15453         // permits enumerator values that are representable in some larger
15454         // integral type.
15455         if (!getLangOpts().CPlusPlus && !T.isNull())
15456           Diag(IdLoc, diag::warn_enum_value_overflow);
15457       } else if (!getLangOpts().CPlusPlus &&
15458                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15459         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15460         Diag(IdLoc, diag::ext_enum_value_not_int)
15461           << EnumVal.toString(10) << 1;
15462       }
15463     }
15464   }
15465 
15466   if (!EltTy->isDependentType()) {
15467     // Make the enumerator value match the signedness and size of the
15468     // enumerator's type.
15469     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15470     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15471   }
15472 
15473   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15474                                   Val, EnumVal);
15475 }
15476 
15477 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15478                                                 SourceLocation IILoc) {
15479   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15480       !getLangOpts().CPlusPlus)
15481     return SkipBodyInfo();
15482 
15483   // We have an anonymous enum definition. Look up the first enumerator to
15484   // determine if we should merge the definition with an existing one and
15485   // skip the body.
15486   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15487                                          ForRedeclaration);
15488   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15489   if (!PrevECD)
15490     return SkipBodyInfo();
15491 
15492   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15493   NamedDecl *Hidden;
15494   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15495     SkipBodyInfo Skip;
15496     Skip.Previous = Hidden;
15497     return Skip;
15498   }
15499 
15500   return SkipBodyInfo();
15501 }
15502 
15503 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15504                               SourceLocation IdLoc, IdentifierInfo *Id,
15505                               AttributeList *Attr,
15506                               SourceLocation EqualLoc, Expr *Val) {
15507   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15508   EnumConstantDecl *LastEnumConst =
15509     cast_or_null<EnumConstantDecl>(lastEnumConst);
15510 
15511   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15512   // we find one that is.
15513   S = getNonFieldDeclScope(S);
15514 
15515   // Verify that there isn't already something declared with this name in this
15516   // scope.
15517   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15518                                          ForRedeclaration);
15519   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15520     // Maybe we will complain about the shadowed template parameter.
15521     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15522     // Just pretend that we didn't see the previous declaration.
15523     PrevDecl = nullptr;
15524   }
15525 
15526   // C++ [class.mem]p15:
15527   // If T is the name of a class, then each of the following shall have a name
15528   // different from T:
15529   // - every enumerator of every member of class T that is an unscoped
15530   // enumerated type
15531   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15532     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15533                             DeclarationNameInfo(Id, IdLoc));
15534 
15535   EnumConstantDecl *New =
15536     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15537   if (!New)
15538     return nullptr;
15539 
15540   if (PrevDecl) {
15541     // When in C++, we may get a TagDecl with the same name; in this case the
15542     // enum constant will 'hide' the tag.
15543     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15544            "Received TagDecl when not in C++!");
15545     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15546         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15547       if (isa<EnumConstantDecl>(PrevDecl))
15548         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15549       else
15550         Diag(IdLoc, diag::err_redefinition) << Id;
15551       notePreviousDefinition(PrevDecl, IdLoc);
15552       return nullptr;
15553     }
15554   }
15555 
15556   // Process attributes.
15557   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15558   AddPragmaAttributes(S, New);
15559 
15560   // Register this decl in the current scope stack.
15561   New->setAccess(TheEnumDecl->getAccess());
15562   PushOnScopeChains(New, S);
15563 
15564   ActOnDocumentableDecl(New);
15565 
15566   return New;
15567 }
15568 
15569 // Returns true when the enum initial expression does not trigger the
15570 // duplicate enum warning.  A few common cases are exempted as follows:
15571 // Element2 = Element1
15572 // Element2 = Element1 + 1
15573 // Element2 = Element1 - 1
15574 // Where Element2 and Element1 are from the same enum.
15575 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15576   Expr *InitExpr = ECD->getInitExpr();
15577   if (!InitExpr)
15578     return true;
15579   InitExpr = InitExpr->IgnoreImpCasts();
15580 
15581   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15582     if (!BO->isAdditiveOp())
15583       return true;
15584     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15585     if (!IL)
15586       return true;
15587     if (IL->getValue() != 1)
15588       return true;
15589 
15590     InitExpr = BO->getLHS();
15591   }
15592 
15593   // This checks if the elements are from the same enum.
15594   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15595   if (!DRE)
15596     return true;
15597 
15598   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15599   if (!EnumConstant)
15600     return true;
15601 
15602   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15603       Enum)
15604     return true;
15605 
15606   return false;
15607 }
15608 
15609 namespace {
15610 struct DupKey {
15611   int64_t val;
15612   bool isTombstoneOrEmptyKey;
15613   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15614     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15615 };
15616 
15617 static DupKey GetDupKey(const llvm::APSInt& Val) {
15618   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15619                 false);
15620 }
15621 
15622 struct DenseMapInfoDupKey {
15623   static DupKey getEmptyKey() { return DupKey(0, true); }
15624   static DupKey getTombstoneKey() { return DupKey(1, true); }
15625   static unsigned getHashValue(const DupKey Key) {
15626     return (unsigned)(Key.val * 37);
15627   }
15628   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15629     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15630            LHS.val == RHS.val;
15631   }
15632 };
15633 } // end anonymous namespace
15634 
15635 // Emits a warning when an element is implicitly set a value that
15636 // a previous element has already been set to.
15637 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15638                                         EnumDecl *Enum,
15639                                         QualType EnumType) {
15640   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15641     return;
15642   // Avoid anonymous enums
15643   if (!Enum->getIdentifier())
15644     return;
15645 
15646   // Only check for small enums.
15647   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15648     return;
15649 
15650   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15651   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15652 
15653   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15654   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15655           ValueToVectorMap;
15656 
15657   DuplicatesVector DupVector;
15658   ValueToVectorMap EnumMap;
15659 
15660   // Populate the EnumMap with all values represented by enum constants without
15661   // an initialier.
15662   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15663     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15664 
15665     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15666     // this constant.  Skip this enum since it may be ill-formed.
15667     if (!ECD) {
15668       return;
15669     }
15670 
15671     if (ECD->getInitExpr())
15672       continue;
15673 
15674     DupKey Key = GetDupKey(ECD->getInitVal());
15675     DeclOrVector &Entry = EnumMap[Key];
15676 
15677     // First time encountering this value.
15678     if (Entry.isNull())
15679       Entry = ECD;
15680   }
15681 
15682   // Create vectors for any values that has duplicates.
15683   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15684     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15685     if (!ValidDuplicateEnum(ECD, Enum))
15686       continue;
15687 
15688     DupKey Key = GetDupKey(ECD->getInitVal());
15689 
15690     DeclOrVector& Entry = EnumMap[Key];
15691     if (Entry.isNull())
15692       continue;
15693 
15694     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15695       // Ensure constants are different.
15696       if (D == ECD)
15697         continue;
15698 
15699       // Create new vector and push values onto it.
15700       ECDVector *Vec = new ECDVector();
15701       Vec->push_back(D);
15702       Vec->push_back(ECD);
15703 
15704       // Update entry to point to the duplicates vector.
15705       Entry = Vec;
15706 
15707       // Store the vector somewhere we can consult later for quick emission of
15708       // diagnostics.
15709       DupVector.push_back(Vec);
15710       continue;
15711     }
15712 
15713     ECDVector *Vec = Entry.get<ECDVector*>();
15714     // Make sure constants are not added more than once.
15715     if (*Vec->begin() == ECD)
15716       continue;
15717 
15718     Vec->push_back(ECD);
15719   }
15720 
15721   // Emit diagnostics.
15722   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15723                                   DupVectorEnd = DupVector.end();
15724        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15725     ECDVector *Vec = *DupVectorIter;
15726     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15727 
15728     // Emit warning for one enum constant.
15729     ECDVector::iterator I = Vec->begin();
15730     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15731       << (*I)->getName() << (*I)->getInitVal().toString(10)
15732       << (*I)->getSourceRange();
15733     ++I;
15734 
15735     // Emit one note for each of the remaining enum constants with
15736     // the same value.
15737     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15738       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15739         << (*I)->getName() << (*I)->getInitVal().toString(10)
15740         << (*I)->getSourceRange();
15741     delete Vec;
15742   }
15743 }
15744 
15745 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15746                              bool AllowMask) const {
15747   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15748   assert(ED->isCompleteDefinition() && "expected enum definition");
15749 
15750   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15751   llvm::APInt &FlagBits = R.first->second;
15752 
15753   if (R.second) {
15754     for (auto *E : ED->enumerators()) {
15755       const auto &EVal = E->getInitVal();
15756       // Only single-bit enumerators introduce new flag values.
15757       if (EVal.isPowerOf2())
15758         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15759     }
15760   }
15761 
15762   // A value is in a flag enum if either its bits are a subset of the enum's
15763   // flag bits (the first condition) or we are allowing masks and the same is
15764   // true of its complement (the second condition). When masks are allowed, we
15765   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15766   //
15767   // While it's true that any value could be used as a mask, the assumption is
15768   // that a mask will have all of the insignificant bits set. Anything else is
15769   // likely a logic error.
15770   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15771   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15772 }
15773 
15774 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15775                          Decl *EnumDeclX,
15776                          ArrayRef<Decl *> Elements,
15777                          Scope *S, AttributeList *Attr) {
15778   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15779   QualType EnumType = Context.getTypeDeclType(Enum);
15780 
15781   if (Attr)
15782     ProcessDeclAttributeList(S, Enum, Attr);
15783 
15784   if (Enum->isDependentType()) {
15785     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15786       EnumConstantDecl *ECD =
15787         cast_or_null<EnumConstantDecl>(Elements[i]);
15788       if (!ECD) continue;
15789 
15790       ECD->setType(EnumType);
15791     }
15792 
15793     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15794     return;
15795   }
15796 
15797   // TODO: If the result value doesn't fit in an int, it must be a long or long
15798   // long value.  ISO C does not support this, but GCC does as an extension,
15799   // emit a warning.
15800   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15801   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15802   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15803 
15804   // Verify that all the values are okay, compute the size of the values, and
15805   // reverse the list.
15806   unsigned NumNegativeBits = 0;
15807   unsigned NumPositiveBits = 0;
15808 
15809   // Keep track of whether all elements have type int.
15810   bool AllElementsInt = true;
15811 
15812   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15813     EnumConstantDecl *ECD =
15814       cast_or_null<EnumConstantDecl>(Elements[i]);
15815     if (!ECD) continue;  // Already issued a diagnostic.
15816 
15817     const llvm::APSInt &InitVal = ECD->getInitVal();
15818 
15819     // Keep track of the size of positive and negative values.
15820     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15821       NumPositiveBits = std::max(NumPositiveBits,
15822                                  (unsigned)InitVal.getActiveBits());
15823     else
15824       NumNegativeBits = std::max(NumNegativeBits,
15825                                  (unsigned)InitVal.getMinSignedBits());
15826 
15827     // Keep track of whether every enum element has type int (very commmon).
15828     if (AllElementsInt)
15829       AllElementsInt = ECD->getType() == Context.IntTy;
15830   }
15831 
15832   // Figure out the type that should be used for this enum.
15833   QualType BestType;
15834   unsigned BestWidth;
15835 
15836   // C++0x N3000 [conv.prom]p3:
15837   //   An rvalue of an unscoped enumeration type whose underlying
15838   //   type is not fixed can be converted to an rvalue of the first
15839   //   of the following types that can represent all the values of
15840   //   the enumeration: int, unsigned int, long int, unsigned long
15841   //   int, long long int, or unsigned long long int.
15842   // C99 6.4.4.3p2:
15843   //   An identifier declared as an enumeration constant has type int.
15844   // The C99 rule is modified by a gcc extension
15845   QualType BestPromotionType;
15846 
15847   bool Packed = Enum->hasAttr<PackedAttr>();
15848   // -fshort-enums is the equivalent to specifying the packed attribute on all
15849   // enum definitions.
15850   if (LangOpts.ShortEnums)
15851     Packed = true;
15852 
15853   if (Enum->isFixed()) {
15854     BestType = Enum->getIntegerType();
15855     if (BestType->isPromotableIntegerType())
15856       BestPromotionType = Context.getPromotedIntegerType(BestType);
15857     else
15858       BestPromotionType = BestType;
15859 
15860     BestWidth = Context.getIntWidth(BestType);
15861   }
15862   else if (NumNegativeBits) {
15863     // If there is a negative value, figure out the smallest integer type (of
15864     // int/long/longlong) that fits.
15865     // If it's packed, check also if it fits a char or a short.
15866     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15867       BestType = Context.SignedCharTy;
15868       BestWidth = CharWidth;
15869     } else if (Packed && NumNegativeBits <= ShortWidth &&
15870                NumPositiveBits < ShortWidth) {
15871       BestType = Context.ShortTy;
15872       BestWidth = ShortWidth;
15873     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15874       BestType = Context.IntTy;
15875       BestWidth = IntWidth;
15876     } else {
15877       BestWidth = Context.getTargetInfo().getLongWidth();
15878 
15879       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15880         BestType = Context.LongTy;
15881       } else {
15882         BestWidth = Context.getTargetInfo().getLongLongWidth();
15883 
15884         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15885           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15886         BestType = Context.LongLongTy;
15887       }
15888     }
15889     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15890   } else {
15891     // If there is no negative value, figure out the smallest type that fits
15892     // all of the enumerator values.
15893     // If it's packed, check also if it fits a char or a short.
15894     if (Packed && NumPositiveBits <= CharWidth) {
15895       BestType = Context.UnsignedCharTy;
15896       BestPromotionType = Context.IntTy;
15897       BestWidth = CharWidth;
15898     } else if (Packed && NumPositiveBits <= ShortWidth) {
15899       BestType = Context.UnsignedShortTy;
15900       BestPromotionType = Context.IntTy;
15901       BestWidth = ShortWidth;
15902     } else if (NumPositiveBits <= IntWidth) {
15903       BestType = Context.UnsignedIntTy;
15904       BestWidth = IntWidth;
15905       BestPromotionType
15906         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15907                            ? Context.UnsignedIntTy : Context.IntTy;
15908     } else if (NumPositiveBits <=
15909                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15910       BestType = Context.UnsignedLongTy;
15911       BestPromotionType
15912         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15913                            ? Context.UnsignedLongTy : Context.LongTy;
15914     } else {
15915       BestWidth = Context.getTargetInfo().getLongLongWidth();
15916       assert(NumPositiveBits <= BestWidth &&
15917              "How could an initializer get larger than ULL?");
15918       BestType = Context.UnsignedLongLongTy;
15919       BestPromotionType
15920         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15921                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15922     }
15923   }
15924 
15925   // Loop over all of the enumerator constants, changing their types to match
15926   // the type of the enum if needed.
15927   for (auto *D : Elements) {
15928     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15929     if (!ECD) continue;  // Already issued a diagnostic.
15930 
15931     // Standard C says the enumerators have int type, but we allow, as an
15932     // extension, the enumerators to be larger than int size.  If each
15933     // enumerator value fits in an int, type it as an int, otherwise type it the
15934     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15935     // that X has type 'int', not 'unsigned'.
15936 
15937     // Determine whether the value fits into an int.
15938     llvm::APSInt InitVal = ECD->getInitVal();
15939 
15940     // If it fits into an integer type, force it.  Otherwise force it to match
15941     // the enum decl type.
15942     QualType NewTy;
15943     unsigned NewWidth;
15944     bool NewSign;
15945     if (!getLangOpts().CPlusPlus &&
15946         !Enum->isFixed() &&
15947         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15948       NewTy = Context.IntTy;
15949       NewWidth = IntWidth;
15950       NewSign = true;
15951     } else if (ECD->getType() == BestType) {
15952       // Already the right type!
15953       if (getLangOpts().CPlusPlus)
15954         // C++ [dcl.enum]p4: Following the closing brace of an
15955         // enum-specifier, each enumerator has the type of its
15956         // enumeration.
15957         ECD->setType(EnumType);
15958       continue;
15959     } else {
15960       NewTy = BestType;
15961       NewWidth = BestWidth;
15962       NewSign = BestType->isSignedIntegerOrEnumerationType();
15963     }
15964 
15965     // Adjust the APSInt value.
15966     InitVal = InitVal.extOrTrunc(NewWidth);
15967     InitVal.setIsSigned(NewSign);
15968     ECD->setInitVal(InitVal);
15969 
15970     // Adjust the Expr initializer and type.
15971     if (ECD->getInitExpr() &&
15972         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15973       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15974                                                 CK_IntegralCast,
15975                                                 ECD->getInitExpr(),
15976                                                 /*base paths*/ nullptr,
15977                                                 VK_RValue));
15978     if (getLangOpts().CPlusPlus)
15979       // C++ [dcl.enum]p4: Following the closing brace of an
15980       // enum-specifier, each enumerator has the type of its
15981       // enumeration.
15982       ECD->setType(EnumType);
15983     else
15984       ECD->setType(NewTy);
15985   }
15986 
15987   Enum->completeDefinition(BestType, BestPromotionType,
15988                            NumPositiveBits, NumNegativeBits);
15989 
15990   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15991 
15992   if (Enum->isClosedFlag()) {
15993     for (Decl *D : Elements) {
15994       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15995       if (!ECD) continue;  // Already issued a diagnostic.
15996 
15997       llvm::APSInt InitVal = ECD->getInitVal();
15998       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15999           !IsValueInFlagEnum(Enum, InitVal, true))
16000         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16001           << ECD << Enum;
16002     }
16003   }
16004 
16005   // Now that the enum type is defined, ensure it's not been underaligned.
16006   if (Enum->hasAttrs())
16007     CheckAlignasUnderalignment(Enum);
16008 }
16009 
16010 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16011                                   SourceLocation StartLoc,
16012                                   SourceLocation EndLoc) {
16013   StringLiteral *AsmString = cast<StringLiteral>(expr);
16014 
16015   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16016                                                    AsmString, StartLoc,
16017                                                    EndLoc);
16018   CurContext->addDecl(New);
16019   return New;
16020 }
16021 
16022 static void checkModuleImportContext(Sema &S, Module *M,
16023                                      SourceLocation ImportLoc, DeclContext *DC,
16024                                      bool FromInclude = false) {
16025   SourceLocation ExternCLoc;
16026 
16027   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16028     switch (LSD->getLanguage()) {
16029     case LinkageSpecDecl::lang_c:
16030       if (ExternCLoc.isInvalid())
16031         ExternCLoc = LSD->getLocStart();
16032       break;
16033     case LinkageSpecDecl::lang_cxx:
16034       break;
16035     }
16036     DC = LSD->getParent();
16037   }
16038 
16039   while (isa<LinkageSpecDecl>(DC))
16040     DC = DC->getParent();
16041 
16042   if (!isa<TranslationUnitDecl>(DC)) {
16043     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16044                           ? diag::ext_module_import_not_at_top_level_noop
16045                           : diag::err_module_import_not_at_top_level_fatal)
16046         << M->getFullModuleName() << DC;
16047     S.Diag(cast<Decl>(DC)->getLocStart(),
16048            diag::note_module_import_not_at_top_level) << DC;
16049   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16050     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16051       << M->getFullModuleName();
16052     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16053   }
16054 }
16055 
16056 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16057                                            SourceLocation ModuleLoc,
16058                                            ModuleDeclKind MDK,
16059                                            ModuleIdPath Path) {
16060   assert(getLangOpts().ModulesTS &&
16061          "should only have module decl in modules TS");
16062 
16063   // A module implementation unit requires that we are not compiling a module
16064   // of any kind. A module interface unit requires that we are not compiling a
16065   // module map.
16066   switch (getLangOpts().getCompilingModule()) {
16067   case LangOptions::CMK_None:
16068     // It's OK to compile a module interface as a normal translation unit.
16069     break;
16070 
16071   case LangOptions::CMK_ModuleInterface:
16072     if (MDK != ModuleDeclKind::Implementation)
16073       break;
16074 
16075     // We were asked to compile a module interface unit but this is a module
16076     // implementation unit. That indicates the 'export' is missing.
16077     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16078       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16079     break;
16080 
16081   case LangOptions::CMK_ModuleMap:
16082     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16083     return nullptr;
16084   }
16085 
16086   // FIXME: Most of this work should be done by the preprocessor rather than
16087   // here, in order to support macro import.
16088 
16089   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16090   // modules, the dots here are just another character that can appear in a
16091   // module name.
16092   std::string ModuleName;
16093   for (auto &Piece : Path) {
16094     if (!ModuleName.empty())
16095       ModuleName += ".";
16096     ModuleName += Piece.first->getName();
16097   }
16098 
16099   // FIXME: If we've already seen a module-declaration, report an error.
16100 
16101   // If a module name was explicitly specified on the command line, it must be
16102   // correct.
16103   if (!getLangOpts().CurrentModule.empty() &&
16104       getLangOpts().CurrentModule != ModuleName) {
16105     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16106         << SourceRange(Path.front().second, Path.back().second)
16107         << getLangOpts().CurrentModule;
16108     return nullptr;
16109   }
16110   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16111 
16112   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16113   Module *Mod;
16114 
16115   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16116 
16117   switch (MDK) {
16118   case ModuleDeclKind::Module: {
16119     // We can't have parsed or imported a definition of this module or parsed a
16120     // module map defining it already.
16121     if (auto *M = Map.findModule(ModuleName)) {
16122       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16123       if (M->DefinitionLoc.isValid())
16124         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16125       else if (const auto *FE = M->getASTFile())
16126         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16127             << FE->getName();
16128       return nullptr;
16129     }
16130 
16131     // Create a Module for the module that we're defining.
16132     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16133                                            ModuleScopes.front().Module);
16134     assert(Mod && "module creation should not fail");
16135     break;
16136   }
16137 
16138   case ModuleDeclKind::Partition:
16139     // FIXME: Check we are in a submodule of the named module.
16140     return nullptr;
16141 
16142   case ModuleDeclKind::Implementation:
16143     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16144         PP.getIdentifierInfo(ModuleName), Path[0].second);
16145     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16146                                        /*IsIncludeDirective=*/false);
16147     if (!Mod)
16148       return nullptr;
16149     break;
16150   }
16151 
16152   // Switch from the global module to the named module.
16153   ModuleScopes.back().Module = Mod;
16154   VisibleModules.setVisible(Mod, ModuleLoc);
16155 
16156   // From now on, we have an owning module for all declarations we see.
16157   // However, those declarations are module-private unless explicitly
16158   // exported.
16159   auto *TU = Context.getTranslationUnitDecl();
16160   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16161   TU->setLocalOwningModule(Mod);
16162 
16163   // FIXME: Create a ModuleDecl.
16164   return nullptr;
16165 }
16166 
16167 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16168                                    SourceLocation ImportLoc,
16169                                    ModuleIdPath Path) {
16170   Module *Mod =
16171       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16172                                    /*IsIncludeDirective=*/false);
16173   if (!Mod)
16174     return true;
16175 
16176   VisibleModules.setVisible(Mod, ImportLoc);
16177 
16178   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16179 
16180   // FIXME: we should support importing a submodule within a different submodule
16181   // of the same top-level module. Until we do, make it an error rather than
16182   // silently ignoring the import.
16183   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16184   // warn on a redundant import of the current module?
16185   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16186       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16187     Diag(ImportLoc, getLangOpts().isCompilingModule()
16188                         ? diag::err_module_self_import
16189                         : diag::err_module_import_in_implementation)
16190         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16191 
16192   SmallVector<SourceLocation, 2> IdentifierLocs;
16193   Module *ModCheck = Mod;
16194   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16195     // If we've run out of module parents, just drop the remaining identifiers.
16196     // We need the length to be consistent.
16197     if (!ModCheck)
16198       break;
16199     ModCheck = ModCheck->Parent;
16200 
16201     IdentifierLocs.push_back(Path[I].second);
16202   }
16203 
16204   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16205   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16206                                           Mod, IdentifierLocs);
16207   if (!ModuleScopes.empty())
16208     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16209   TU->addDecl(Import);
16210   return Import;
16211 }
16212 
16213 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16214   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16215   BuildModuleInclude(DirectiveLoc, Mod);
16216 }
16217 
16218 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16219   // Determine whether we're in the #include buffer for a module. The #includes
16220   // in that buffer do not qualify as module imports; they're just an
16221   // implementation detail of us building the module.
16222   //
16223   // FIXME: Should we even get ActOnModuleInclude calls for those?
16224   bool IsInModuleIncludes =
16225       TUKind == TU_Module &&
16226       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16227 
16228   bool ShouldAddImport = !IsInModuleIncludes;
16229 
16230   // If this module import was due to an inclusion directive, create an
16231   // implicit import declaration to capture it in the AST.
16232   if (ShouldAddImport) {
16233     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16234     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16235                                                      DirectiveLoc, Mod,
16236                                                      DirectiveLoc);
16237     if (!ModuleScopes.empty())
16238       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16239     TU->addDecl(ImportD);
16240     Consumer.HandleImplicitImportDecl(ImportD);
16241   }
16242 
16243   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16244   VisibleModules.setVisible(Mod, DirectiveLoc);
16245 }
16246 
16247 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16248   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16249 
16250   ModuleScopes.push_back({});
16251   ModuleScopes.back().Module = Mod;
16252   if (getLangOpts().ModulesLocalVisibility)
16253     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16254 
16255   VisibleModules.setVisible(Mod, DirectiveLoc);
16256 
16257   // The enclosing context is now part of this module.
16258   // FIXME: Consider creating a child DeclContext to hold the entities
16259   // lexically within the module.
16260   if (getLangOpts().trackLocalOwningModule()) {
16261     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16262       cast<Decl>(DC)->setModuleOwnershipKind(
16263           getLangOpts().ModulesLocalVisibility
16264               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16265               : Decl::ModuleOwnershipKind::Visible);
16266       cast<Decl>(DC)->setLocalOwningModule(Mod);
16267     }
16268   }
16269 }
16270 
16271 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16272   if (getLangOpts().ModulesLocalVisibility) {
16273     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16274     // Leaving a module hides namespace names, so our visible namespace cache
16275     // is now out of date.
16276     VisibleNamespaceCache.clear();
16277   }
16278 
16279   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16280          "left the wrong module scope");
16281   ModuleScopes.pop_back();
16282 
16283   // We got to the end of processing a local module. Create an
16284   // ImportDecl as we would for an imported module.
16285   FileID File = getSourceManager().getFileID(EomLoc);
16286   SourceLocation DirectiveLoc;
16287   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16288     // We reached the end of a #included module header. Use the #include loc.
16289     assert(File != getSourceManager().getMainFileID() &&
16290            "end of submodule in main source file");
16291     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16292   } else {
16293     // We reached an EOM pragma. Use the pragma location.
16294     DirectiveLoc = EomLoc;
16295   }
16296   BuildModuleInclude(DirectiveLoc, Mod);
16297 
16298   // Any further declarations are in whatever module we returned to.
16299   if (getLangOpts().trackLocalOwningModule()) {
16300     // The parser guarantees that this is the same context that we entered
16301     // the module within.
16302     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16303       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16304       if (!getCurrentModule())
16305         cast<Decl>(DC)->setModuleOwnershipKind(
16306             Decl::ModuleOwnershipKind::Unowned);
16307     }
16308   }
16309 }
16310 
16311 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16312                                                       Module *Mod) {
16313   // Bail if we're not allowed to implicitly import a module here.
16314   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16315       VisibleModules.isVisible(Mod))
16316     return;
16317 
16318   // Create the implicit import declaration.
16319   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16320   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16321                                                    Loc, Mod, Loc);
16322   TU->addDecl(ImportD);
16323   Consumer.HandleImplicitImportDecl(ImportD);
16324 
16325   // Make the module visible.
16326   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16327   VisibleModules.setVisible(Mod, Loc);
16328 }
16329 
16330 /// We have parsed the start of an export declaration, including the '{'
16331 /// (if present).
16332 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16333                                  SourceLocation LBraceLoc) {
16334   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16335 
16336   // C++ Modules TS draft:
16337   //   An export-declaration shall appear in the purview of a module other than
16338   //   the global module.
16339   if (ModuleScopes.empty() ||
16340       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16341     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16342 
16343   //   An export-declaration [...] shall not contain more than one
16344   //   export keyword.
16345   //
16346   // The intent here is that an export-declaration cannot appear within another
16347   // export-declaration.
16348   if (D->isExported())
16349     Diag(ExportLoc, diag::err_export_within_export);
16350 
16351   CurContext->addDecl(D);
16352   PushDeclContext(S, D);
16353   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16354   return D;
16355 }
16356 
16357 /// Complete the definition of an export declaration.
16358 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16359   auto *ED = cast<ExportDecl>(D);
16360   if (RBraceLoc.isValid())
16361     ED->setRBraceLoc(RBraceLoc);
16362 
16363   // FIXME: Diagnose export of internal-linkage declaration (including
16364   // anonymous namespace).
16365 
16366   PopDeclContext();
16367   return D;
16368 }
16369 
16370 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16371                                       IdentifierInfo* AliasName,
16372                                       SourceLocation PragmaLoc,
16373                                       SourceLocation NameLoc,
16374                                       SourceLocation AliasNameLoc) {
16375   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16376                                          LookupOrdinaryName);
16377   AsmLabelAttr *Attr =
16378       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16379 
16380   // If a declaration that:
16381   // 1) declares a function or a variable
16382   // 2) has external linkage
16383   // already exists, add a label attribute to it.
16384   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16385     if (isDeclExternC(PrevDecl))
16386       PrevDecl->addAttr(Attr);
16387     else
16388       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16389           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16390   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16391   } else
16392     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16393 }
16394 
16395 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16396                              SourceLocation PragmaLoc,
16397                              SourceLocation NameLoc) {
16398   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16399 
16400   if (PrevDecl) {
16401     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16402   } else {
16403     (void)WeakUndeclaredIdentifiers.insert(
16404       std::pair<IdentifierInfo*,WeakInfo>
16405         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16406   }
16407 }
16408 
16409 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16410                                 IdentifierInfo* AliasName,
16411                                 SourceLocation PragmaLoc,
16412                                 SourceLocation NameLoc,
16413                                 SourceLocation AliasNameLoc) {
16414   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16415                                     LookupOrdinaryName);
16416   WeakInfo W = WeakInfo(Name, NameLoc);
16417 
16418   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16419     if (!PrevDecl->hasAttr<AliasAttr>())
16420       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16421         DeclApplyPragmaWeak(TUScope, ND, W);
16422   } else {
16423     (void)WeakUndeclaredIdentifiers.insert(
16424       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16425   }
16426 }
16427 
16428 Decl *Sema::getObjCDeclContext() const {
16429   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16430 }
16431